aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/app/app.qbs9
-rw-r--r--src/app/main.cpp28
-rw-r--r--src/libs/3rdparty/botan/botan.cpp2
-rw-r--r--src/libs/3rdparty/botan/botan.pri1
-rw-r--r--src/libs/3rdparty/cplusplus/Bind.cpp70
-rw-r--r--src/libs/3rdparty/cplusplus/Control.cpp2
-rw-r--r--src/libs/3rdparty/cplusplus/FullySpecifiedType.cpp22
-rw-r--r--src/libs/3rdparty/cplusplus/FullySpecifiedType.h2
-rw-r--r--src/libs/3rdparty/cplusplus/Lexer.cpp167
-rw-r--r--src/libs/3rdparty/cplusplus/Lexer.h9
-rw-r--r--src/libs/3rdparty/cplusplus/MemoryPool.cpp15
-rw-r--r--src/libs/3rdparty/cplusplus/MemoryPool.h16
-rw-r--r--src/libs/3rdparty/cplusplus/Parser.cpp44
-rw-r--r--src/libs/3rdparty/cplusplus/Parser.h4
-rw-r--r--src/libs/3rdparty/cplusplus/Scope.cpp12
-rw-r--r--src/libs/3rdparty/cplusplus/Scope.h8
-rw-r--r--src/libs/3rdparty/cplusplus/TranslationUnit.cpp5
-rw-r--r--src/libs/3rdparty/cplusplus/TranslationUnit.h5
-rw-r--r--src/libs/cplusplus/CppDocument.cpp25
-rw-r--r--src/libs/cplusplus/CppDocument.h31
-rw-r--r--src/libs/cplusplus/DependencyTable.cpp15
-rw-r--r--src/libs/cplusplus/DependencyTable.h9
-rw-r--r--src/libs/cplusplus/FastPreprocessor.cpp15
-rw-r--r--src/libs/cplusplus/FastPreprocessor.h1
-rw-r--r--src/libs/cplusplus/LookupContext.cpp38
-rw-r--r--src/libs/cplusplus/LookupContext.h3
-rw-r--r--src/libs/cplusplus/LookupItem.cpp2
-rw-r--r--src/libs/cplusplus/ResolveExpression.cpp2
-rw-r--r--src/libs/cplusplus/SimpleLexer.cpp4
-rw-r--r--src/libs/cplusplus/SimpleLexer.h4
-rw-r--r--src/libs/cplusplus/cplusplus_dependencies.pri2
-rw-r--r--src/libs/cplusplus/pp-engine.cpp7
-rw-r--r--src/libs/extensionsystem/iplugin.cpp14
-rw-r--r--src/libs/extensionsystem/iplugin.h1
-rw-r--r--src/libs/extensionsystem/pluginerroroverview.cpp6
-rw-r--r--src/libs/extensionsystem/pluginmanager.cpp396
-rw-r--r--src/libs/extensionsystem/pluginmanager.h3
-rw-r--r--src/libs/extensionsystem/pluginmanager_p.h13
-rw-r--r--src/libs/extensionsystem/pluginspec.cpp9
-rw-r--r--src/libs/extensionsystem/pluginspec.h7
-rw-r--r--src/libs/extensionsystem/pluginspec_p.h3
-rw-r--r--src/libs/extensionsystem/pluginview.cpp524
-rw-r--r--src/libs/extensionsystem/pluginview.h43
-rw-r--r--src/libs/glsl/glslengine.cpp2
-rw-r--r--src/libs/glsl/glslmemorypool.cpp15
-rw-r--r--src/libs/glsl/glslmemorypool.h15
-rw-r--r--src/libs/glsl/glslsemantic.cpp4
-rw-r--r--src/libs/libs.pro3
-rw-r--r--src/libs/libs.qbs1
-rw-r--r--src/libs/qmleditorwidgets/contextpanetextwidget.cpp65
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidget.cpp47
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetimage.cpp60
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp34
-rw-r--r--src/libs/qmleditorwidgets/customcolordialog.cpp26
-rw-r--r--src/libs/qmleditorwidgets/filewidget.cpp6
-rw-r--r--src/libs/qmleditorwidgets/fontsizespinbox.cpp3
-rw-r--r--src/libs/qmljs/qmljsmodelmanagerinterface.cpp5
-rw-r--r--src/libs/qmljs/qmljsmodelmanagerinterface.h2
-rw-r--r--src/libs/qmljs/qmljsstaticanalysismessage.cpp2
-rw-r--r--src/libs/qmljs/qmljstypedescriptionreader.cpp2
-rw-r--r--src/libs/qtcreatorcdbext/gdbmihelpers.cpp30
-rw-r--r--src/libs/qtcreatorcdbext/gdbmihelpers.h1
-rw-r--r--src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp4
-rw-r--r--src/libs/ssh/sftpchannel.cpp24
-rw-r--r--src/libs/ssh/sftpfilesystemmodel.cpp6
-rw-r--r--src/libs/ssh/sftpincomingpacket.cpp12
-rw-r--r--src/libs/ssh/sftpoperation.cpp4
-rw-r--r--src/libs/ssh/sftpoperation_p.h2
-rw-r--r--src/libs/ssh/ssh.pro6
-rw-r--r--src/libs/ssh/ssh.qbs2
-rw-r--r--src/libs/ssh/sshchannel.cpp18
-rw-r--r--src/libs/ssh/sshchannel_p.h5
-rw-r--r--src/libs/ssh/sshchannelmanager.cpp2
-rw-r--r--src/libs/ssh/sshconnection.cpp17
-rw-r--r--src/libs/ssh/sshconnection.h10
-rw-r--r--src/libs/ssh/sshconnectionmanager.cpp67
-rw-r--r--src/libs/ssh/sshcryptofacility.cpp8
-rw-r--r--src/libs/ssh/sshdirecttcpiptunnel.cpp4
-rw-r--r--src/libs/ssh/sshhostkeydatabase.cpp120
-rw-r--r--src/libs/ssh/sshhostkeydatabase.h73
-rw-r--r--src/libs/ssh/sshincomingpacket.cpp32
-rw-r--r--src/libs/ssh/sshkeycreationdialog.cpp12
-rw-r--r--src/libs/ssh/sshkeyexchange.cpp43
-rw-r--r--src/libs/ssh/sshkeyexchange_p.h8
-rw-r--r--src/libs/ssh/sshkeygenerator.cpp6
-rw-r--r--src/libs/ssh/sshremoteprocess.cpp29
-rw-r--r--src/libs/ssh/sshremoteprocessrunner.cpp9
-rw-r--r--src/libs/timeline/README34
-rw-r--r--src/libs/timeline/qml/ButtonsBar.qml (renamed from src/plugins/qmlprofiler/qml/ButtonsBar.qml)14
-rw-r--r--src/libs/timeline/qml/CategoryLabel.qml245
-rw-r--r--src/libs/timeline/qml/Detail.qml (renamed from src/plugins/qmlprofiler/qml/Detail.qml)0
-rw-r--r--src/libs/timeline/qml/MainView.qml472
-rw-r--r--src/libs/timeline/qml/Overview.qml197
-rw-r--r--src/libs/timeline/qml/RangeDetails.qml (renamed from src/plugins/qmlprofiler/qml/RangeDetails.qml)65
-rw-r--r--src/libs/timeline/qml/RangeMover.qml (renamed from src/plugins/qmlprofiler/qml/RangeMover.qml)0
-rw-r--r--src/libs/timeline/qml/RowLabel.qml83
-rw-r--r--src/libs/timeline/qml/SelectionRange.qml (renamed from src/plugins/qmlprofiler/qml/SelectionRange.qml)79
-rw-r--r--src/libs/timeline/qml/SelectionRangeDetails.qml (renamed from src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml)52
-rw-r--r--src/libs/timeline/qml/SynchronousReloader.qml43
-rw-r--r--src/libs/timeline/qml/TimeDisplay.qml187
-rw-r--r--src/libs/timeline/qml/TimeMarks.qml147
-rw-r--r--src/libs/timeline/qml/TimelineContent.qml215
-rw-r--r--src/libs/timeline/qml/TimelineLabels.qml174
-rw-r--r--src/libs/timeline/qml/arrow_down.png (renamed from src/plugins/qmlprofiler/qml/arrow_down.png)bin140 -> 140 bytes
-rw-r--r--src/libs/timeline/qml/arrow_right.png (renamed from src/plugins/qmlprofiler/qml/arrow_right.png)bin144 -> 144 bytes
-rw-r--r--src/libs/timeline/qml/dialog_shadow.png (renamed from src/plugins/qmlprofiler/qml/dialog_shadow.png)bin664 -> 664 bytes
-rw-r--r--src/libs/timeline/qml/ico_edit.png (renamed from src/plugins/qmlprofiler/qml/ico_edit.png)bin164 -> 164 bytes
-rw-r--r--src/libs/timeline/qml/ico_filter.png (renamed from src/plugins/qmlprofiler/qml/ico_filter.png)bin335 -> 335 bytes
-rw-r--r--src/libs/timeline/qml/ico_next.png (renamed from src/plugins/qmlprofiler/qml/ico_next.png)bin715 -> 715 bytes
-rw-r--r--src/libs/timeline/qml/ico_note.png (renamed from src/plugins/qmlprofiler/qml/ico_note.png)bin117 -> 117 bytes
-rw-r--r--src/libs/timeline/qml/ico_prev.png (renamed from src/plugins/qmlprofiler/qml/ico_prev.png)bin745 -> 745 bytes
-rw-r--r--src/libs/timeline/qml/ico_rangeselected.png (renamed from src/plugins/qmlprofiler/qml/ico_rangeselected.png)bin233 -> 233 bytes
-rw-r--r--src/libs/timeline/qml/ico_rangeselection.png (renamed from src/plugins/qmlprofiler/qml/ico_rangeselection.png)bin224 -> 224 bytes
-rw-r--r--src/libs/timeline/qml/ico_selectionmode.png (renamed from src/plugins/qmlprofiler/qml/ico_selectionmode.png)bin328 -> 328 bytes
-rw-r--r--src/libs/timeline/qml/ico_zoom.png (renamed from src/plugins/qmlprofiler/qml/ico_zoom.png)bin584 -> 584 bytes
-rw-r--r--src/libs/timeline/qml/lock_closed.png (renamed from src/plugins/qmlprofiler/qml/lock_closed.png)bin276 -> 276 bytes
-rw-r--r--src/libs/timeline/qml/lock_open.png (renamed from src/plugins/qmlprofiler/qml/lock_open.png)bin265 -> 265 bytes
-rw-r--r--src/libs/timeline/qml/notes.frag37
-rw-r--r--src/libs/timeline/qml/notes.vert (renamed from src/plugins/qmldesigner/qmldesignerwarning.cpp)19
-rw-r--r--src/libs/timeline/qml/range_handle.png (renamed from src/plugins/qmlprofiler/qml/range_handle.png)bin197 -> 197 bytes
-rw-r--r--src/libs/timeline/qml/timeline.qrc38
-rw-r--r--src/libs/timeline/qml/timelineitems.frag46
-rw-r--r--src/libs/timeline/qml/timelineitems.vert64
-rw-r--r--src/libs/timeline/timeline.pro45
-rw-r--r--src/libs/timeline/timeline.qbs39
-rw-r--r--src/libs/timeline/timeline_dependencies.pri4
-rw-r--r--src/libs/timeline/timeline_global.h43
-rw-r--r--src/libs/timeline/timelineabstractrenderer.cpp205
-rw-r--r--src/libs/timeline/timelineabstractrenderer.h100
-rw-r--r--src/libs/timeline/timelineabstractrenderer_p.h58
-rw-r--r--src/libs/timeline/timelineitemsrenderpass.cpp461
-rw-r--r--src/libs/timeline/timelineitemsrenderpass.h53
-rw-r--r--src/libs/timeline/timelinemodel.cpp664
-rw-r--r--src/libs/timeline/timelinemodel.h156
-rw-r--r--src/libs/timeline/timelinemodel_p.h155
-rw-r--r--src/libs/timeline/timelinemodelaggregator.cpp230
-rw-r--r--src/libs/timeline/timelinemodelaggregator.h77
-rw-r--r--src/libs/timeline/timelinenotesmodel.cpp225
-rw-r--r--src/libs/timeline/timelinenotesmodel.h85
-rw-r--r--src/libs/timeline/timelinenotesmodel_p.h65
-rw-r--r--src/libs/timeline/timelinenotesrenderpass.cpp265
-rw-r--r--src/libs/timeline/timelinenotesrenderpass.h (renamed from src/plugins/qmlprofiler/abstracttimelinemodel_p.h)38
-rw-r--r--src/libs/timeline/timelineoverviewrenderer.cpp91
-rw-r--r--src/libs/timeline/timelineoverviewrenderer.h55
-rw-r--r--src/libs/timeline/timelineoverviewrenderer_p.h49
-rw-r--r--src/libs/timeline/timelinerenderer.cpp305
-rw-r--r--src/libs/timeline/timelinerenderer.h82
-rw-r--r--src/libs/timeline/timelinerenderer_p.h73
-rw-r--r--src/libs/timeline/timelinerenderpass.cpp63
-rw-r--r--src/libs/timeline/timelinerenderpass.h63
-rw-r--r--src/libs/timeline/timelinerenderstate.cpp248
-rw-r--r--src/libs/timeline/timelinerenderstate.h77
-rw-r--r--src/libs/timeline/timelinerenderstate_p.h56
-rw-r--r--src/libs/timeline/timelineselectionrenderpass.cpp150
-rw-r--r--src/libs/timeline/timelineselectionrenderpass.h56
-rw-r--r--src/libs/timeline/timelinezoomcontrol.cpp173
-rw-r--r--src/libs/timeline/timelinezoomcontrol.h108
-rw-r--r--src/libs/utils/algorithm.h2
-rw-r--r--src/libs/utils/basetreeview.cpp96
-rw-r--r--src/libs/utils/basetreeview.h3
-rw-r--r--src/libs/utils/checkablemessagebox.cpp115
-rw-r--r--src/libs/utils/checkablemessagebox.h10
-rw-r--r--src/libs/utils/elfreader.cpp2
-rw-r--r--src/libs/utils/fadingindicator.cpp146
-rw-r--r--src/libs/utils/fadingindicator.h50
-rw-r--r--src/libs/utils/fancymainwindow.cpp11
-rw-r--r--src/libs/utils/fileinprojectfinder.cpp66
-rw-r--r--src/libs/utils/fileinprojectfinder.h4
-rw-r--r--src/libs/utils/fileutils.cpp57
-rw-r--r--src/libs/utils/fileutils.h14
-rw-r--r--src/libs/utils/images/progressindicator_big.pngbin0 -> 1443 bytes
-rw-r--r--src/libs/utils/images/progressindicator_big@2x.pngbin0 -> 2449 bytes
-rw-r--r--src/libs/utils/images/progressindicator_medium.pngbin0 -> 875 bytes
-rw-r--r--src/libs/utils/images/progressindicator_medium@2x.pngbin0 -> 1541 bytes
-rw-r--r--src/libs/utils/images/progressindicator_small.pngbin0 -> 305 bytes
-rw-r--r--src/libs/utils/images/progressindicator_small@2x.pngbin0 -> 397 bytes
-rw-r--r--src/libs/utils/macroexpander.cpp2
-rw-r--r--src/libs/utils/outputformatter.cpp11
-rw-r--r--src/libs/utils/outputformatter.h2
-rw-r--r--src/libs/utils/persistentsettings.cpp4
-rw-r--r--src/libs/utils/persistentsettings.h2
-rw-r--r--src/libs/utils/portlist.cpp2
-rw-r--r--src/libs/utils/progressindicator.cpp140
-rw-r--r--src/libs/utils/progressindicator.h82
-rw-r--r--src/libs/utils/projectintropage.cpp6
-rw-r--r--src/libs/utils/reloadpromptutils.cpp7
-rw-r--r--src/libs/utils/reloadpromptutils.h3
-rw-r--r--src/libs/utils/synchronousprocess.cpp2
-rw-r--r--src/libs/utils/theme/theme.cpp2
-rw-r--r--src/libs/utils/tooltip/tipcontents.cpp196
-rw-r--r--src/libs/utils/tooltip/tipcontents.h130
-rw-r--r--src/libs/utils/tooltip/tips.cpp127
-rw-r--r--src/libs/utils/tooltip/tips.h74
-rw-r--r--src/libs/utils/tooltip/tooltip.cpp96
-rw-r--r--src/libs/utils/tooltip/tooltip.h31
-rw-r--r--src/libs/utils/treemodel.cpp926
-rw-r--r--src/libs/utils/treemodel.h224
-rw-r--r--src/libs/utils/unixutils.cpp5
-rw-r--r--src/libs/utils/utils-lib.pri12
-rw-r--r--src/libs/utils/utils.qbs12
-rw-r--r--src/libs/utils/utils.qrc6
-rw-r--r--src/libs/utils/wizard.cpp6
-rw-r--r--src/libs/utils/wizardpage.h4
-rw-r--r--src/plugins/analyzerbase/analyzermanager.cpp2
-rw-r--r--src/plugins/analyzerbase/analyzerrunconfigwidget.cpp5
-rw-r--r--src/plugins/analyzerbase/analyzerruncontrol.cpp5
-rw-r--r--src/plugins/analyzerbase/analyzerutils.cpp10
-rw-r--r--src/plugins/analyzerbase/detailederrorview.cpp44
-rw-r--r--src/plugins/analyzerbase/detailederrorview.h11
-rw-r--r--src/plugins/analyzerbase/startremotedialog.cpp12
-rw-r--r--src/plugins/android/androidanalyzesupport.cpp2
-rw-r--r--src/plugins/android/androidbuildapkwidget.ui2
-rw-r--r--src/plugins/android/androidconfigurations.cpp58
-rw-r--r--src/plugins/android/androidconfigurations.h4
-rw-r--r--src/plugins/android/androiddebugsupport.cpp45
-rw-r--r--src/plugins/android/androiddebugsupport.h6
-rw-r--r--src/plugins/android/androiddeployconfiguration.cpp5
-rw-r--r--src/plugins/android/androiddeployconfiguration.h3
-rw-r--r--src/plugins/android/androiddeployqtstep.cpp230
-rw-r--r--src/plugins/android/androiddeployqtstep.h30
-rw-r--r--src/plugins/android/androidmanifestdocument.cpp6
-rw-r--r--src/plugins/android/androidmanifesteditor.cpp2
-rw-r--r--src/plugins/android/androidmanifesteditorwidget.cpp27
-rw-r--r--src/plugins/android/androidmanifesteditorwidget.h9
-rw-r--r--src/plugins/android/androidpotentialkit.cpp2
-rw-r--r--src/plugins/android/androidqtsupport.h2
-rw-r--r--src/plugins/android/androidqtversion.cpp12
-rw-r--r--src/plugins/android/androidrunfactories.cpp7
-rw-r--r--src/plugins/android/androidsettingswidget.cpp63
-rw-r--r--src/plugins/android/androidsettingswidget.h9
-rw-r--r--src/plugins/android/androidsettingswidget.ui66
-rw-r--r--src/plugins/android/androidtoolchain.cpp30
-rw-r--r--src/plugins/android/javaeditor.cpp6
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp10
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp3
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsopenprojectwizard.cpp2
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsproject.cpp16
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp2
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp6
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h2
-rw-r--r--src/plugins/autotoolsprojectmanager/makefileparser.cpp2
-rw-r--r--src/plugins/autotoolsprojectmanager/makefileparserthread.cpp3
-rw-r--r--src/plugins/autotoolsprojectmanager/makestep.cpp2
-rw-r--r--src/plugins/baremetal/baremetal.pro26
-rw-r--r--src/plugins/baremetal/baremetal.qbs11
-rw-r--r--src/plugins/baremetal/baremetal.qrc5
-rw-r--r--src/plugins/baremetal/baremetalconstants.h13
-rw-r--r--src/plugins/baremetal/baremetalcustomrunconfiguration.cpp201
-rw-r--r--src/plugins/baremetal/baremetalcustomrunconfiguration.h72
-rw-r--r--src/plugins/baremetal/baremetaldebugsupport.cpp202
-rw-r--r--src/plugins/baremetal/baremetaldebugsupport.h91
-rw-r--r--src/plugins/baremetal/baremetaldevice.cpp77
-rw-r--r--src/plugins/baremetal/baremetaldevice.h17
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp88
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwidget.h20
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp23
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp79
-rw-r--r--src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h19
-rw-r--r--src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp2
-rw-r--r--src/plugins/baremetal/baremetalplugin.cpp11
-rw-r--r--src/plugins/baremetal/baremetalplugin.h4
-rw-r--r--src/plugins/baremetal/baremetalrunconfiguration.cpp4
-rw-r--r--src/plugins/baremetal/baremetalrunconfiguration.h2
-rw-r--r--src/plugins/baremetal/baremetalrunconfigurationfactory.cpp21
-rw-r--r--src/plugins/baremetal/baremetalruncontrolfactory.cpp142
-rw-r--r--src/plugins/baremetal/baremetalruncontrolfactory.h2
-rw-r--r--src/plugins/baremetal/defaultgdbserverprovider.cpp211
-rw-r--r--src/plugins/baremetal/defaultgdbserverprovider.h106
-rw-r--r--src/plugins/baremetal/gdbserverprovider.cpp414
-rw-r--r--src/plugins/baremetal/gdbserverprovider.h208
-rw-r--r--src/plugins/baremetal/gdbserverproviderchooser.cpp124
-rw-r--r--src/plugins/baremetal/gdbserverproviderchooser.h83
-rw-r--r--src/plugins/baremetal/gdbserverprovidermanager.cpp215
-rw-r--r--src/plugins/baremetal/gdbserverprovidermanager.h92
-rw-r--r--src/plugins/baremetal/gdbserverproviderprocess.cpp134
-rw-r--r--src/plugins/baremetal/gdbserverproviderprocess.h73
-rw-r--r--src/plugins/baremetal/gdbserverproviderssettingspage.cpp621
-rw-r--r--src/plugins/baremetal/gdbserverproviderssettingspage.h149
-rw-r--r--src/plugins/baremetal/images/QtBareMetal.pngbin0 -> 5204 bytes
-rw-r--r--src/plugins/baremetal/openocdgdbserverprovider.cpp371
-rw-r--r--src/plugins/baremetal/openocdgdbserverprovider.h125
-rw-r--r--src/plugins/baremetal/stlinkutilgdbserverprovider.cpp407
-rw-r--r--src/plugins/baremetal/stlinkutilgdbserverprovider.h137
-rw-r--r--src/plugins/bazaar/bazaarclient.cpp165
-rw-r--r--src/plugins/bazaar/bazaarclient.h6
-rw-r--r--src/plugins/bazaar/bazaarcontrol.cpp16
-rw-r--r--src/plugins/bazaar/bazaarcontrol.h2
-rw-r--r--src/plugins/bazaar/bazaarplugin.cpp50
-rw-r--r--src/plugins/bazaar/clonewizard.cpp15
-rw-r--r--src/plugins/bazaar/uncommitdialog.cpp4
-rw-r--r--src/plugins/beautifier/artisticstyle/artisticstyle.cpp6
-rw-r--r--src/plugins/beautifier/beautifierplugin.cpp19
-rw-r--r--src/plugins/beautifier/clangformat/clangformat.cpp10
-rw-r--r--src/plugins/beautifier/configurationdialog.cpp2
-rw-r--r--src/plugins/beautifier/configurationeditor.cpp8
-rw-r--r--src/plugins/beautifier/configurationpanel.cpp9
-rw-r--r--src/plugins/beautifier/uncrustify/uncrustify.cpp6
-rw-r--r--src/plugins/bineditor/bineditor.cpp3
-rw-r--r--src/plugins/bineditor/bineditorplugin.cpp59
-rw-r--r--src/plugins/bookmarks/bookmarkmanager.cpp29
-rw-r--r--src/plugins/bookmarks/bookmarksplugin.cpp6
-rw-r--r--src/plugins/clangcodemodel/clangcodemodelplugin.cpp35
-rw-r--r--src/plugins/clangcodemodel/clangcodemodelplugin.h9
-rw-r--r--src/plugins/clangcodemodel/clangcompleter.cpp19
-rw-r--r--src/plugins/clangcodemodel/clangcompletion.cpp56
-rw-r--r--src/plugins/clangcodemodel/clangcompletion.h9
-rw-r--r--src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp4
-rw-r--r--src/plugins/clangcodemodel/clangmodelmanagersupport.cpp2
-rw-r--r--src/plugins/clangcodemodel/clangutils.cpp33
-rw-r--r--src/plugins/clangcodemodel/indexer.cpp28
-rw-r--r--src/plugins/classview/classviewmanager.cpp6
-rw-r--r--src/plugins/classview/classviewparser.cpp33
-rw-r--r--src/plugins/clearcase/activityselector.cpp17
-rw-r--r--src/plugins/clearcase/checkoutdialog.cpp2
-rw-r--r--src/plugins/clearcase/clearcasecontrol.cpp12
-rw-r--r--src/plugins/clearcase/clearcasecontrol.h2
-rw-r--r--src/plugins/clearcase/clearcaseplugin.cpp58
-rw-r--r--src/plugins/clearcase/clearcaseplugin.h1
-rw-r--r--src/plugins/clearcase/clearcasesubmiteditor.cpp2
-rw-r--r--src/plugins/clearcase/clearcasesubmiteditorwidget.cpp4
-rw-r--r--src/plugins/clearcase/settingspage.cpp2
-rw-r--r--src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp34
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditor.cpp10
-rw-r--r--src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp1
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeproject.cpp88
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeproject.h8
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp8
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectnodes.h1
-rw-r--r--src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp22
-rw-r--r--src/plugins/cmakeprojectmanager/cmaketool.cpp3
-rw-r--r--src/plugins/coreplugin/actionmanager/actioncontainer.cpp14
-rw-r--r--src/plugins/coreplugin/actionmanager/actioncontainer_p.h6
-rw-r--r--src/plugins/coreplugin/actionmanager/actionmanager.cpp71
-rw-r--r--src/plugins/coreplugin/actionmanager/actionmanager.h14
-rw-r--r--src/plugins/coreplugin/actionmanager/actionmanager_p.h5
-rw-r--r--src/plugins/coreplugin/actionmanager/command.cpp31
-rw-r--r--src/plugins/coreplugin/actionmanager/command_p.h2
-rw-r--r--src/plugins/coreplugin/actionmanager/commandbutton.h2
-rw-r--r--src/plugins/coreplugin/actionmanager/commandmappings.h2
-rw-r--r--src/plugins/coreplugin/actionmanager/commandsfile.cpp2
-rw-r--r--src/plugins/coreplugin/basefilewizardfactory.cpp7
-rw-r--r--src/plugins/coreplugin/basefilewizardfactory.h6
-rw-r--r--src/plugins/coreplugin/corejsextensions.cpp2
-rw-r--r--src/plugins/coreplugin/coreplugin.cpp13
-rw-r--r--src/plugins/coreplugin/coreplugin.pro8
-rw-r--r--src/plugins/coreplugin/coreplugin.qbs10
-rw-r--r--src/plugins/coreplugin/designmode.cpp20
-rw-r--r--src/plugins/coreplugin/designmode.h6
-rw-r--r--src/plugins/coreplugin/dialogs/externaltoolconfig.cpp63
-rw-r--r--src/plugins/coreplugin/dialogs/externaltoolconfig.h17
-rw-r--r--src/plugins/coreplugin/dialogs/externaltoolconfig.ui38
-rw-r--r--src/plugins/coreplugin/dialogs/ioptionspage.h6
-rw-r--r--src/plugins/coreplugin/dialogs/newdialog.cpp4
-rw-r--r--src/plugins/coreplugin/dialogs/openwithdialog.cpp5
-rw-r--r--src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp4
-rw-r--r--src/plugins/coreplugin/dialogs/saveitemsdialog.cpp2
-rw-r--r--src/plugins/coreplugin/dialogs/saveitemsdialog.h7
-rw-r--r--src/plugins/coreplugin/dialogs/settingsdialog.cpp4
-rw-r--r--src/plugins/coreplugin/dialogs/shortcutsettings.cpp14
-rw-r--r--src/plugins/coreplugin/dialogs/shortcutsettings.h2
-rw-r--r--src/plugins/coreplugin/documentmanager.cpp138
-rw-r--r--src/plugins/coreplugin/documentmanager.h13
-rw-r--r--src/plugins/coreplugin/editmode.cpp15
-rw-r--r--src/plugins/coreplugin/editmode.h7
-rw-r--r--src/plugins/coreplugin/editormanager/documentmodel.cpp15
-rw-r--r--src/plugins/coreplugin/editormanager/editormanager.cpp187
-rw-r--r--src/plugins/coreplugin/editormanager/editormanager.h9
-rw-r--r--src/plugins/coreplugin/editormanager/editormanager_p.h14
-rw-r--r--src/plugins/coreplugin/editormanager/editorview.cpp50
-rw-r--r--src/plugins/coreplugin/editormanager/editorview.h9
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsview.cpp4
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsview.h10
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorswindow.cpp4
-rw-r--r--src/plugins/coreplugin/editortoolbar.cpp13
-rw-r--r--src/plugins/coreplugin/editortoolbar.h6
-rw-r--r--src/plugins/coreplugin/externaltool.cpp353
-rw-r--r--src/plugins/coreplugin/externaltool.h5
-rw-r--r--src/plugins/coreplugin/externaltoolmanager.cpp343
-rw-r--r--src/plugins/coreplugin/fancyactionbar.cpp21
-rw-r--r--src/plugins/coreplugin/fancytabwidget.cpp20
-rw-r--r--src/plugins/coreplugin/featureprovider.h2
-rw-r--r--src/plugins/coreplugin/fileutils.cpp2
-rw-r--r--src/plugins/coreplugin/find/basetextfind.h2
-rw-r--r--src/plugins/coreplugin/find/currentdocumentfind.cpp15
-rw-r--r--src/plugins/coreplugin/find/findplugin.cpp35
-rw-r--r--src/plugins/coreplugin/find/findplugin.h4
-rw-r--r--src/plugins/coreplugin/find/findtoolbar.cpp159
-rw-r--r--src/plugins/coreplugin/find/findtoolbar.h2
-rw-r--r--src/plugins/coreplugin/find/findtoolwindow.cpp4
-rw-r--r--src/plugins/coreplugin/find/ifindsupport.cpp63
-rw-r--r--src/plugins/coreplugin/find/itemviewfind.cpp2
-rw-r--r--src/plugins/coreplugin/find/searchresulttreeview.cpp3
-rw-r--r--src/plugins/coreplugin/find/searchresultwidget.cpp26
-rw-r--r--src/plugins/coreplugin/find/searchresultwidget.h4
-rw-r--r--src/plugins/coreplugin/find/searchresultwindow.cpp16
-rw-r--r--src/plugins/coreplugin/find/searchresultwindow.h2
-rw-r--r--src/plugins/coreplugin/generalsettings.cpp8
-rw-r--r--src/plugins/coreplugin/helpmanager.cpp171
-rw-r--r--src/plugins/coreplugin/helpmanager.h9
-rw-r--r--src/plugins/coreplugin/icore.cpp2
-rw-r--r--src/plugins/coreplugin/idocument.cpp117
-rw-r--r--src/plugins/coreplugin/idocument.h32
-rw-r--r--src/plugins/coreplugin/infobar.cpp2
-rw-r--r--src/plugins/coreplugin/iversioncontrol.h23
-rw-r--r--src/plugins/coreplugin/iwelcomepage.cpp (renamed from src/libs/utils/iwelcomepage.cpp)4
-rw-r--r--src/plugins/coreplugin/iwelcomepage.h (renamed from src/libs/utils/iwelcomepage.h)22
-rw-r--r--src/plugins/coreplugin/iwizardfactory.cpp6
-rw-r--r--src/plugins/coreplugin/iwizardfactory.h2
-rw-r--r--src/plugins/coreplugin/locator/basefilefilter.cpp199
-rw-r--r--src/plugins/coreplugin/locator/basefilefilter.h55
-rw-r--r--src/plugins/coreplugin/locator/commandlocator.cpp12
-rw-r--r--src/plugins/coreplugin/locator/commandlocator.h8
-rw-r--r--src/plugins/coreplugin/locator/directoryfilter.cpp39
-rw-r--r--src/plugins/coreplugin/locator/directoryfilter.h4
-rw-r--r--src/plugins/coreplugin/locator/executefilter.cpp3
-rw-r--r--src/plugins/coreplugin/locator/executefilter.h6
-rw-r--r--src/plugins/coreplugin/locator/filesystemfilter.cpp5
-rw-r--r--src/plugins/coreplugin/locator/filesystemfilter.h6
-rw-r--r--src/plugins/coreplugin/locator/ilocatorfilter.cpp8
-rw-r--r--src/plugins/coreplugin/locator/ilocatorfilter.h10
-rw-r--r--src/plugins/coreplugin/locator/locator.cpp71
-rw-r--r--src/plugins/coreplugin/locator/locator.h7
-rw-r--r--src/plugins/coreplugin/locator/locator.pri12
-rw-r--r--src/plugins/coreplugin/locator/locator_test.cpp4
-rw-r--r--src/plugins/coreplugin/locator/locatorconstants.h1
-rw-r--r--src/plugins/coreplugin/locator/locatorfiltersfilter.cpp14
-rw-r--r--src/plugins/coreplugin/locator/locatorfiltersfilter.h2
-rw-r--r--src/plugins/coreplugin/locator/locatorfiltertest.cpp3
-rw-r--r--src/plugins/coreplugin/locator/locatorfiltertest.h6
-rw-r--r--src/plugins/coreplugin/locator/locatorsearchutils.cpp11
-rw-r--r--src/plugins/coreplugin/locator/locatorsettingspage.cpp (renamed from src/plugins/coreplugin/locator/settingspage.cpp)48
-rw-r--r--src/plugins/coreplugin/locator/locatorsettingspage.h (renamed from src/plugins/coreplugin/locator/settingspage.h)12
-rw-r--r--src/plugins/coreplugin/locator/locatorsettingspage.ui (renamed from src/plugins/coreplugin/locator/settingspage.ui)0
-rw-r--r--src/plugins/coreplugin/locator/locatorwidget.cpp111
-rw-r--r--src/plugins/coreplugin/locator/locatorwidget.h9
-rw-r--r--src/plugins/coreplugin/locator/opendocumentsfilter.cpp3
-rw-r--r--src/plugins/coreplugin/locator/opendocumentsfilter.h10
-rw-r--r--src/plugins/coreplugin/mainwindow.cpp53
-rw-r--r--src/plugins/coreplugin/mainwindow.h11
-rw-r--r--src/plugins/coreplugin/manhattanstyle.cpp56
-rw-r--r--src/plugins/coreplugin/messagebox.cpp72
-rw-r--r--src/plugins/coreplugin/messagebox.h50
-rw-r--r--src/plugins/coreplugin/messagemanager.cpp4
-rw-r--r--src/plugins/coreplugin/messageoutputwindow.cpp10
-rw-r--r--src/plugins/coreplugin/messageoutputwindow.h2
-rw-r--r--src/plugins/coreplugin/mimedatabase.cpp2
-rw-r--r--src/plugins/coreplugin/mimetypemagicdialog.cpp8
-rw-r--r--src/plugins/coreplugin/mimetypesettings.cpp8
-rw-r--r--src/plugins/coreplugin/navigationsubwidget.cpp35
-rw-r--r--src/plugins/coreplugin/navigationsubwidget.h14
-rw-r--r--src/plugins/coreplugin/navigationwidget.cpp37
-rw-r--r--src/plugins/coreplugin/navigationwidget.h13
-rw-r--r--src/plugins/coreplugin/outputpane.cpp18
-rw-r--r--src/plugins/coreplugin/outputpane.h6
-rw-r--r--src/plugins/coreplugin/outputpanemanager.cpp32
-rw-r--r--src/plugins/coreplugin/outputwindow.cpp22
-rw-r--r--src/plugins/coreplugin/outputwindow.h4
-rw-r--r--src/plugins/coreplugin/patchtool.cpp6
-rw-r--r--src/plugins/coreplugin/plugindialog.cpp47
-rw-r--r--src/plugins/coreplugin/plugindialog.h5
-rw-r--r--src/plugins/coreplugin/progressmanager/futureprogress.cpp4
-rw-r--r--src/plugins/coreplugin/progressmanager/progressbar.cpp12
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager.cpp10
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager.h4
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager_p.h2
-rw-r--r--src/plugins/coreplugin/rightpane.cpp9
-rw-r--r--src/plugins/coreplugin/rightpane.h8
-rw-r--r--src/plugins/coreplugin/sidebar.cpp17
-rw-r--r--src/plugins/coreplugin/sidebar.h4
-rw-r--r--src/plugins/coreplugin/sidebarwidget.cpp23
-rw-r--r--src/plugins/coreplugin/sidebarwidget.h5
-rw-r--r--src/plugins/coreplugin/testdatadir.cpp5
-rw-r--r--src/plugins/coreplugin/testdatadir.h5
-rw-r--r--src/plugins/coreplugin/themesettings.cpp8
-rw-r--r--src/plugins/coreplugin/themesettingswidget.cpp6
-rw-r--r--src/plugins/coreplugin/toolsettings.cpp8
-rw-r--r--src/plugins/coreplugin/variablechooser.cpp6
-rw-r--r--src/plugins/coreplugin/vcsmanager.cpp37
-rw-r--r--src/plugins/coreplugin/vcsmanager.h8
-rw-r--r--src/plugins/coreplugin/windowsupport.cpp14
-rw-r--r--src/plugins/coreplugin/windowsupport.h1
-rw-r--r--src/plugins/cpaster/cpasterplugin.cpp40
-rw-r--r--src/plugins/cpaster/frontend/argumentscollector.cpp5
-rw-r--r--src/plugins/cpaster/kdepasteprotocol.cpp8
-rw-r--r--src/plugins/cpaster/pastebindotcaprotocol.cpp8
-rw-r--r--src/plugins/cpaster/pastebindotcomprotocol.cpp6
-rw-r--r--src/plugins/cpaster/pasteview.cpp6
-rw-r--r--src/plugins/cpaster/protocol.cpp2
-rw-r--r--src/plugins/cpaster/urlopenprotocol.cpp3
-rw-r--r--src/plugins/cppeditor/cppcodemodelinspectordialog.cpp142
-rw-r--r--src/plugins/cppeditor/cppdocumentationcommenthelper.cpp144
-rw-r--r--src/plugins/cppeditor/cppdocumentationcommenthelper.h25
-rw-r--r--src/plugins/cppeditor/cppdoxygen_test.cpp168
-rw-r--r--src/plugins/cppeditor/cppdoxygen_test.h (renamed from src/plugins/genericprojectmanager/cppmodelmanagerhelper.h)43
-rw-r--r--src/plugins/cppeditor/cppeditor.cpp57
-rw-r--r--src/plugins/cppeditor/cppeditor.h16
-rw-r--r--src/plugins/cppeditor/cppeditor.pro3
-rw-r--r--src/plugins/cppeditor/cppeditor.qbs3
-rw-r--r--src/plugins/cppeditor/cppeditordocument.cpp28
-rw-r--r--src/plugins/cppeditor/cppeditordocument.h6
-rw-r--r--src/plugins/cppeditor/cppeditorplugin.cpp60
-rw-r--r--src/plugins/cppeditor/cppeditorplugin.h56
-rw-r--r--src/plugins/cppeditor/cppelementevaluator.cpp19
-rw-r--r--src/plugins/cppeditor/cppfollowsymbolundercursor.cpp13
-rw-r--r--src/plugins/cppeditor/cppfunctiondecldeflink.cpp3
-rw-r--r--src/plugins/cppeditor/cpphighlighter.cpp28
-rw-r--r--src/plugins/cppeditor/cppincludehierarchy.cpp4
-rw-r--r--src/plugins/cppeditor/cppincludehierarchy_test.cpp14
-rw-r--r--src/plugins/cppeditor/cppincludehierarchymodel.cpp8
-rw-r--r--src/plugins/cppeditor/cppinsertvirtualmethods.cpp17
-rw-r--r--src/plugins/cppeditor/cppoutline.cpp2
-rw-r--r--src/plugins/cppeditor/cpppreprocessordialog.cpp2
-rw-r--r--src/plugins/cppeditor/cppquickfix_test.cpp1340
-rw-r--r--src/plugins/cppeditor/cppquickfix_test.h6
-rw-r--r--src/plugins/cppeditor/cppquickfixassistant.cpp14
-rw-r--r--src/plugins/cppeditor/cppquickfixes.cpp514
-rw-r--r--src/plugins/cppeditor/cppquickfixes.h9
-rw-r--r--src/plugins/cppeditor/cpptypehierarchy.cpp2
-rw-r--r--src/plugins/cppeditor/cppuseselections_test.cpp4
-rw-r--r--src/plugins/cppeditor/cppuseselectionsupdater.cpp2
-rw-r--r--src/plugins/cppeditor/cppvirtualfunctionassistprovider.cpp11
-rw-r--r--src/plugins/cppeditor/cppvirtualfunctionassistprovider.h1
-rw-r--r--src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp9
-rw-r--r--src/plugins/cpptools/baseeditordocumentparser.cpp6
-rw-r--r--src/plugins/cpptools/baseeditordocumentprocessor.cpp4
-rw-r--r--src/plugins/cpptools/baseeditordocumentprocessor.h2
-rw-r--r--src/plugins/cpptools/builtineditordocumentparser.cpp18
-rw-r--r--src/plugins/cpptools/builtineditordocumentparser.h2
-rw-r--r--src/plugins/cpptools/builtineditordocumentprocessor.cpp2
-rw-r--r--src/plugins/cpptools/completionsettingspage.cpp88
-rw-r--r--src/plugins/cpptools/completionsettingspage.h7
-rw-r--r--src/plugins/cpptools/completionsettingspage.ui169
-rw-r--r--src/plugins/cpptools/cppcodeformatter.cpp8
-rw-r--r--src/plugins/cpptools/cppcodegen_test.cpp430
-rw-r--r--src/plugins/cpptools/cppcodemodelinspectordumper.cpp4
-rw-r--r--src/plugins/cpptools/cppcodestylepreferences.cpp4
-rw-r--r--src/plugins/cpptools/cppcodestylesettings.cpp4
-rw-r--r--src/plugins/cpptools/cppcodestylesettingspage.cpp106
-rw-r--r--src/plugins/cpptools/cppcompletion_test.cpp223
-rw-r--r--src/plugins/cpptools/cppcompletionassist.cpp136
-rw-r--r--src/plugins/cpptools/cppcompletionassist.h14
-rw-r--r--src/plugins/cpptools/cppcompletionassistprocessor.cpp78
-rw-r--r--src/plugins/cpptools/cppcompletionassistprocessor.h63
-rw-r--r--src/plugins/cpptools/cppcurrentdocumentfilter.cpp5
-rw-r--r--src/plugins/cpptools/cppeditoroutline.cpp (renamed from src/plugins/cppeditor/cppeditoroutline.cpp)35
-rw-r--r--src/plugins/cpptools/cppeditoroutline.h (renamed from src/plugins/cppeditor/cppeditoroutline.h)17
-rw-r--r--src/plugins/cpptools/cppfilesettingspage.cpp4
-rw-r--r--src/plugins/cpptools/cppfindreferences.cpp93
-rw-r--r--src/plugins/cpptools/cppheadersource_test.cpp8
-rw-r--r--src/plugins/cpptools/cppincludesfilter.cpp189
-rw-r--r--src/plugins/cpptools/cppincludesfilter.h62
-rw-r--r--src/plugins/cpptools/cpplocalsymbols.cpp2
-rw-r--r--src/plugins/cpptools/cpplocatordata.cpp3
-rw-r--r--src/plugins/cpptools/cpplocatorfilter.cpp2
-rw-r--r--src/plugins/cpptools/cpplocatorfilter_test.cpp2
-rw-r--r--src/plugins/cpptools/cppmodelmanager.cpp119
-rw-r--r--src/plugins/cpptools/cppmodelmanager.h22
-rw-r--r--src/plugins/cpptools/cppmodelmanager_test.cpp183
-rw-r--r--src/plugins/cpptools/cpppointerdeclarationformatter.cpp2
-rw-r--r--src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp13
-rw-r--r--src/plugins/cpptools/cppprojectfile.cpp44
-rw-r--r--src/plugins/cpptools/cppprojectfile.h9
-rw-r--r--src/plugins/cpptools/cppprojects.cpp97
-rw-r--r--src/plugins/cpptools/cppprojects.h13
-rw-r--r--src/plugins/cpptools/cppqtstyleindenter.cpp13
-rw-r--r--src/plugins/cpptools/cpprefactoringchanges.cpp7
-rw-r--r--src/plugins/cpptools/cppsemanticinfoupdater.cpp5
-rw-r--r--src/plugins/cpptools/cppsourceprocessor.cpp34
-rw-r--r--src/plugins/cpptools/cppsourceprocessor_test.cpp79
-rw-r--r--src/plugins/cpptools/cpptools.pro6
-rw-r--r--src/plugins/cpptools/cpptools.qbs3
-rw-r--r--src/plugins/cpptools/cpptoolsconstants.h1
-rw-r--r--src/plugins/cpptools/cpptoolsplugin.cpp21
-rw-r--r--src/plugins/cpptools/cpptoolsplugin.h1
-rw-r--r--src/plugins/cpptools/cpptoolsreuse.cpp26
-rw-r--r--src/plugins/cpptools/cpptoolsreuse.h4
-rw-r--r--src/plugins/cpptools/cpptoolssettings.cpp44
-rw-r--r--src/plugins/cpptools/cpptoolssettings.h7
-rw-r--r--src/plugins/cpptools/cpptoolstestcase.cpp146
-rw-r--r--src/plugins/cpptools/cpptoolstestcase.h61
-rw-r--r--src/plugins/cpptools/cppworkingcopy.h23
-rw-r--r--src/plugins/cpptools/doxygengenerator.cpp2
-rw-r--r--src/plugins/cpptools/editordocumenthandle.cpp8
-rw-r--r--src/plugins/cpptools/editordocumenthandle.h6
-rw-r--r--src/plugins/cpptools/includeutils.cpp106
-rw-r--r--src/plugins/cpptools/insertionpointlocator.cpp20
-rw-r--r--src/plugins/cpptools/modelmanagertesthelper.cpp34
-rw-r--r--src/plugins/cpptools/modelmanagertesthelper.h1
-rw-r--r--src/plugins/cpptools/searchsymbols.cpp41
-rw-r--r--src/plugins/cpptools/stringtable.cpp3
-rw-r--r--src/plugins/cpptools/symbolsearcher_test.cpp2
-rw-r--r--src/plugins/cpptools/symbolsfindfilter.cpp48
-rw-r--r--src/plugins/cpptools/typehierarchybuilder.cpp10
-rw-r--r--src/plugins/cpptools/typehierarchybuilder_test.cpp16
-rw-r--r--src/plugins/cvs/checkoutwizard.cpp15
-rw-r--r--src/plugins/cvs/cvsclient.cpp48
-rw-r--r--src/plugins/cvs/cvsclient.h5
-rw-r--r--src/plugins/cvs/cvscontrol.cpp12
-rw-r--r--src/plugins/cvs/cvscontrol.h2
-rw-r--r--src/plugins/cvs/cvsplugin.cpp49
-rw-r--r--src/plugins/cvs/cvsplugin.h4
-rw-r--r--src/plugins/cvs/cvssubmiteditor.cpp4
-rw-r--r--src/plugins/debugger/breakhandler.cpp1645
-rw-r--r--src/plugins/debugger/breakhandler.h272
-rw-r--r--src/plugins/debugger/breakpoint.cpp12
-rw-r--r--src/plugins/debugger/breakpoint.h5
-rw-r--r--src/plugins/debugger/breakpointmarker.cpp88
-rw-r--r--src/plugins/debugger/breakwindow.cpp188
-rw-r--r--src/plugins/debugger/breakwindow.h12
-rw-r--r--src/plugins/debugger/cdb/cdbengine.cpp172
-rw-r--r--src/plugins/debugger/cdb/cdbengine.h7
-rw-r--r--src/plugins/debugger/cdb/cdbparsehelpers.cpp3
-rw-r--r--src/plugins/debugger/commonoptionspage.cpp4
-rw-r--r--src/plugins/debugger/debugger.pro6
-rw-r--r--src/plugins/debugger/debugger.qbs3
-rw-r--r--src/plugins/debugger/debuggeractions.cpp13
-rw-r--r--src/plugins/debugger/debuggeractions.h1
-rw-r--r--src/plugins/debugger/debuggerconstants.h4
-rw-r--r--src/plugins/debugger/debuggercore.h7
-rw-r--r--src/plugins/debugger/debuggerdialogs.cpp87
-rw-r--r--src/plugins/debugger/debuggerengine.cpp195
-rw-r--r--src/plugins/debugger/debuggerengine.h58
-rw-r--r--src/plugins/debugger/debuggeritem.cpp15
-rw-r--r--src/plugins/debugger/debuggeritem.h1
-rw-r--r--src/plugins/debugger/debuggeritemmanager.cpp159
-rw-r--r--src/plugins/debugger/debuggeritemmanager.h31
-rw-r--r--src/plugins/debugger/debuggeritemmodel.cpp311
-rw-r--r--src/plugins/debugger/debuggeritemmodel.h93
-rw-r--r--src/plugins/debugger/debuggerkitconfigwidget.cpp36
-rw-r--r--src/plugins/debugger/debuggerkitconfigwidget.h8
-rw-r--r--src/plugins/debugger/debuggerkitinformation.cpp25
-rw-r--r--src/plugins/debugger/debuggermainwindow.cpp86
-rw-r--r--src/plugins/debugger/debuggermainwindow.h9
-rw-r--r--src/plugins/debugger/debuggeroptionspage.cpp459
-rw-r--r--src/plugins/debugger/debuggeroptionspage.h78
-rw-r--r--src/plugins/debugger/debuggerplugin.cpp415
-rw-r--r--src/plugins/debugger/debuggerprotocol.cpp140
-rw-r--r--src/plugins/debugger/debuggerprotocol.h65
-rw-r--r--src/plugins/debugger/debuggerrunconfigurationaspect.cpp30
-rw-r--r--src/plugins/debugger/debuggerruncontrol.cpp134
-rw-r--r--src/plugins/debugger/debuggerruncontrol.h30
-rw-r--r--src/plugins/debugger/debuggersourcepathmappingwidget.cpp35
-rw-r--r--src/plugins/debugger/debuggerstartparameters.h7
-rw-r--r--src/plugins/debugger/debuggertooltipmanager.cpp897
-rw-r--r--src/plugins/debugger/debuggertooltipmanager.h9
-rw-r--r--src/plugins/debugger/disassembleragent.cpp13
-rw-r--r--src/plugins/debugger/disassembleragent.h5
-rw-r--r--src/plugins/debugger/gdb/attachgdbadapter.cpp16
-rw-r--r--src/plugins/debugger/gdb/attachgdbadapter.h2
-rw-r--r--src/plugins/debugger/gdb/coregdbadapter.cpp37
-rw-r--r--src/plugins/debugger/gdb/coregdbadapter.h7
-rw-r--r--src/plugins/debugger/gdb/gdbengine.cpp1463
-rw-r--r--src/plugins/debugger/gdb/gdbengine.h183
-rw-r--r--src/plugins/debugger/gdb/gdboptionspage.cpp4
-rw-r--r--src/plugins/debugger/gdb/gdbplainengine.cpp19
-rw-r--r--src/plugins/debugger/gdb/gdbplainengine.h4
-rw-r--r--src/plugins/debugger/gdb/gdbprocess.cpp6
-rw-r--r--src/plugins/debugger/gdb/remotegdbserveradapter.cpp116
-rw-r--r--src/plugins/debugger/gdb/remotegdbserveradapter.h22
-rw-r--r--src/plugins/debugger/gdb/startgdbserverdialog.cpp31
-rw-r--r--src/plugins/debugger/gdb/termgdbadapter.cpp36
-rw-r--r--src/plugins/debugger/gdb/termgdbadapter.h2
-rw-r--r--src/plugins/debugger/imageviewer.cpp4
-rw-r--r--src/plugins/debugger/lldb/lldbengine.cpp606
-rw-r--r--src/plugins/debugger/lldb/lldbengine.h44
-rw-r--r--src/plugins/debugger/loadcoredialog.cpp49
-rw-r--r--src/plugins/debugger/logwindow.cpp46
-rw-r--r--src/plugins/debugger/memoryagent.cpp48
-rw-r--r--src/plugins/debugger/memoryagent.h29
-rw-r--r--src/plugins/debugger/memoryview.cpp39
-rw-r--r--src/plugins/debugger/memoryview.h16
-rw-r--r--src/plugins/debugger/moduleshandler.cpp365
-rw-r--r--src/plugins/debugger/moduleshandler.h15
-rw-r--r--src/plugins/debugger/moduleswindow.cpp4
-rw-r--r--src/plugins/debugger/pdb/pdbengine.cpp99
-rw-r--r--src/plugins/debugger/pdb/pdbengine.h16
-rw-r--r--src/plugins/debugger/qml/baseqmldebuggerclient.cpp3
-rw-r--r--src/plugins/debugger/qml/baseqmldebuggerclient.h8
-rw-r--r--src/plugins/debugger/qml/qmladapter.cpp50
-rw-r--r--src/plugins/debugger/qml/qmladapter.h5
-rw-r--r--src/plugins/debugger/qml/qmlcppengine.cpp41
-rw-r--r--src/plugins/debugger/qml/qmlcppengine.h10
-rw-r--r--src/plugins/debugger/qml/qmlengine.cpp111
-rw-r--r--src/plugins/debugger/qml/qmlengine.h12
-rw-r--r--src/plugins/debugger/qml/qmlinspectoradapter.cpp10
-rw-r--r--src/plugins/debugger/qml/qmlinspectoradapter.h4
-rw-r--r--src/plugins/debugger/qml/qmlinspectoragent.cpp23
-rw-r--r--src/plugins/debugger/qml/qmlinspectoragent.h4
-rw-r--r--src/plugins/debugger/qml/qmllivetextpreview.cpp28
-rw-r--r--src/plugins/debugger/qml/qmlv8debuggerclient.cpp80
-rw-r--r--src/plugins/debugger/qml/qmlv8debuggerclient.h8
-rw-r--r--src/plugins/debugger/qml/qscriptdebuggerclient.cpp68
-rw-r--r--src/plugins/debugger/qml/qscriptdebuggerclient.h6
-rw-r--r--src/plugins/debugger/registerhandler.cpp865
-rw-r--r--src/plugins/debugger/registerhandler.h99
-rw-r--r--src/plugins/debugger/registerwindow.cpp98
-rw-r--r--src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp13
-rw-r--r--src/plugins/debugger/snapshothandler.h4
-rw-r--r--src/plugins/debugger/sourceagent.cpp22
-rw-r--r--src/plugins/debugger/sourceagent.h7
-rw-r--r--src/plugins/debugger/sourceutils.cpp13
-rw-r--r--src/plugins/debugger/stackhandler.cpp28
-rw-r--r--src/plugins/debugger/stackhandler.h22
-rw-r--r--src/plugins/debugger/stackwindow.cpp21
-rw-r--r--src/plugins/debugger/terminal.cpp169
-rw-r--r--src/plugins/debugger/terminal.h (renamed from src/plugins/debugger/breakpointmarker.h)47
-rw-r--r--src/plugins/debugger/unstartedappwatcherdialog.cpp23
-rw-r--r--src/plugins/debugger/unstartedappwatcherdialog.h11
-rw-r--r--src/plugins/debugger/watchdata.cpp71
-rw-r--r--src/plugins/debugger/watchdata.h20
-rw-r--r--src/plugins/debugger/watchhandler.cpp1164
-rw-r--r--src/plugins/debugger/watchhandler.h61
-rw-r--r--src/plugins/debugger/watchwindow.cpp225
-rw-r--r--src/plugins/debugger/watchwindow.h13
-rw-r--r--src/plugins/designer/formeditorplugin.cpp10
-rw-r--r--src/plugins/designer/formeditorw.cpp58
-rw-r--r--src/plugins/designer/formtemplatewizardpage.cpp8
-rw-r--r--src/plugins/designer/formwindoweditor.cpp2
-rw-r--r--src/plugins/designer/formwindowfile.cpp19
-rw-r--r--src/plugins/designer/formwindowfile.h2
-rw-r--r--src/plugins/designer/gotoslot_test.cpp14
-rw-r--r--src/plugins/designer/qtcreatorintegration.cpp28
-rw-r--r--src/plugins/designer/resourcehandler.cpp29
-rw-r--r--src/plugins/designer/resourcehandler.h8
-rw-r--r--src/plugins/diffeditor/diffeditor.cpp125
-rw-r--r--src/plugins/diffeditor/diffeditor.h7
-rw-r--r--src/plugins/diffeditor/diffeditorcontroller.cpp29
-rw-r--r--src/plugins/diffeditor/diffeditorcontroller.h16
-rw-r--r--src/plugins/diffeditor/diffeditordocument.cpp10
-rw-r--r--src/plugins/diffeditor/diffeditordocument.h5
-rw-r--r--src/plugins/diffeditor/diffeditorguicontroller.cpp16
-rw-r--r--src/plugins/diffeditor/diffeditorguicontroller.h3
-rw-r--r--src/plugins/diffeditor/diffeditormanager.cpp23
-rw-r--r--src/plugins/diffeditor/diffeditormanager.h2
-rw-r--r--src/plugins/diffeditor/diffeditorplugin.cpp62
-rw-r--r--src/plugins/diffeditor/diffeditorreloader.cpp8
-rw-r--r--src/plugins/diffeditor/diffutils.cpp20
-rw-r--r--src/plugins/diffeditor/sidebysidediffeditorwidget.cpp224
-rw-r--r--src/plugins/diffeditor/sidebysidediffeditorwidget.h4
-rw-r--r--src/plugins/diffeditor/unifieddiffeditorwidget.cpp76
-rw-r--r--src/plugins/diffeditor/unifieddiffeditorwidget.h2
-rw-r--r--src/plugins/fakevim/fakevim_test.cpp724
-rw-r--r--src/plugins/fakevim/fakevimhandler.cpp1925
-rw-r--r--src/plugins/fakevim/fakevimplugin.cpp23
-rw-r--r--src/plugins/fakevim/fakevimplugin.h21
-rw-r--r--src/plugins/genericprojectmanager/cppmodelmanagerhelper.cpp74
-rw-r--r--src/plugins/genericprojectmanager/filesselectionwizardpage.cpp10
-rw-r--r--src/plugins/genericprojectmanager/genericbuildconfiguration.cpp12
-rw-r--r--src/plugins/genericprojectmanager/genericmakestep.cpp20
-rw-r--r--src/plugins/genericprojectmanager/genericproject.cpp10
-rw-r--r--src/plugins/genericprojectmanager/genericprojectmanager.pro3
-rw-r--r--src/plugins/genericprojectmanager/genericprojectmanager.qbs5
-rw-r--r--src/plugins/genericprojectmanager/genericprojectnodes.cpp10
-rw-r--r--src/plugins/genericprojectmanager/genericprojectplugin.cpp7
-rw-r--r--src/plugins/genericprojectmanager/genericprojectplugin_test.cpp115
-rw-r--r--src/plugins/git/branchadddialog.cpp2
-rw-r--r--src/plugins/git/branchcheckoutdialog.cpp3
-rw-r--r--src/plugins/git/branchmodel.cpp6
-rw-r--r--src/plugins/git/changeselectiondialog.cpp32
-rw-r--r--src/plugins/git/clonewizard.cpp11
-rw-r--r--src/plugins/git/clonewizardpage.cpp4
-rw-r--r--src/plugins/git/commitdata.cpp2
-rw-r--r--src/plugins/git/gerrit/gerritdialog.cpp21
-rw-r--r--src/plugins/git/gerrit/gerritdialog.h25
-rw-r--r--src/plugins/git/gerrit/gerritmodel.cpp28
-rw-r--r--src/plugins/git/gerrit/gerritplugin.cpp33
-rw-r--r--src/plugins/git/gerrit/gerritpushdialog.cpp8
-rw-r--r--src/plugins/git/gerrit/gerritpushdialog.h4
-rw-r--r--src/plugins/git/gitclient.cpp272
-rw-r--r--src/plugins/git/gitclient.h6
-rw-r--r--src/plugins/git/giteditor.cpp20
-rw-r--r--src/plugins/git/giteditor.h2
-rw-r--r--src/plugins/git/gitplugin.cpp76
-rw-r--r--src/plugins/git/gitplugin.h4
-rw-r--r--src/plugins/git/gitsubmiteditor.cpp14
-rw-r--r--src/plugins/git/gitsubmiteditorwidget.cpp17
-rw-r--r--src/plugins/git/gitversioncontrol.cpp12
-rw-r--r--src/plugins/git/gitversioncontrol.h2
-rw-r--r--src/plugins/git/logchangedialog.cpp6
-rw-r--r--src/plugins/git/mergetool.cpp5
-rw-r--r--src/plugins/git/remotedialog.cpp15
-rw-r--r--src/plugins/git/settingspage.cpp4
-rw-r--r--src/plugins/git/stashdialog.cpp30
-rw-r--r--src/plugins/glsleditor/glslcompletionassist.cpp2
-rw-r--r--src/plugins/glsleditor/glsleditor.cpp18
-rw-r--r--src/plugins/glsleditor/glslhighlighter.cpp26
-rw-r--r--src/plugins/help/docsettingspage.cpp29
-rw-r--r--src/plugins/help/docsettingspage.h3
-rw-r--r--src/plugins/help/filtersettingspage.cpp16
-rw-r--r--src/plugins/help/generalsettingspage.cpp23
-rw-r--r--src/plugins/help/help.pro8
-rw-r--r--src/plugins/help/help.qbs2
-rw-r--r--src/plugins/help/helpfindsupport.cpp12
-rw-r--r--src/plugins/help/helpindexfilter.cpp110
-rw-r--r--src/plugins/help/helpindexfilter.h14
-rw-r--r--src/plugins/help/helpplugin.cpp124
-rw-r--r--src/plugins/help/helpplugin.h2
-rw-r--r--src/plugins/help/helpviewer.h1
-rw-r--r--src/plugins/help/localhelpmanager.cpp5
-rw-r--r--src/plugins/help/localhelpmanager.h8
-rw-r--r--src/plugins/help/macwebkithelpviewer.h6
-rw-r--r--src/plugins/help/macwebkithelpviewer.mm91
-rw-r--r--src/plugins/help/openpagesmodel.cpp3
-rw-r--r--src/plugins/help/openpagesswitcher.cpp8
-rw-r--r--src/plugins/help/qtwebkithelpviewer.cpp24
-rw-r--r--src/plugins/help/qtwebkithelpviewer.h5
-rw-r--r--src/plugins/help/remotehelpfilter.cpp6
-rw-r--r--src/plugins/help/textbrowserhelpviewer.cpp29
-rw-r--r--src/plugins/help/textbrowserhelpviewer.h5
-rw-r--r--src/plugins/imageviewer/imageviewer.cpp6
-rw-r--r--src/plugins/imageviewer/imageviewerfile.cpp4
-rw-r--r--src/plugins/ios/iosanalyzesupport.cpp3
-rw-r--r--src/plugins/ios/iosbuildstep.cpp4
-rw-r--r--src/plugins/ios/iosconfigurations.cpp31
-rw-r--r--src/plugins/ios/iosdebugsupport.cpp34
-rw-r--r--src/plugins/ios/iosdeployconfiguration.cpp5
-rw-r--r--src/plugins/ios/iosdeployconfiguration.h3
-rw-r--r--src/plugins/ios/iosdeploystep.cpp14
-rw-r--r--src/plugins/ios/iosdevice.cpp6
-rw-r--r--src/plugins/ios/iosdsymbuildstep.cpp4
-rw-r--r--src/plugins/ios/iosmanager.cpp4
-rw-r--r--src/plugins/ios/iosqtversion.cpp8
-rw-r--r--src/plugins/ios/iosrunconfiguration.cpp16
-rw-r--r--src/plugins/ios/iosrunfactories.cpp12
-rw-r--r--src/plugins/ios/iosrunner.cpp2
-rw-r--r--src/plugins/ios/iossimulator.cpp2
-rw-r--r--src/plugins/macros/findmacrohandler.cpp24
-rw-r--r--src/plugins/macros/macrooptionswidget.cpp12
-rw-r--r--src/plugins/macros/macrosplugin.cpp8
-rw-r--r--src/plugins/mercurial/clonewizard.cpp15
-rw-r--r--src/plugins/mercurial/commiteditor.cpp4
-rw-r--r--src/plugins/mercurial/mercurialclient.cpp80
-rw-r--r--src/plugins/mercurial/mercurialclient.h4
-rw-r--r--src/plugins/mercurial/mercurialcontrol.cpp12
-rw-r--r--src/plugins/mercurial/mercurialcontrol.h2
-rw-r--r--src/plugins/mercurial/mercurialplugin.cpp18
-rw-r--r--src/plugins/perforce/perforcechecker.cpp8
-rw-r--r--src/plugins/perforce/perforceplugin.cpp88
-rw-r--r--src/plugins/perforce/perforceplugin.h1
-rw-r--r--src/plugins/perforce/perforceversioncontrol.cpp12
-rw-r--r--src/plugins/perforce/perforceversioncontrol.h2
-rw-r--r--src/plugins/perforce/settingspage.cpp2
-rw-r--r--src/plugins/projectexplorer/abi.cpp28
-rw-r--r--src/plugins/projectexplorer/abi.h3
-rw-r--r--src/plugins/projectexplorer/abstractprocessstep.cpp2
-rw-r--r--src/plugins/projectexplorer/addnewmodel.cpp214
-rw-r--r--src/plugins/projectexplorer/addnewmodel.h89
-rw-r--r--src/plugins/projectexplorer/allprojectsfilter.cpp26
-rw-r--r--src/plugins/projectexplorer/allprojectsfilter.h5
-rw-r--r--src/plugins/projectexplorer/allprojectsfind.cpp2
-rw-r--r--src/plugins/projectexplorer/applicationlauncher.cpp11
-rw-r--r--src/plugins/projectexplorer/applicationlauncher.h4
-rw-r--r--src/plugins/projectexplorer/appoutputpane.cpp6
-rw-r--r--src/plugins/projectexplorer/buildmanager.cpp6
-rw-r--r--src/plugins/projectexplorer/buildmanager.h2
-rw-r--r--src/plugins/projectexplorer/buildprogress.cpp6
-rw-r--r--src/plugins/projectexplorer/buildstepspage.cpp14
-rw-r--r--src/plugins/projectexplorer/clangparser.cpp20
-rw-r--r--src/plugins/projectexplorer/codestylesettingspropertiespage.cpp2
-rw-r--r--src/plugins/projectexplorer/currentprojectfilter.cpp39
-rw-r--r--src/plugins/projectexplorer/currentprojectfilter.h4
-rw-r--r--src/plugins/projectexplorer/currentprojectfind.cpp16
-rw-r--r--src/plugins/projectexplorer/customparser.cpp24
-rw-r--r--src/plugins/projectexplorer/customtoolchain.cpp10
-rw-r--r--src/plugins/projectexplorer/deployablefile.cpp5
-rw-r--r--src/plugins/projectexplorer/deployconfiguration.cpp70
-rw-r--r--src/plugins/projectexplorer/deployconfiguration.h35
-rw-r--r--src/plugins/projectexplorer/deploymentdata.h9
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicemanager.cpp21
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicemanager.h3
-rw-r--r--src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp6
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp10
-rw-r--r--src/plugins/projectexplorer/devicesupport/idevice.cpp10
-rw-r--r--src/plugins/projectexplorer/doubletabwidget.cpp24
-rw-r--r--src/plugins/projectexplorer/editorconfiguration.cpp12
-rw-r--r--src/plugins/projectexplorer/foldernavigationwidget.cpp17
-rw-r--r--src/plugins/projectexplorer/foldernavigationwidget.h9
-rw-r--r--src/plugins/projectexplorer/gccparser.cpp2
-rw-r--r--src/plugins/projectexplorer/gcctoolchain.cpp20
-rw-r--r--src/plugins/projectexplorer/journaldwatcher.cpp221
-rw-r--r--src/plugins/projectexplorer/journaldwatcher.h72
-rw-r--r--src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp6
-rw-r--r--src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp1
-rw-r--r--src/plugins/projectexplorer/jsonwizard/jsonwizard.cpp17
-rw-r--r--src/plugins/projectexplorer/jsonwizard/jsonwizard.h4
-rw-r--r--src/plugins/projectexplorer/jsonwizard/jsonwizardfactory.cpp16
-rw-r--r--src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp14
-rw-r--r--src/plugins/projectexplorer/kit.cpp28
-rw-r--r--src/plugins/projectexplorer/kitinformationconfigwidget.cpp10
-rw-r--r--src/plugins/projectexplorer/kitmodel.cpp369
-rw-r--r--src/plugins/projectexplorer/kitmodel.h35
-rw-r--r--src/plugins/projectexplorer/kitoptionspage.cpp279
-rw-r--r--src/plugins/projectexplorer/kitoptionspage.h33
-rw-r--r--src/plugins/projectexplorer/linuxiccparser.cpp37
-rw-r--r--src/plugins/projectexplorer/linuxiccparser.h1
-rw-r--r--src/plugins/projectexplorer/localapplicationruncontrol.h15
-rw-r--r--src/plugins/projectexplorer/miniprojecttargetselector.cpp6
-rw-r--r--src/plugins/projectexplorer/nodesvisitor.cpp5
-rw-r--r--src/plugins/projectexplorer/nodesvisitor.h1
-rw-r--r--src/plugins/projectexplorer/panelswidget.cpp6
-rw-r--r--src/plugins/projectexplorer/processparameters.cpp4
-rw-r--r--src/plugins/projectexplorer/project.cpp2
-rw-r--r--src/plugins/projectexplorer/projectexplorer.cpp510
-rw-r--r--src/plugins/projectexplorer/projectexplorer.h22
-rw-r--r--src/plugins/projectexplorer/projectexplorer.pro15
-rw-r--r--src/plugins/projectexplorer/projectexplorer.qbs3
-rw-r--r--src/plugins/projectexplorer/projectexplorerconstants.h1
-rw-r--r--src/plugins/projectexplorer/projectmodels.cpp103
-rw-r--r--src/plugins/projectexplorer/projectmodels.h3
-rw-r--r--src/plugins/projectexplorer/projectnodes.cpp225
-rw-r--r--src/plugins/projectexplorer/projectnodes.h90
-rw-r--r--src/plugins/projectexplorer/projecttree.cpp505
-rw-r--r--src/plugins/projectexplorer/projecttree.h161
-rw-r--r--src/plugins/projectexplorer/projecttreewidget.cpp99
-rw-r--r--src/plugins/projectexplorer/projecttreewidget.h12
-rw-r--r--src/plugins/projectexplorer/projectwelcomepage.cpp4
-rw-r--r--src/plugins/projectexplorer/projectwelcomepage.h6
-rw-r--r--src/plugins/projectexplorer/projectwizardpage.cpp98
-rw-r--r--src/plugins/projectexplorer/projectwizardpage.h7
-rw-r--r--src/plugins/projectexplorer/runconfiguration.cpp11
-rw-r--r--src/plugins/projectexplorer/runconfiguration.h9
-rw-r--r--src/plugins/projectexplorer/runsettingspropertiespage.cpp2
-rw-r--r--src/plugins/projectexplorer/session.cpp82
-rw-r--r--src/plugins/projectexplorer/session.h4
-rw-r--r--src/plugins/projectexplorer/settingsaccessor.cpp128
-rw-r--r--src/plugins/projectexplorer/targetsettingspanel.cpp12
-rw-r--r--src/plugins/projectexplorer/targetsetuppage.cpp4
-rw-r--r--src/plugins/projectexplorer/taskmodel.cpp17
-rw-r--r--src/plugins/projectexplorer/toolchainmanager.cpp2
-rw-r--r--src/plugins/projectexplorer/toolchainmanager.h2
-rw-r--r--src/plugins/projectexplorer/toolchainoptionspage.cpp674
-rw-r--r--src/plugins/projectexplorer/toolchainoptionspage.h91
-rw-r--r--src/plugins/projectexplorer/windebuginterface.cpp13
-rw-r--r--src/plugins/projectexplorer/windebuginterface.h2
-rw-r--r--src/plugins/qbsprojectmanager/customqbspropertiesdialog.cpp104
-rw-r--r--src/plugins/qbsprojectmanager/customqbspropertiesdialog.h62
-rw-r--r--src/plugins/qbsprojectmanager/customqbspropertiesdialog.ui120
-rw-r--r--src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp35
-rw-r--r--src/plugins/qbsprojectmanager/defaultpropertyprovider.h6
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp124
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildconfiguration.h7
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildstep.cpp93
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildstep.h9
-rw-r--r--src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui25
-rw-r--r--src/plugins/qbsprojectmanager/qbscleanstep.cpp10
-rw-r--r--src/plugins/qbsprojectmanager/qbsconstants.h8
-rw-r--r--src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp6
-rw-r--r--src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.h1
-rw-r--r--src/plugins/qbsprojectmanager/qbsinstallstep.cpp13
-rw-r--r--src/plugins/qbsprojectmanager/qbslogsink.cpp2
-rw-r--r--src/plugins/qbsprojectmanager/qbsnodes.cpp43
-rw-r--r--src/plugins/qbsprojectmanager/qbsnodes.h11
-rw-r--r--src/plugins/qbsprojectmanager/qbsprofilessettingspage.cpp242
-rw-r--r--src/plugins/qbsprojectmanager/qbsprofilessettingspage.h56
-rw-r--r--src/plugins/qbsprojectmanager/qbsprofilessettingswidget.ui125
-rw-r--r--src/plugins/qbsprojectmanager/qbsproject.cpp87
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectfile.cpp2
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.cpp20
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.h14
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.pro8
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanager.qbs8
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp50
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h2
-rw-r--r--src/plugins/qbsprojectmanager/qbsprojectparser.cpp2
-rw-r--r--src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp17
-rw-r--r--src/plugins/qbsprojectmanager/qbsrunconfiguration.h4
-rw-r--r--src/plugins/qmakeandroidsupport/androidpackageinstallationfactory.cpp10
-rw-r--r--src/plugins/qmakeandroidsupport/androidqmakebuildconfigurationfactory.h2
-rw-r--r--src/plugins/qmakeandroidsupport/createandroidmanifestwizard.cpp81
-rw-r--r--src/plugins/qmakeandroidsupport/createandroidmanifestwizard.h6
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.cpp66
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.h11
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.cpp44
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.h2
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.ui14
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidrunconfiguration.cpp5
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidrunfactories.cpp12
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidsupport.cpp8
-rw-r--r--src/plugins/qmakeandroidsupport/qmakeandroidsupport.h2
-rw-r--r--src/plugins/qmakeprojectmanager/customwidgetwizard/plugingenerator.cpp2
-rw-r--r--src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.cpp12
-rw-r--r--src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.h2
-rw-r--r--src/plugins/qmakeprojectmanager/externaleditors.cpp6
-rw-r--r--src/plugins/qmakeprojectmanager/findqmakeprofiles.cpp2
-rw-r--r--src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp2
-rw-r--r--src/plugins/qmakeprojectmanager/profileeditor.cpp8
-rw-r--r--src/plugins/qmakeprojectmanager/qmakenodes.cpp343
-rw-r--r--src/plugins/qmakeprojectmanager/qmakenodes.h46
-rw-r--r--src/plugins/qmakeprojectmanager/qmakeproject.cpp132
-rw-r--r--src/plugins/qmakeprojectmanager/qmakeproject.h3
-rw-r--r--src/plugins/qmakeprojectmanager/qmakeprojectmanager.cpp15
-rw-r--r--src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp32
-rw-r--r--src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.h2
-rw-r--r--src/plugins/qmakeprojectmanager/qmakestep.cpp6
-rw-r--r--src/plugins/qmakeprojectmanager/qmakestep.ui2
-rw-r--r--src/plugins/qmakeprojectmanager/wizards/abstractmobileappwizard.cpp5
-rw-r--r--src/plugins/qmakeprojectmanager/wizards/consoleappwizard.cpp5
-rw-r--r--src/plugins/qmakeprojectmanager/wizards/guiappwizard.cpp13
-rw-r--r--src/plugins/qmakeprojectmanager/wizards/librarywizard.cpp11
-rw-r--r--src/plugins/qmakeprojectmanager/wizards/qtprojectparameters.cpp2
-rw-r--r--src/plugins/qmakeprojectmanager/wizards/testwizard.cpp3
-rw-r--r--src/plugins/qmldesigner/components/componentcore/crumblebar.cpp2
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp20
-rw-r--r--src/plugins/qmldesigner/components/formeditor/dragtool.cpp2
-rw-r--r--src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp4
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocument.cpp51
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocument.h2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp2
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp6
-rw-r--r--src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp6
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp12
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp5
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h3
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp12
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp6
-rw-r--r--src/plugins/qmldesigner/componentsplugin/Controls/TabViewSpecifics.qml2
-rw-r--r--src/plugins/qmldesigner/componentsplugin/addtabdesigneraction.cpp4
-rw-r--r--src/plugins/qmldesigner/designercore/exceptions/exception.cpp5
-rw-r--r--src/plugins/qmldesigner/designercore/include/rewriterview.h2
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp14
-rw-r--r--src/plugins/qmldesigner/designercore/instances/puppetcreator.cpp33
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp7
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp9
-rw-r--r--src/plugins/qmldesigner/designercore/model/model.cpp58
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelmerger.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/model/rewriterview.cpp4
-rw-r--r--src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp5
-rw-r--r--src/plugins/qmldesigner/designmodewidget.cpp8
-rw-r--r--src/plugins/qmldesigner/documentmanager.cpp6
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.cpp2
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.pri6
-rw-r--r--src/plugins/qmldesigner/settingspage.cpp3
-rw-r--r--src/plugins/qmljseditor/qmljscompletionassist.cpp13
-rw-r--r--src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp2
-rw-r--r--src/plugins/qmljseditor/qmljseditor.cpp8
-rw-r--r--src/plugins/qmljseditor/qmljseditordocument.cpp8
-rw-r--r--src/plugins/qmljseditor/qmljshoverhandler.cpp5
-rw-r--r--src/plugins/qmljseditor/qmljsoutline.cpp14
-rw-r--r--src/plugins/qmljseditor/qmljsoutline.h4
-rw-r--r--src/plugins/qmljseditor/qmljsquickfixassist.cpp2
-rw-r--r--src/plugins/qmljseditor/qmloutlinemodel.cpp2
-rw-r--r--src/plugins/qmljstools/qmlconsoleitemdelegate.cpp3
-rw-r--r--src/plugins/qmljstools/qmlconsolepane.cpp21
-rw-r--r--src/plugins/qmljstools/qmlconsoleview.cpp2
-rw-r--r--src/plugins/qmljstools/qmljscodestylesettingspage.cpp4
-rw-r--r--src/plugins/qmljstools/qmljslocatordata.cpp11
-rw-r--r--src/plugins/qmljstools/qmljsmodelmanager.cpp17
-rw-r--r--src/plugins/qmljstools/qmljstoolsplugin.cpp3
-rw-r--r--src/plugins/qmlprofiler/abstracttimelinemodel.cpp299
-rw-r--r--src/plugins/qmlprofiler/abstracttimelinemodel.h146
-rw-r--r--src/plugins/qmlprofiler/notesmodel.cpp229
-rw-r--r--src/plugins/qmlprofiler/qml/CategoryLabel.qml312
-rw-r--r--src/plugins/qmlprofiler/qml/MainView.qml544
-rw-r--r--src/plugins/qmlprofiler/qml/Overview.js193
-rw-r--r--src/plugins/qmlprofiler/qml/Overview.qml207
-rw-r--r--src/plugins/qmlprofiler/qml/TimeDisplay.qml129
-rw-r--r--src/plugins/qmlprofiler/qml/TimeMarks.qml196
-rw-r--r--src/plugins/qmlprofiler/qml/bindingloops.frag35
-rw-r--r--src/plugins/qmlprofiler/qml/bindingloops.vert43
-rw-r--r--src/plugins/qmlprofiler/qml/qmlprofiler.qrc29
-rw-r--r--src/plugins/qmlprofiler/qmlprofiler.pro110
-rw-r--r--src/plugins/qmlprofiler/qmlprofiler.qbs34
-rw-r--r--src/plugins/qmlprofiler/qmlprofiler_dependencies.pri1
-rw-r--r--src/plugins/qmlprofiler/qmlprofileranimationsmodel.cpp (renamed from src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.cpp)154
-rw-r--r--src/plugins/qmlprofiler/qmlprofileranimationsmodel.h (renamed from src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.h)26
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp359
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.h59
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp7
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp8
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdatamodel.h3
-rw-r--r--src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp2
-rw-r--r--src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h2
-rw-r--r--src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp58
-rw-r--r--src/plugins/qmlprofiler/qmlprofilermodelmanager.h14
-rw-r--r--src/plugins/qmlprofiler/qmlprofilernotesmodel.cpp109
-rw-r--r--src/plugins/qmlprofiler/qmlprofilernotesmodel.h55
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerplugin.cpp11
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerplugin.h10
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerrangemodel.cpp303
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerrangemodel.h (renamed from src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.h)31
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp4
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertimelinemodel.cpp114
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertimelinemodel.h (renamed from src/plugins/qmlprofiler/notesmodel.h)75
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.cpp36
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.h48
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp324
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertool.cpp5
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertracefile.cpp8
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertracefile.h3
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertraceview.cpp220
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertraceview.h53
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp2
-rw-r--r--src/plugins/qmlprofiler/sortedtimelinemodel.cpp165
-rw-r--r--src/plugins/qmlprofiler/sortedtimelinemodel.h190
-rw-r--r--src/plugins/qmlprofiler/timelinemodelaggregator.cpp400
-rw-r--r--src/plugins/qmlprofiler/timelinemodelaggregator.h138
-rw-r--r--src/plugins/qmlprofiler/timelinerenderer.cpp709
-rw-r--r--src/plugins/qmlprofiler/timelinerenderer.h238
-rw-r--r--src/plugins/qmlprojectmanager/QmlProjectManager.json.in1
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp3
-rw-r--r--src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp4
-rw-r--r--src/plugins/qmlprojectmanager/qmlproject.cpp8
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectfile.cpp4
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectfile.h2
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectnodes.cpp6
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp4
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp6
-rw-r--r--src/plugins/qnx/bardescriptordocument.cpp12
-rw-r--r--src/plugins/qnx/bardescriptoreditor.cpp2
-rw-r--r--src/plugins/qnx/bardescriptoreditorassetswidget.cpp2
-rw-r--r--src/plugins/qnx/bardescriptoreditorentrypointwidget.cpp4
-rw-r--r--src/plugins/qnx/bardescriptoreditorwidget.cpp10
-rw-r--r--src/plugins/qnx/bardescriptoreditorwidget.h2
-rw-r--r--src/plugins/qnx/bardescriptorfilenode.h1
-rw-r--r--src/plugins/qnx/bardescriptorfilenodemanager.cpp16
-rw-r--r--src/plugins/qnx/blackberryapilevelconfiguration.cpp10
-rw-r--r--src/plugins/qnx/blackberryapplicationrunner.cpp6
-rw-r--r--src/plugins/qnx/blackberrydebugsupport.cpp22
-rw-r--r--src/plugins/qnx/blackberrydebugsupport.h8
-rw-r--r--src/plugins/qnx/blackberryruncontrolfactory.cpp141
-rw-r--r--src/plugins/qnx/blackberryruncontrolfactory.h2
-rw-r--r--src/plugins/qnx/qnxanalyzesupport.cpp6
-rw-r--r--src/plugins/qnx/qnxattachdebugsupport.cpp21
-rw-r--r--src/plugins/qnx/qnxattachdebugsupport.h6
-rw-r--r--src/plugins/qnx/qnxbaseconfiguration.cpp32
-rw-r--r--src/plugins/qnx/qnxconfiguration.cpp36
-rw-r--r--src/plugins/qnx/qnxdebugsupport.cpp60
-rw-r--r--src/plugins/qnx/qnxdebugsupport.h9
-rw-r--r--src/plugins/qnx/qnxdeployconfigurationfactory.h2
-rw-r--r--src/plugins/qnx/qnxdeviceconfiguration.cpp20
-rw-r--r--src/plugins/qnx/qnxplugin.cpp7
-rw-r--r--src/plugins/qnx/qnxruncontrol.cpp4
-rw-r--r--src/plugins/qnx/qnxruncontrolfactory.cpp21
-rw-r--r--src/plugins/qnx/qnxsettingswidget.ui2
-rw-r--r--src/plugins/qnx/qnxutils.cpp10
-rw-r--r--src/plugins/qtsupport/baseqtversion.cpp3
-rw-r--r--src/plugins/qtsupport/gettingstartedwelcomepage.cpp4
-rw-r--r--src/plugins/qtsupport/gettingstartedwelcomepage.h6
-rw-r--r--src/plugins/qtsupport/qtoutputformatter.cpp214
-rw-r--r--src/plugins/qtsupport/qtoutputformatter.h7
-rw-r--r--src/plugins/qtsupport/qtsupportplugin.cpp4
-rw-r--r--src/plugins/qtsupport/qtsupportplugin.h3
-rw-r--r--src/plugins/qtsupport/screenshotcropper.cpp5
-rw-r--r--src/plugins/qtsupport/uicodemodelsupport.cpp4
-rw-r--r--src/plugins/remotelinux/abstractpackagingstep.cpp7
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp7
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp8
-rw-r--r--src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp11
-rw-r--r--src/plugins/remotelinux/genericdirectuploadservice.cpp2
-rw-r--r--src/plugins/remotelinux/genericdirectuploadstep.cpp4
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp11
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h1
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui11
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp2
-rw-r--r--src/plugins/remotelinux/linuxdevice.cpp6
-rw-r--r--src/plugins/remotelinux/linuxdevicetester.cpp13
-rw-r--r--src/plugins/remotelinux/packageuploader.cpp3
-rw-r--r--src/plugins/remotelinux/publickeydeploymentdialog.cpp9
-rw-r--r--src/plugins/remotelinux/remotelinuxanalyzesupport.cpp22
-rw-r--r--src/plugins/remotelinux/remotelinuxcheckforfreediskspaceservice.cpp6
-rw-r--r--src/plugins/remotelinux/remotelinuxdebugsupport.cpp66
-rw-r--r--src/plugins/remotelinux/remotelinuxdebugsupport.h4
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp4
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp5
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.h1
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp20
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentreader.cpp6
-rw-r--r--src/plugins/remotelinux/remotelinuxpackageinstaller.cpp16
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfiguration.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp26
-rw-r--r--src/plugins/remotelinux/remotelinuxruncontrol.cpp20
-rw-r--r--src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp8
-rw-r--r--src/plugins/remotelinux/remotelinuxsignaloperation.cpp6
-rw-r--r--src/plugins/remotelinux/sshkeydeployer.cpp6
-rw-r--r--src/plugins/remotelinux/typespecificdeviceconfigurationlistmodel.cpp2
-rw-r--r--src/plugins/resourceeditor/qrceditor/qrceditor.cpp2
-rw-r--r--src/plugins/resourceeditor/qrceditor/resourcefile.cpp5
-rw-r--r--src/plugins/resourceeditor/resourceeditorconstants.h1
-rw-r--r--src/plugins/resourceeditor/resourceeditorfactory.cpp2
-rw-r--r--src/plugins/resourceeditor/resourceeditorplugin.cpp65
-rw-r--r--src/plugins/resourceeditor/resourceeditorplugin.h4
-rw-r--r--src/plugins/resourceeditor/resourceeditorw.cpp26
-rw-r--r--src/plugins/resourceeditor/resourceeditorw.h2
-rw-r--r--src/plugins/resourceeditor/resourcenode.cpp17
-rw-r--r--src/plugins/resourceeditor/resourcenode.h7
-rw-r--r--src/plugins/subversion/checkoutwizard.cpp15
-rw-r--r--src/plugins/subversion/subversion.qbs1
-rw-r--r--src/plugins/subversion/subversion_dependencies.pri3
-rw-r--r--src/plugins/subversion/subversionclient.cpp343
-rw-r--r--src/plugins/subversion/subversionclient.h34
-rw-r--r--src/plugins/subversion/subversionconstants.h19
-rw-r--r--src/plugins/subversion/subversioncontrol.cpp12
-rw-r--r--src/plugins/subversion/subversioncontrol.h2
-rw-r--r--src/plugins/subversion/subversionplugin.cpp222
-rw-r--r--src/plugins/subversion/subversionplugin.h9
-rw-r--r--src/plugins/subversion/subversionsettings.cpp2
-rw-r--r--src/plugins/subversion/subversionsettings.h1
-rw-r--r--src/plugins/subversion/subversionsubmiteditor.cpp2
-rw-r--r--src/plugins/tasklist/stopmonitoringhandler.cpp2
-rw-r--r--src/plugins/tasklist/taskfile.cpp4
-rw-r--r--src/plugins/tasklist/tasklistplugin.cpp16
-rw-r--r--src/plugins/texteditor/autocompleter.cpp14
-rw-r--r--src/plugins/texteditor/basefilefind.cpp53
-rw-r--r--src/plugins/texteditor/basehoverhandler.cpp3
-rw-r--r--src/plugins/texteditor/behaviorsettingspage.cpp4
-rw-r--r--src/plugins/texteditor/codeassist/codeassistant.cpp18
-rw-r--r--src/plugins/texteditor/codeassist/codeassistant.h2
-rw-r--r--src/plugins/texteditor/codeassist/genericproposalmodel.cpp6
-rw-r--r--src/plugins/texteditor/codeassist/genericproposalwidget.cpp4
-rw-r--r--src/plugins/texteditor/codecselector.cpp6
-rw-r--r--src/plugins/texteditor/codestylepool.cpp14
-rw-r--r--src/plugins/texteditor/codestyleselectorwidget.cpp8
-rw-r--r--src/plugins/texteditor/completionsettings.cpp5
-rw-r--r--src/plugins/texteditor/completionsettings.h1
-rw-r--r--src/plugins/texteditor/findincurrentfile.cpp7
-rw-r--r--src/plugins/texteditor/findinfiles.cpp9
-rw-r--r--src/plugins/texteditor/fontsettings.cpp4
-rw-r--r--src/plugins/texteditor/fontsettingspage.cpp9
-rw-r--r--src/plugins/texteditor/generichighlighter/context.cpp2
-rw-r--r--src/plugins/texteditor/generichighlighter/highlightdefinition.cpp21
-rw-r--r--src/plugins/texteditor/generichighlighter/highlighter.cpp74
-rw-r--r--src/plugins/texteditor/generichighlighter/highlighterexception.h14
-rw-r--r--src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp27
-rw-r--r--src/plugins/texteditor/generichighlighter/managedefinitionsdialog.h9
-rw-r--r--src/plugins/texteditor/generichighlighter/manager.cpp17
-rw-r--r--src/plugins/texteditor/highlighterutils.cpp2
-rw-r--r--src/plugins/texteditor/indenter.cpp6
-rw-r--r--src/plugins/texteditor/ioutlinewidget.h5
-rw-r--r--src/plugins/texteditor/linenumberfilter.cpp2
-rw-r--r--src/plugins/texteditor/normalindenter.cpp2
-rw-r--r--src/plugins/texteditor/outlinefactory.cpp46
-rw-r--r--src/plugins/texteditor/outlinefactory.h2
-rw-r--r--src/plugins/texteditor/refactoringchanges.cpp2
-rw-r--r--src/plugins/texteditor/semantichighlighter.cpp4
-rw-r--r--src/plugins/texteditor/snippets/plaintextsnippetprovider.cpp2
-rw-r--r--src/plugins/texteditor/syntaxhighlighter.cpp15
-rw-r--r--src/plugins/texteditor/textdocument.cpp20
-rw-r--r--src/plugins/texteditor/textdocument.h2
-rw-r--r--src/plugins/texteditor/texteditor.cpp58
-rw-r--r--src/plugins/texteditor/texteditor.h6
-rw-r--r--src/plugins/texteditor/texteditorsettings.cpp6
-rw-r--r--src/plugins/texteditor/textmark.cpp6
-rw-r--r--src/plugins/todo/cpptodoitemsscanner.cpp4
-rw-r--r--src/plugins/todo/qmljstodoitemsscanner.cpp4
-rw-r--r--src/plugins/todo/todoitemsprovider.cpp8
-rw-r--r--[-rwxr-xr-x]src/plugins/todo/todooutputpane.cpp11
-rw-r--r--[-rwxr-xr-x]src/plugins/todo/todooutputpane.h0
-rw-r--r--[-rwxr-xr-x]src/plugins/todo/todoplugin.cpp9
-rw-r--r--[-rwxr-xr-x]src/plugins/todo/todoplugin.h0
-rw-r--r--src/plugins/valgrind/callgrind/callgrindcontroller.cpp25
-rw-r--r--src/plugins/valgrind/callgrind/callgrindrunner.cpp13
-rw-r--r--src/plugins/valgrind/callgrindengine.cpp21
-rw-r--r--src/plugins/valgrind/callgrindtool.cpp109
-rw-r--r--src/plugins/valgrind/callgrindvisualisation.cpp49
-rw-r--r--src/plugins/valgrind/memcheck/memcheckrunner.cpp37
-rw-r--r--src/plugins/valgrind/memcheck/memcheckrunner.h1
-rw-r--r--src/plugins/valgrind/memcheckengine.cpp103
-rw-r--r--src/plugins/valgrind/memcheckengine.h22
-rw-r--r--src/plugins/valgrind/memcheckerrorview.cpp74
-rw-r--r--src/plugins/valgrind/memcheckerrorview.h4
-rw-r--r--src/plugins/valgrind/memchecktool.cpp73
-rw-r--r--src/plugins/valgrind/memchecktool.h17
-rw-r--r--src/plugins/valgrind/suppressiondialog.cpp12
-rw-r--r--src/plugins/valgrind/valgrind.qbs1
-rw-r--r--src/plugins/valgrind/valgrind_dependencies.pri1
-rw-r--r--src/plugins/valgrind/valgrindconfigwidget.cpp142
-rw-r--r--src/plugins/valgrind/valgrindengine.cpp27
-rw-r--r--src/plugins/valgrind/valgrindplugin.cpp18
-rw-r--r--src/plugins/valgrind/valgrindplugin.h2
-rw-r--r--src/plugins/valgrind/valgrindprocess.cpp65
-rw-r--r--src/plugins/valgrind/valgrindprocess.h2
-rw-r--r--src/plugins/valgrind/valgrindruncontrolfactory.cpp6
-rw-r--r--src/plugins/valgrind/valgrindrunner.cpp29
-rw-r--r--src/plugins/valgrind/valgrindrunner.h1
-rw-r--r--src/plugins/valgrind/valgrindtool.cpp5
-rw-r--r--src/plugins/valgrind/xmlprotocol/errorlistmodel.cpp2
-rw-r--r--src/plugins/valgrind/xmlprotocol/modelhelpers.cpp2
-rw-r--r--src/plugins/valgrind/xmlprotocol/stackmodel.cpp4
-rw-r--r--src/plugins/valgrind/xmlprotocol/threadedparser.cpp27
-rw-r--r--src/plugins/vcsbase/basecheckoutwizardfactory.cpp3
-rw-r--r--src/plugins/vcsbase/checkoutprogresswizardpage.cpp2
-rw-r--r--src/plugins/vcsbase/cleandialog.cpp4
-rw-r--r--src/plugins/vcsbase/nicknamedialog.cpp10
-rw-r--r--src/plugins/vcsbase/submiteditorfile.cpp9
-rw-r--r--src/plugins/vcsbase/submiteditorwidget.cpp2
-rw-r--r--src/plugins/vcsbase/submiteditorwidget.ui102
-rw-r--r--src/plugins/vcsbase/submitfilemodel.cpp11
-rw-r--r--src/plugins/vcsbase/vcsbase.pro6
-rw-r--r--src/plugins/vcsbase/vcsbase.qbs6
-rw-r--r--src/plugins/vcsbase/vcsbaseclient.cpp197
-rw-r--r--src/plugins/vcsbase/vcsbaseclient.h23
-rw-r--r--src/plugins/vcsbase/vcsbaseeditor.cpp57
-rw-r--r--src/plugins/vcsbase/vcsbaseeditor.h2
-rw-r--r--src/plugins/vcsbase/vcsbaseeditorparameterwidget.cpp21
-rw-r--r--src/plugins/vcsbase/vcsbaseeditorparameterwidget.h6
-rw-r--r--src/plugins/vcsbase/vcsbaseplugin.cpp114
-rw-r--r--src/plugins/vcsbase/vcsbaseplugin.h4
-rw-r--r--src/plugins/vcsbase/vcsbasesubmiteditor.cpp40
-rw-r--r--src/plugins/vcsbase/vcscommand.cpp27
-rw-r--r--src/plugins/vcsbase/vcsconfigurationpage.cpp91
-rw-r--r--src/plugins/vcsbase/vcsoutputwindow.cpp14
-rw-r--r--src/plugins/vcsbase/vcsoutputwindow.h4
-rw-r--r--src/plugins/vcsbase/vcsplugin.cpp18
-rw-r--r--src/plugins/vcsbase/wizard/vcsconfigurationpage.cpp180
-rw-r--r--src/plugins/vcsbase/wizard/vcsconfigurationpage.h (renamed from src/plugins/vcsbase/vcsconfigurationpage.h)27
-rw-r--r--src/plugins/vcsbase/wizard/vcsjsextension.cpp54
-rw-r--r--src/plugins/vcsbase/wizard/vcsjsextension.h51
-rw-r--r--src/plugins/welcome/welcome.qbs1
-rw-r--r--src/plugins/welcome/welcomeplugin.cpp219
-rw-r--r--src/plugins/winrt/winrtdebugsupport.cpp4
-rw-r--r--src/plugins/winrt/winrtdevice.cpp2
-rw-r--r--src/plugins/winrt/winrtpackagedeploymentstep.cpp8
-rw-r--r--src/plugins/winrt/winrtrunfactories.cpp6
-rw-r--r--src/share/qtcreator/externaltools/qmlscene.xml1
-rw-r--r--src/share/qtcreator/externaltools/qmlviewer.xml1
-rw-r--r--src/shared/help/bookmarkmanager.cpp49
-rw-r--r--src/shared/help/topicchooser.cpp14
-rw-r--r--src/shared/proparser/profileevaluator.cpp44
-rw-r--r--src/shared/proparser/profileevaluator.h2
m---------src/shared/qbs0
-rw-r--r--src/shared/scriptwrapper/README58
-rw-r--r--src/shared/scriptwrapper/interface_wrap_helpers.h89
-rw-r--r--src/shared/scriptwrapper/scriptwrapper.pri3
-rw-r--r--src/shared/scriptwrapper/wrap_helpers.h332
-rw-r--r--src/src.qbs1
-rw-r--r--src/tools/3rdparty/iossim/iossim.pro2
-rw-r--r--src/tools/3rdparty/iossim_1_8_2/iossim_1_8_2.pro2
-rw-r--r--src/tools/cplusplus-ast2png/cplusplus-ast2png.cpp653
-rw-r--r--src/tools/cplusplus-ast2png/cplusplus-ast2png.pro4
-rw-r--r--src/tools/cplusplus-ast2png/cplusplus-ast2png.qbs6
-rw-r--r--src/tools/cplusplus-ast2png/dumpers.inc1743
-rw-r--r--src/tools/cplusplus-ast2png/tests/templ01.cpp (renamed from src/plugins/qmldesigner/qmldesignerwarning.h)24
-rw-r--r--src/tools/cplusplus-frontend/cplusplus-frontend.cpp111
-rw-r--r--src/tools/cplusplus-frontend/cplusplus-frontend.pro4
-rw-r--r--src/tools/cplusplus-frontend/cplusplus-frontend.qbs6
-rw-r--r--src/tools/cplusplus-frontend/tests/t1.cpp85
-rw-r--r--src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp2
-rw-r--r--src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro14
-rw-r--r--src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.qbs7
-rw-r--r--src/tools/cplusplus-shared/CPlusPlusTool.qbs7
-rw-r--r--src/tools/cplusplus-shared/CPlusPlusToolUsingCustomUtils.qbs15
-rw-r--r--src/tools/cplusplus-shared/pp-configuration.inc (renamed from src/tools/cplusplus-tools-utils/pp-configuration.inc)0
-rw-r--r--src/tools/cplusplus-shared/tool.pri12
-rw-r--r--src/tools/cplusplus-shared/utils.cpp (renamed from src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp)2
-rw-r--r--src/tools/cplusplus-shared/utils.h (renamed from src/tools/cplusplus-tools-utils/cplusplus-tools-utils.h)0
-rw-r--r--src/tools/cplusplus-shared/utils.pri6
-rw-r--r--src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri22
-rw-r--r--src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp24
-rw-r--r--src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro17
-rw-r--r--src/tools/cplusplus-update-frontend/cplusplus-update-frontend.qbs12
-rw-r--r--src/tools/cplusplustools.qbs10
-rw-r--r--src/tools/icons/qtcreatoricons.svg351
-rw-r--r--src/tools/iostool/iostool.pro2
-rw-r--r--src/tools/tools.pro8
-rw-r--r--src/tools/tools.qbs1
1359 files changed, 41627 insertions, 26978 deletions
diff --git a/src/app/app.qbs b/src/app/app.qbs
index 844536ab13b..d02e79aac80 100644
--- a/src/app/app.qbs
+++ b/src/app/app.qbs
@@ -1,23 +1,18 @@
import qbs
-Application {
+QtcProduct {
+ type: ["application"]
name: project.ide_app_target
consoleApplication: qbs.debugInformation
cpp.rpaths: qbs.targetOS.contains("osx") ? ["@executable_path/.."]
: ["$ORIGIN/../" + project.libDirName + "/qtcreator"]
- cpp.defines: project.generalDefines
- cpp.linkerFlags: {
- if (qbs.buildVariant == "release" && (qbs.toolchain.contains("gcc") || qbs.toolchain.contains("mingw")))
- return ["-Wl,-s"]
- }
cpp.includePaths: [
"../shared/qtsingleapplication",
"../shared/qtlockedfile",
]
Depends { name: "app_version_header" }
- Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["widgets", "network"] }
Depends { name: "Utils" }
Depends { name: "ExtensionSystem" }
diff --git a/src/app/main.cpp b/src/app/main.cpp
index 45c401a37e5..a27986d5f00 100644
--- a/src/app/main.cpp
+++ b/src/app/main.cpp
@@ -36,6 +36,7 @@
#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
#include <qtsingleapplication.h>
+#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <QDebug>
@@ -56,6 +57,7 @@
#include <QApplication>
#include <QMessageBox>
#include <QStandardPaths>
+#include <QTemporaryDir>
#ifdef ENABLE_QT_BREAKPAD
#include <qtsystemexceptionhandler.h>
@@ -171,7 +173,7 @@ static bool copyRecursively(const QString &srcFilePath,
if (srcFileInfo.isDir()) {
QDir targetDir(tgtFilePath);
targetDir.cdUp();
- if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName()))
+ if (!targetDir.mkdir(Utils::FileName::fromString(tgtFilePath).fileName()))
return false;
QDir sourceDir(srcFilePath);
QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
@@ -338,10 +340,14 @@ int main(int argc, char **argv)
testOptionProvided = true;
}
}
+ QScopedPointer<QTemporaryDir> temporaryCleanSettingsDir;
if (settingsPath.isEmpty() && testOptionProvided) {
- settingsPath = QDir::tempPath() + QString::fromLatin1("/qtc-%1-test-settings")
- .arg(QLatin1String(Core::Constants::IDE_VERSION_LONG));
- settingsPath = QDir::cleanPath(settingsPath);
+ const QString settingsPathTemplate = QDir::cleanPath(QDir::tempPath()
+ + QString::fromLatin1("/qtc-test-settings-XXXXXX"));
+ temporaryCleanSettingsDir.reset(new QTemporaryDir(settingsPathTemplate));
+ if (!temporaryCleanSettingsDir->isValid())
+ return 1;
+ settingsPath = temporaryCleanSettingsDir->path();
}
if (!settingsPath.isEmpty())
QSettings::setPath(QSettings::IniFormat, QSettings::UserScope, settingsPath);
@@ -393,20 +399,8 @@ int main(int argc, char **argv)
}
// Make sure we honor the system's proxy settings
-#if defined(Q_OS_UNIX)
- QUrl proxyUrl(QString::fromLatin1(qgetenv("http_proxy")));
- if (proxyUrl.isValid()) {
- QNetworkProxy proxy(QNetworkProxy::HttpProxy, proxyUrl.host(),
- proxyUrl.port(), proxyUrl.userName(), proxyUrl.password());
- QNetworkProxy::setApplicationProxy(proxy);
-# if defined(Q_OS_MAC) // unix and mac
- } else {
- QNetworkProxyFactory::setUseSystemConfiguration(true);
-# endif
- }
-#else // windows
QNetworkProxyFactory::setUseSystemConfiguration(true);
-#endif
+
// Load
const QStringList pluginPaths = getPluginPaths() + customPluginPaths;
PluginManager::setPluginPaths(pluginPaths);
diff --git a/src/libs/3rdparty/botan/botan.cpp b/src/libs/3rdparty/botan/botan.cpp
index 0a859da7895..b7a9ddff42f 100644
--- a/src/libs/3rdparty/botan/botan.cpp
+++ b/src/libs/3rdparty/botan/botan.cpp
@@ -44444,7 +44444,7 @@ void ANSI_X931_RNG::add_entropy(const byte input[], size_t length)
}
/*
-* Check if the the PRNG is seeded
+* Check if the PRNG is seeded
*/
bool ANSI_X931_RNG::is_seeded() const
{
diff --git a/src/libs/3rdparty/botan/botan.pri b/src/libs/3rdparty/botan/botan.pri
index 6055e918064..b3a26e4e84c 100644
--- a/src/libs/3rdparty/botan/botan.pri
+++ b/src/libs/3rdparty/botan/botan.pri
@@ -48,7 +48,6 @@ win32 {
unix:*-g++* {
QMAKE_CFLAGS += -fPIC -fpermissive -finline-functions -Wno-long-long
QMAKE_CXXFLAGS += -fPIC -fpermissive -finline-functions -Wno-long-long
- QMAKE_CXXFLAGS_HIDESYMS -= -fvisibility-inlines-hidden # for ubuntu 7.04
}
linux*|freebsd* {
diff --git a/src/libs/3rdparty/cplusplus/Bind.cpp b/src/libs/3rdparty/cplusplus/Bind.cpp
index 0bedfd04f41..58e3815a8f6 100644
--- a/src/libs/3rdparty/cplusplus/Bind.cpp
+++ b/src/libs/3rdparty/cplusplus/Bind.cpp
@@ -33,7 +33,7 @@
#include <vector>
#include <string>
#include <memory>
-
+#include <sstream>
using namespace CPlusPlus;
@@ -459,6 +459,59 @@ bool Bind::visit(EnumeratorAST *ast)
return false;
}
+namespace {
+
+bool isInteger(const StringLiteral *stringLiteral)
+{
+ const int size = stringLiteral->size();
+ const char *chars = stringLiteral->chars();
+ for (int i = 0; i < size; ++i) {
+ if (!isdigit(chars[i]))
+ return false;
+ }
+ return true;
+}
+
+bool stringLiteralToInt(const StringLiteral *stringLiteral, int *output)
+{
+ if (!output)
+ return false;
+
+ if (!isInteger(stringLiteral)) {
+ *output = 0;
+ return false;
+ }
+
+ std::stringstream ss(std::string(stringLiteral->chars(), stringLiteral->size()));
+ const bool ok = !(ss >> *output).fail();
+ if (!ok)
+ *output = 0;
+
+ return ok;
+}
+
+void calculateConstantValue(const Symbol *symbol, EnumeratorDeclaration *e, Control *control)
+{
+ if (symbol) {
+ if (const Declaration *decl = symbol->asDeclaration()) {
+ if (const EnumeratorDeclaration *previousEnumDecl = decl->asEnumeratorDeclarator()) {
+ if (const StringLiteral *constantValue = previousEnumDecl->constantValue()) {
+ int constantValueAsInt = 0;
+ if (stringLiteralToInt(constantValue, &constantValueAsInt)) {
+ ++constantValueAsInt;
+ const std::string buffer
+ = std::to_string(static_cast<long long>(constantValueAsInt));
+ e->setConstantValue(control->stringLiteral(buffer.c_str(),
+ unsigned(buffer.size())));
+ }
+ }
+ }
+ }
+ }
+}
+
+} // anonymous namespace
+
void Bind::enumerator(EnumeratorAST *ast, Enum *symbol)
{
(void) symbol;
@@ -477,6 +530,10 @@ void Bind::enumerator(EnumeratorAST *ast, Enum *symbol)
if (ExpressionAST *expr = ast->expression)
e->setConstantValue(asStringLiteral(expr->firstToken(), expr->lastToken()));
+ else if (!symbol->isEmpty())
+ calculateConstantValue(*(symbol->memberEnd()-1), e, control());
+ else
+ e->setConstantValue(control()->stringLiteral("0", 1));
symbol->addMember(e);
}
@@ -1577,6 +1634,15 @@ bool Bind::visit(ConditionAST *ast)
unsigned sourceLocation = location(declaratorId->name, ast->firstToken());
Declaration *decl = control()->newDeclaration(sourceLocation, declaratorId->name->name);
decl->setType(type);
+
+ if (type.isAuto() && translationUnit()->languageFeatures().cxx11Enabled) {
+ const ExpressionAST *initializer = ast->declarator->initializer;
+
+ const unsigned startOfExpression = initializer->firstToken();
+ const unsigned endOfExpression = initializer->lastToken();
+ decl->setInitializer(asStringLiteral(startOfExpression, endOfExpression));
+ }
+
_scope->addMember(decl);
}
@@ -1861,7 +1927,7 @@ bool Bind::visit(SimpleDeclarationAST *ast)
for (DeclaratorListAST *it = ast->declarator_list; it; it = it->next) {
DeclaratorIdAST *declaratorId = 0;
- FullySpecifiedType declTy = this->declarator(it->value, type.qualifiedType(), &declaratorId);
+ FullySpecifiedType declTy = this->declarator(it->value, type, &declaratorId);
const Name *declName = 0;
unsigned sourceLocation = location(it->value, ast->firstToken());
diff --git a/src/libs/3rdparty/cplusplus/Control.cpp b/src/libs/3rdparty/cplusplus/Control.cpp
index 75f49d72b12..afdd6790560 100644
--- a/src/libs/3rdparty/cplusplus/Control.cpp
+++ b/src/libs/3rdparty/cplusplus/Control.cpp
@@ -827,7 +827,7 @@ TopLevelDeclarationProcessor *Control::topLevelDeclarationProcessor() const
return d->processor;
}
-void Control::setTopLevelDeclarationProcessor(CPlusPlus::TopLevelDeclarationProcessor *processor)
+void Control::setTopLevelDeclarationProcessor(TopLevelDeclarationProcessor *processor)
{
d->processor = processor;
}
diff --git a/src/libs/3rdparty/cplusplus/FullySpecifiedType.cpp b/src/libs/3rdparty/cplusplus/FullySpecifiedType.cpp
index 9685148baf9..f78e4e9338e 100644
--- a/src/libs/3rdparty/cplusplus/FullySpecifiedType.cpp
+++ b/src/libs/3rdparty/cplusplus/FullySpecifiedType.cpp
@@ -214,29 +214,7 @@ unsigned FullySpecifiedType::flags() const
void FullySpecifiedType::setFlags(unsigned flags)
{ _flags = flags; }
-void FullySpecifiedType::copySpecifiers(const FullySpecifiedType &type)
-{
- // class storage specifiers
- f._isFriend = type.f._isFriend;
- f._isAuto = type.f._isAuto;
- f._isRegister = type.f._isRegister;
- f._isStatic = type.f._isStatic;
- f._isExtern = type.f._isExtern;
- f._isMutable = type.f._isMutable;
- f._isTypedef = type.f._isTypedef;
-
- // function specifiers
- f._isInline = type.f._isInline;
- f._isVirtual = type.f._isVirtual;
- f._isOverride = type.f._isOverride;
- f._isFinal = type.f._isFinal;
- f._isExplicit = type.f._isExplicit;
-}
-
bool FullySpecifiedType::match(const FullySpecifiedType &otherTy, Matcher *matcher) const
{
- if (_flags != otherTy._flags)
- return false;
-
return type()->match(otherTy.type(), matcher);
}
diff --git a/src/libs/3rdparty/cplusplus/FullySpecifiedType.h b/src/libs/3rdparty/cplusplus/FullySpecifiedType.h
index bf376b3f7c2..7526a923c91 100644
--- a/src/libs/3rdparty/cplusplus/FullySpecifiedType.h
+++ b/src/libs/3rdparty/cplusplus/FullySpecifiedType.h
@@ -108,8 +108,6 @@ public:
FullySpecifiedType simplified() const;
- void copySpecifiers(const FullySpecifiedType &type);
-
unsigned flags() const;
void setFlags(unsigned flags);
diff --git a/src/libs/3rdparty/cplusplus/Lexer.cpp b/src/libs/3rdparty/cplusplus/Lexer.cpp
index 93e47045f30..3fb9a66bd24 100644
--- a/src/libs/3rdparty/cplusplus/Lexer.cpp
+++ b/src/libs/3rdparty/cplusplus/Lexer.cpp
@@ -305,24 +305,27 @@ void Lexer::scan_helper(Token *tok)
tok->f.kind = T_ERROR;
}
} else if (std::isdigit(_yychar)) {
+ if (f._ppMode) {
+ scanPreprocessorNumber(tok, true);
+ break;
+ }
+
const char *yytext = _currentChar - 2;
- do {
- if (_yychar == 'e' || _yychar == 'E') {
- yyinp();
- if (_yychar == '-' || _yychar == '+') {
- yyinp();
- // ### CPP_CHECK(std::isdigit(_yychar));
- }
- } else if (std::isalnum(_yychar) || _yychar == '.') {
+ yyinp();
+ scanDigitSequence(); // this is optional: we already skipped over the first digit
+ scanExponentPart();
+ scanOptionalFloatingSuffix();
+ if (std::isalnum(_yychar) || _yychar == '_') {
+ do {
yyinp();
- } else {
- break;
- }
- } while (_yychar);
- int yylen = _currentChar - yytext;
- tok->f.kind = T_NUMERIC_LITERAL;
- if (control())
- tok->number = control()->numericLiteral(yytext, yylen);
+ } while (std::isalnum(_yychar) || _yychar == '_');
+ tok->f.kind = T_ERROR;
+ } else {
+ int yylen = _currentChar - yytext;
+ tok->f.kind = T_NUMERIC_LITERAL;
+ if (control())
+ tok->number = control()->numericLiteral(yytext, yylen);
+ }
} else {
tok->f.kind = T_DOT;
}
@@ -651,7 +654,10 @@ void Lexer::scan_helper(Token *tok)
} else if (std::isalpha(ch) || ch == '_' || ch == '$' || isByteOfMultiByteCodePoint(ch)) {
scanIdentifier(tok, _currentChar - _tokenStart - 1);
} else if (std::isdigit(ch)) {
- scanNumericLiteral(tok);
+ if (f._ppMode)
+ scanPreprocessorNumber(tok, false);
+ else
+ scanNumericLiteral(tok);
} else {
tok->f.kind = T_ERROR;
}
@@ -776,26 +782,141 @@ void Lexer::scanUntilQuote(Token *tok, unsigned char quote)
tok->string = control()->stringLiteral(yytext, yylen);
}
+bool Lexer::scanDigitSequence()
+{
+ if (!std::isdigit(_yychar))
+ return false;
+ yyinp();
+ while (std::isdigit(_yychar))
+ yyinp();
+ return true;
+}
+
+bool Lexer::scanExponentPart()
+{
+ if (_yychar != 'e' && _yychar != 'E')
+ return false;
+ yyinp();
+ if (_yychar == '+' || _yychar == '-')
+ yyinp();
+ return scanDigitSequence();
+}
+
+void Lexer::scanOptionalFloatingSuffix()
+{
+ if (_yychar == 'f' || _yychar == 'l' || _yychar == 'F' || _yychar == 'L')
+ yyinp();
+}
+
+void Lexer::scanOptionalIntegerSuffix(bool allowU)
+{
+ switch(_yychar) {
+ case 'u':
+ case 'U':
+ if (allowU) {
+ yyinp();
+ scanOptionalIntegerSuffix(false);
+ }
+ return;
+ case 'l':
+ yyinp();
+ if (_yychar == 'l')
+ yyinp();
+ return;
+ case 'L':
+ yyinp();
+ if (_yychar == 'L')
+ yyinp();
+ return;
+ default:
+ return;
+ }
+}
+
void Lexer::scanNumericLiteral(Token *tok)
{
const char *yytext = _currentChar - 1;
+ if (*yytext == '0' && _yychar) {
+ if (_yychar == 'x' || _yychar == 'X') {
+ yyinp();
+ while (std::isdigit(_yychar) ||
+ (_yychar >= 'a' && _yychar <= 'f') ||
+ (_yychar >= 'A' && _yychar <= 'F')) {
+ yyinp();
+ }
+ scanOptionalIntegerSuffix();
+ goto theEnd;
+ } else if (_yychar == 'b' || _yychar == 'B') { // see n3472
+ yyinp();
+ while (_yychar == '0' || _yychar == '1')
+ yyinp();
+ scanOptionalIntegerSuffix();
+ goto theEnd;
+ } else if (_yychar >= '0' && _yychar <= '7') {
+ do {
+ yyinp();
+ } while (_yychar >= '0' && _yychar <= '7');
+ scanOptionalIntegerSuffix();
+ goto theEnd;
+ }
+ }
+
+ while (_yychar) {
+ if (_yychar == '.') {
+ yyinp();
+ scanDigitSequence(); // this is optional: "1." is a valid floating point number
+ scanExponentPart();
+ scanOptionalFloatingSuffix();
+ break;
+ } else if (_yychar == 'e' || _yychar == 'E') {
+ if (scanExponentPart())
+ scanOptionalFloatingSuffix();
+ break;
+ } else if (std::isdigit(_yychar)) {
+ yyinp();
+ } else {
+ scanOptionalIntegerSuffix();
+ break;
+ }
+ }
+
+theEnd:
+ if (std::isalnum(_yychar) || _yychar == '_') {
+ do {
+ yyinp();
+ } while (std::isalnum(_yychar) || _yychar == '_');
+ tok->f.kind = T_ERROR;
+ } else {
+ int yylen = _currentChar - yytext;
+ tok->f.kind = T_NUMERIC_LITERAL;
+ if (control())
+ tok->number = control()->numericLiteral(yytext, yylen);
+ }
+}
+
+void Lexer::scanPreprocessorNumber(Token *tok, bool dotAlreadySkipped)
+{
+ const char *yytext = _currentChar - (dotAlreadySkipped ? 2 : 1);
+ if (dotAlreadySkipped &&
+ (!_yychar || (_yychar && !std::isdigit(_yychar)))) {
+ tok->f.kind = T_DOT;
+ return;
+ }
+
while (_yychar) {
if (_yychar == 'e' || _yychar == 'E') {
yyinp();
- if (_yychar == '-' || _yychar == '+') {
+ if (_yychar == '+' || _yychar == '-')
yyinp();
- // ### CPP_CHECK(std::isdigit(_yychar));
- }
- } else if (std::isalnum(_yychar) || _yychar == '.') {
+ } else if (std::isalnum(_yychar) || _yychar == '_' || _yychar == '.') {
yyinp();
} else {
break;
}
}
- int yylen = _currentChar - yytext;
+ int yylen = _currentChar - yytext;
tok->f.kind = T_NUMERIC_LITERAL;
-
if (control())
tok->number = control()->numericLiteral(yytext, yylen);
}
diff --git a/src/libs/3rdparty/cplusplus/Lexer.h b/src/libs/3rdparty/cplusplus/Lexer.h
index 78396a0e600..0309c69950e 100644
--- a/src/libs/3rdparty/cplusplus/Lexer.h
+++ b/src/libs/3rdparty/cplusplus/Lexer.h
@@ -61,6 +61,9 @@ public:
LanguageFeatures languageFeatures() const { return _languageFeatures; }
void setLanguageFeatures(LanguageFeatures features) { _languageFeatures = features; }
+ void setPreprocessorMode(bool onoff)
+ { f._ppMode = onoff; }
+
public:
static void yyinp_utf8(const char *&currentSourceChar, unsigned char &yychar,
unsigned &utf16charCounter)
@@ -95,7 +98,12 @@ private:
void scanRawStringLiteral(Token *tok, unsigned char hint = 0);
void scanCharLiteral(Token *tok, unsigned char hint = 0);
void scanUntilQuote(Token *tok, unsigned char quote);
+ bool scanDigitSequence();
+ bool scanExponentPart();
+ void scanOptionalFloatingSuffix();
+ void scanOptionalIntegerSuffix(bool allowU = true);
void scanNumericLiteral(Token *tok);
+ void scanPreprocessorNumber(Token *tok, bool dotAlreadySkipped);
void scanIdentifier(Token *tok, unsigned extraProcessedChars = 0);
void scanBackslash(Kind type);
void scanCppComment(Kind type);
@@ -115,6 +123,7 @@ private:
unsigned _scanCommentTokens: 1;
unsigned _scanKeywords: 1;
unsigned _scanAngleStringLiteralTokens: 1;
+ unsigned _ppMode: 1;
};
struct State {
diff --git a/src/libs/3rdparty/cplusplus/MemoryPool.cpp b/src/libs/3rdparty/cplusplus/MemoryPool.cpp
index 5c1041d16ca..bcd5154b729 100644
--- a/src/libs/3rdparty/cplusplus/MemoryPool.cpp
+++ b/src/libs/3rdparty/cplusplus/MemoryPool.cpp
@@ -81,21 +81,6 @@ void *MemoryPool::allocate_helper(size_t size)
return addr;
}
-RecursiveMemoryPool::RecursiveMemoryPool(MemoryPool *pool)
- : _pool(pool),
- _blockCount(pool->_blockCount),
- _ptr(pool->_ptr),
- _end(pool->_end)
-{
-}
-
-RecursiveMemoryPool::~RecursiveMemoryPool()
-{
- _pool->_blockCount = _blockCount;
- _pool->_ptr = _ptr;
- _pool->_end = _end;
-}
-
Managed::Managed()
{ }
diff --git a/src/libs/3rdparty/cplusplus/MemoryPool.h b/src/libs/3rdparty/cplusplus/MemoryPool.h
index 3b2f1999384..ee56aaf9deb 100644
--- a/src/libs/3rdparty/cplusplus/MemoryPool.h
+++ b/src/libs/3rdparty/cplusplus/MemoryPool.h
@@ -27,7 +27,6 @@
namespace CPlusPlus {
class MemoryPool;
-class RecursiveMemoryPool;
class CPLUSPLUS_EXPORT MemoryPool
{
@@ -66,20 +65,6 @@ private:
BLOCK_SIZE = 8 * 1024,
DEFAULT_BLOCK_COUNT = 8
};
-
- friend class RecursiveMemoryPool;
-};
-
-class CPLUSPLUS_EXPORT RecursiveMemoryPool
-{
- MemoryPool *_pool;
- int _blockCount;
- char *_ptr;
- char *_end;
-
-public:
- RecursiveMemoryPool(MemoryPool *pool);
- ~RecursiveMemoryPool();
};
class CPLUSPLUS_EXPORT Managed
@@ -98,5 +83,4 @@ public:
} // namespace CPlusPlus
-
#endif // CPLUSPLUS_MEMORYPOOL_H
diff --git a/src/libs/3rdparty/cplusplus/Parser.cpp b/src/libs/3rdparty/cplusplus/Parser.cpp
index c98f92cc37b..75970b16715 100644
--- a/src/libs/3rdparty/cplusplus/Parser.cpp
+++ b/src/libs/3rdparty/cplusplus/Parser.cpp
@@ -165,6 +165,7 @@ public:
Expression,
ExpressionList,
ParameterDeclarationClause,
+ TemplateId,
TypeId
};
@@ -265,13 +266,12 @@ inline void debugPrintCheckCache(bool) {}
return true; \
}
-Parser::Parser(TranslationUnit *unit, int retryParseDeclarationLimit)
+Parser::Parser(TranslationUnit *unit)
: _translationUnit(unit),
_control(unit->control()),
_pool(unit->memoryPool()),
_languageFeatures(unit->languageFeatures()),
_tokenIndex(1),
- _retryParseDeclarationLimit(retryParseDeclarationLimit),
_templateArguments(0),
_inFunctionBody(false),
_inExpressionStatement(false),
@@ -311,20 +311,6 @@ bool Parser::skipUntil(int token)
return false;
}
-void Parser::skipUntilAfterSemicolonOrRightBrace()
-{
- while (int tk = LA()) {
- switch (tk) {
- case T_SEMICOLON:
- case T_RBRACE:
- consumeToken();
- return;
- default:
- consumeToken();
- }
- }
-}
-
void Parser::skipUntilDeclaration()
{
for (; ; consumeToken()) {
@@ -525,6 +511,7 @@ bool Parser::parseClassOrNamespaceName(NameAST *&node)
bool Parser::parseTemplateId(NameAST *&node, unsigned template_token)
{
DEBUG_THIS_RULE();
+ CHECK_CACHE(ASTCache::TemplateId, NameAST);
const unsigned start = cursor();
@@ -538,14 +525,17 @@ bool Parser::parseTemplateId(NameAST *&node, unsigned template_token)
if (maybeSplitGreaterGreaterToken() || LA() == T_GREATER) {
ast->greater_token = consumeToken();
node = ast;
- return true;
+ const bool result = true;
+ _astCache->insert(ASTCache::TemplateId, start, node, cursor(), result);
+ return result;
}
}
}
+ const bool result = false;
+ _astCache->insert(ASTCache::TemplateId, start, 0, cursor(), result);
rewind(start);
-
- return false;
+ return result;
}
bool Parser::parseNestedNameSpecifier(NestedNameSpecifierListAST *&node,
@@ -641,25 +631,19 @@ bool Parser::parseTranslationUnit(TranslationUnitAST *&node)
TranslationUnitAST *ast = new (_pool) TranslationUnitAST;
DeclarationListAST **decl = &ast->declaration_list;
- int declarationsInRowFailedToParse = 0;
-
while (LA()) {
unsigned start_declaration = cursor();
DeclarationAST *declaration = 0;
if (parseDeclaration(declaration)) {
- declarationsInRowFailedToParse = 0;
*decl = new (_pool) DeclarationListAST;
(*decl)->value = declaration;
decl = &(*decl)->next;
} else {
error(start_declaration, "expected a declaration");
rewind(start_declaration + 1);
- if (++declarationsInRowFailedToParse == _retryParseDeclarationLimit)
- skipUntilAfterSemicolonOrRightBrace();
- else
- skipUntilDeclaration();
+ skipUntilDeclaration();
}
@@ -808,8 +792,6 @@ bool Parser::parseLinkageBody(DeclarationAST *&node)
ast->lbrace_token = consumeToken();
DeclarationListAST **declaration_ptr = &ast->declaration_list;
- int declarationsInRowFailedToParse = 0;
-
while (int tk = LA()) {
if (tk == T_RBRACE)
break;
@@ -817,17 +799,13 @@ bool Parser::parseLinkageBody(DeclarationAST *&node)
unsigned start_declaration = cursor();
DeclarationAST *declaration = 0;
if (parseDeclaration(declaration)) {
- declarationsInRowFailedToParse = 0;
*declaration_ptr = new (_pool) DeclarationListAST;
(*declaration_ptr)->value = declaration;
declaration_ptr = &(*declaration_ptr)->next;
} else {
error(start_declaration, "expected a declaration");
rewind(start_declaration + 1);
- if (++declarationsInRowFailedToParse == _retryParseDeclarationLimit)
- skipUntilAfterSemicolonOrRightBrace();
- else
- skipUntilDeclaration();
+ skipUntilDeclaration();
}
_templateArgumentList.clear();
diff --git a/src/libs/3rdparty/cplusplus/Parser.h b/src/libs/3rdparty/cplusplus/Parser.h
index 5f0a182bd12..4a2a6dfb7e0 100644
--- a/src/libs/3rdparty/cplusplus/Parser.h
+++ b/src/libs/3rdparty/cplusplus/Parser.h
@@ -33,7 +33,7 @@ namespace CPlusPlus {
class CPLUSPLUS_EXPORT Parser
{
public:
- Parser(TranslationUnit *translationUnit, int retryParseDeclarationLimit);
+ Parser(TranslationUnit *translationUnit);
~Parser();
bool parseTranslationUnit(TranslationUnitAST *&node);
@@ -254,7 +254,6 @@ public:
bool parseDesignator(DesignatorAST *&node);
bool skipUntil(int token);
- void skipUntilAfterSemicolonOrRightBrace();
void skipUntilDeclaration();
bool skipUntilStatement();
bool skip(int l, int r);
@@ -317,7 +316,6 @@ private:
MemoryPool *_pool;
LanguageFeatures _languageFeatures;
unsigned _tokenIndex;
- int _retryParseDeclarationLimit;
bool _templateArguments: 1;
bool _inFunctionBody: 1;
bool _inExpressionStatement: 1;
diff --git a/src/libs/3rdparty/cplusplus/Scope.cpp b/src/libs/3rdparty/cplusplus/Scope.cpp
index eff79368e44..107df10dffd 100644
--- a/src/libs/3rdparty/cplusplus/Scope.cpp
+++ b/src/libs/3rdparty/cplusplus/Scope.cpp
@@ -28,9 +28,9 @@
#include <cstring>
-using namespace CPlusPlus;
+namespace CPlusPlus {
-class CPlusPlus::SymbolTable
+class SymbolTable
{
SymbolTable(const SymbolTable &other);
void operator =(const SymbolTable &other);
@@ -238,7 +238,7 @@ Scope::Scope(Clone *clone, Subst *subst, Scope *original)
, _startOffset(original->_startOffset)
, _endOffset(original->_endOffset)
{
- for (iterator it = original->firstMember(), end = original->lastMember(); it != end; ++it)
+ for (iterator it = original->memberBegin(), end = original->memberEnd(); it != end; ++it)
addMember(clone->symbol(*it, subst));
}
@@ -267,11 +267,11 @@ Symbol *Scope::memberAt(unsigned index) const
{ return _members ? _members->symbolAt(index) : 0; }
/// Returns the first Symbol in the scope.
-Scope::iterator Scope::firstMember() const
+Scope::iterator Scope::memberBegin() const
{ return _members ? _members->firstSymbol() : 0; }
/// Returns the last Symbol in the scope.
-Scope::iterator Scope::lastMember() const
+Scope::iterator Scope::memberEnd() const
{ return _members ? _members->lastSymbol() : 0; }
Symbol *Scope::find(const Identifier *id) const
@@ -293,3 +293,5 @@ unsigned Scope::endOffset() const
void Scope::setEndOffset(unsigned offset)
{ _endOffset = offset; }
+
+} // namespace CPlusPlus
diff --git a/src/libs/3rdparty/cplusplus/Scope.h b/src/libs/3rdparty/cplusplus/Scope.h
index 73276d3b44d..142138698ee 100644
--- a/src/libs/3rdparty/cplusplus/Scope.h
+++ b/src/libs/3rdparty/cplusplus/Scope.h
@@ -48,11 +48,11 @@ public:
typedef Symbol **iterator;
- /// Returns the first Symbol in the scope.
- iterator firstMember() const;
+ /// Returns member iterator to the beginning.
+ iterator memberBegin() const;
- /// Returns the last Symbol in the scope.
- iterator lastMember() const;
+ /// Returns member iterator to the end.
+ iterator memberEnd() const;
Symbol *find(const Identifier *id) const;
Symbol *find(OperatorNameId::Kind operatorId) const;
diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
index 4f1ff721390..ea180af5bfd 100644
--- a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
+++ b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
@@ -49,8 +49,7 @@ TranslationUnit::TranslationUnit(Control *control, const StringLiteral *fileId)
_lastSourceChar(0),
_pool(0),
_ast(0),
- _flags(0),
- _retryParseDeclarationLimit(defaultRetryParseDeclarationLimit())
+ _flags(0)
{
_tokens = new std::vector<Token>();
_comments = new std::vector<Token>();
@@ -300,7 +299,7 @@ bool TranslationUnit::parse(ParseMode mode)
f._parsed = true;
- Parser parser(this, _retryParseDeclarationLimit);
+ Parser parser(this);
bool parsed = false;
switch (mode) {
diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.h b/src/libs/3rdparty/cplusplus/TranslationUnit.h
index eb4e1f2e3a5..94eb81666be 100644
--- a/src/libs/3rdparty/cplusplus/TranslationUnit.h
+++ b/src/libs/3rdparty/cplusplus/TranslationUnit.h
@@ -149,9 +149,6 @@ public:
LanguageFeatures languageFeatures() const { return _languageFeatures; }
void setLanguageFeatures(LanguageFeatures features) { _languageFeatures = features; }
- static int defaultRetryParseDeclarationLimit() { return 2; }
- void setRetryParseDeclarationLimit(int limit) { _retryParseDeclarationLimit = limit; }
-
private:
struct PPLine {
unsigned utf16charOffset;
@@ -213,8 +210,6 @@ private:
Flags f;
};
LanguageFeatures _languageFeatures;
-
- int _retryParseDeclarationLimit;
};
} // namespace CPlusPlus
diff --git a/src/libs/cplusplus/CppDocument.cpp b/src/libs/cplusplus/CppDocument.cpp
index 97da6ac555c..57b612e90a3 100644
--- a/src/libs/cplusplus/CppDocument.cpp
+++ b/src/libs/cplusplus/CppDocument.cpp
@@ -503,7 +503,7 @@ QString Document::functionAt(int line, int column, int *lineOpeningDeclaratorPar
if (line < 1 || column < 1)
return QString();
- CPlusPlus::Symbol *symbol = lastVisibleSymbolAt(line, column);
+ Symbol *symbol = lastVisibleSymbolAt(line, column);
if (!symbol)
return QString();
@@ -623,13 +623,6 @@ void Document::tokenize()
_translationUnit->tokenize();
}
-void Document::setRetryHarderToParseDeclarations(bool yesno)
-{
- _translationUnit->setRetryParseDeclarationLimit(
- yesno ? 1000
- : TranslationUnit::defaultRetryParseDeclarationLimit());
-}
-
bool Document::isParsed() const
{
return _translationUnit->isParsed();
@@ -741,17 +734,17 @@ bool Snapshot::isEmpty() const
return _documents.isEmpty();
}
-Snapshot::const_iterator Snapshot::find(const QString &fileName) const
+Snapshot::const_iterator Snapshot::find(const Utils::FileName &fileName) const
{
return _documents.find(fileName);
}
-void Snapshot::remove(const QString &fileName)
+void Snapshot::remove(const Utils::FileName &fileName)
{
_documents.remove(fileName);
}
-bool Snapshot::contains(const QString &fileName) const
+bool Snapshot::contains(const Utils::FileName &fileName) const
{
return _documents.contains(fileName);
}
@@ -759,15 +752,15 @@ bool Snapshot::contains(const QString &fileName) const
void Snapshot::insert(Document::Ptr doc)
{
if (doc) {
- _documents.insert(doc->fileName(), doc);
+ _documents.insert(Utils::FileName::fromString(doc->fileName()), doc);
m_deps.files.clear(); // Will trigger re-build when accessed.
}
}
Document::Ptr Snapshot::preprocessedDocument(const QByteArray &source,
- const QString &fileName) const
+ const Utils::FileName &fileName) const
{
- Document::Ptr newDoc = Document::create(fileName);
+ Document::Ptr newDoc = Document::create(fileName.toString());
if (Document::Ptr thisDocument = document(fileName)) {
newDoc->_revision = thisDocument->_revision;
newDoc->_editorRevision = thisDocument->_editorRevision;
@@ -821,7 +814,7 @@ QList<Snapshot::IncludeLocation> Snapshot::includeLocationsOfDocument(const QStr
return result;
}
-QStringList Snapshot::filesDependingOn(const QString &fileName) const
+Utils::FileNameList Snapshot::filesDependingOn(const Utils::FileName &fileName) const
{
updateDependencyTable();
return m_deps.filesDependingOn(fileName);
@@ -850,7 +843,7 @@ void Snapshot::allIncludesForDocument_helper(const QString &fileName, QSet<QStri
}
}
-Document::Ptr Snapshot::document(const QString &fileName) const
+Document::Ptr Snapshot::document(const Utils::FileName &fileName) const
{
return _documents.value(fileName);
}
diff --git a/src/libs/cplusplus/CppDocument.h b/src/libs/cplusplus/CppDocument.h
index 1750fb81e95..ec2514894ec 100644
--- a/src/libs/cplusplus/CppDocument.h
+++ b/src/libs/cplusplus/CppDocument.h
@@ -37,6 +37,8 @@
#include <cplusplus/PreprocessorClient.h>
#include <cplusplus/DependencyTable.h>
+#include <utils/fileutils.h>
+
#include <QSharedPointer>
#include <QDateTime>
#include <QHash>
@@ -127,7 +129,6 @@ public:
bool isTokenized() const;
void tokenize();
- void setRetryHarderToParseDeclarations(bool yesno);
bool isParsed() const;
bool parse(ParseMode mode = ParseTranlationUnit);
@@ -395,7 +396,7 @@ private:
class CPLUSPLUS_EXPORT Snapshot
{
- typedef QHash<QString, Document::Ptr> Base;
+ typedef QHash<Utils::FileName, Document::Ptr> Base;
public:
Snapshot();
@@ -409,20 +410,32 @@ public:
bool isEmpty() const;
void insert(Document::Ptr doc); // ### remove
- void remove(const QString &fileName); // ### remove
+ void remove(const Utils::FileName &fileName); // ### remove
+ void remove(const QString &fileName)
+ { remove(Utils::FileName::fromString(fileName)); }
const_iterator begin() const { return _documents.begin(); }
const_iterator end() const { return _documents.end(); }
- bool contains(const QString &fileName) const;
- Document::Ptr document(const QString &fileName) const;
+ bool contains(const Utils::FileName &fileName) const;
+ bool contains(const QString &fileName) const
+ { return contains(Utils::FileName::fromString(fileName)); }
+
+ Document::Ptr document(const Utils::FileName &fileName) const;
+ Document::Ptr document(const QString &fileName) const
+ { return document(Utils::FileName::fromString(fileName)); }
- const_iterator find(const QString &fileName) const;
+ const_iterator find(const Utils::FileName &fileName) const;
+ const_iterator find(const QString &fileName) const
+ { return find(Utils::FileName::fromString(fileName)); }
Snapshot simplified(Document::Ptr doc) const;
Document::Ptr preprocessedDocument(const QByteArray &source,
- const QString &fileName) const;
+ const Utils::FileName &fileName) const;
+ Document::Ptr preprocessedDocument(const QByteArray &source,
+ const QString &fileName) const
+ { return preprocessedDocument(source, Utils::FileName::fromString(fileName)); }
Document::Ptr documentFromSource(const QByteArray &preprocessedDocument,
const QString &fileName) const;
@@ -430,7 +443,9 @@ public:
QSet<QString> allIncludesForDocument(const QString &fileName) const;
QList<IncludeLocation> includeLocationsOfDocument(const QString &fileName) const;
- QStringList filesDependingOn(const QString &fileName) const;
+ Utils::FileNameList filesDependingOn(const Utils::FileName &fileName) const;
+ Utils::FileNameList filesDependingOn(const QString &fileName) const
+ { return filesDependingOn(Utils::FileName::fromString(fileName)); }
void updateDependencyTable() const;
bool operator==(const Snapshot &other) const;
diff --git a/src/libs/cplusplus/DependencyTable.cpp b/src/libs/cplusplus/DependencyTable.cpp
index 6df25cf4eda..b26c41574ad 100644
--- a/src/libs/cplusplus/DependencyTable.cpp
+++ b/src/libs/cplusplus/DependencyTable.cpp
@@ -34,13 +34,14 @@
using namespace CPlusPlus;
-QStringList DependencyTable::filesDependingOn(const QString &fileName) const
+Utils::FileNameList DependencyTable::filesDependingOn(const Utils::FileName &fileName) const
{
+ Utils::FileNameList deps;
+
int index = fileIndex.value(fileName, -1);
if (index == -1)
- return QStringList();
+ return deps;
- QStringList deps;
for (int i = 0; i < files.size(); ++i) {
const QBitArray &bits = includeMap.at(i);
@@ -53,7 +54,6 @@ QStringList DependencyTable::filesDependingOn(const QString &fileName) const
void DependencyTable::build(const Snapshot &snapshot)
{
- includesPerFile.clear();
files.clear();
fileIndex.clear();
includes.clear();
@@ -71,15 +71,14 @@ void DependencyTable::build(const Snapshot &snapshot)
}
for (int i = 0; i < files.size(); ++i) {
- const QString fileName = files.at(i);
- if (Document::Ptr doc = snapshot.document(files.at(i))) {
+ const Utils::FileName &fileName = files.at(i);
+ if (Document::Ptr doc = snapshot.document(fileName)) {
QBitArray bitmap(files.size());
QList<int> directIncludes;
const QStringList documentIncludes = doc->includedFiles();
- includesPerFile.insert(fileName, documentIncludes);
foreach (const QString &includedFile, documentIncludes) {
- int index = fileIndex.value(includedFile);
+ int index = fileIndex.value(Utils::FileName::fromString(includedFile));
if (index == -1)
continue;
diff --git a/src/libs/cplusplus/DependencyTable.h b/src/libs/cplusplus/DependencyTable.h
index 2fdefcdcc55..e0c668245b6 100644
--- a/src/libs/cplusplus/DependencyTable.h
+++ b/src/libs/cplusplus/DependencyTable.h
@@ -33,6 +33,8 @@
#include <cplusplus/CPlusPlusForwardDeclarations.h>
+#include <utils/fileutils.h>
+
#include <QBitArray>
#include <QHash>
#include <QString>
@@ -48,11 +50,10 @@ class CPLUSPLUS_EXPORT DependencyTable
private:
friend class Snapshot;
void build(const Snapshot &snapshot);
- QStringList filesDependingOn(const QString &fileName) const;
+ Utils::FileNameList filesDependingOn(const Utils::FileName &fileName) const;
- QHash<QString, QStringList> includesPerFile;
- QVector<QString> files;
- QHash<QString, int> fileIndex;
+ QVector<Utils::FileName> files;
+ QHash<Utils::FileName, int> fileIndex;
QHash<int, QList<int> > includes;
QVector<QBitArray> includeMap;
};
diff --git a/src/libs/cplusplus/FastPreprocessor.cpp b/src/libs/cplusplus/FastPreprocessor.cpp
index b3386f52e13..f4b863679b1 100644
--- a/src/libs/cplusplus/FastPreprocessor.cpp
+++ b/src/libs/cplusplus/FastPreprocessor.cpp
@@ -40,11 +40,14 @@ using namespace CPlusPlus;
FastPreprocessor::FastPreprocessor(const Snapshot &snapshot)
: _snapshot(snapshot)
, _preproc(this, &_env)
+ , _addIncludesToCurrentDoc(false)
{ }
QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QByteArray &source)
{
std::swap(newDoc, _currentDoc);
+ _addIncludesToCurrentDoc = _currentDoc->resolvedIncludes().isEmpty()
+ && _currentDoc->unresolvedIncludes().isEmpty();
const QString fileName = _currentDoc->fileName();
_preproc.setExpandFunctionlikeMacros(false);
_preproc.setKeepComments(true);
@@ -53,8 +56,8 @@ QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QByteArray &source)
_merged.insert(fileName);
for (Snapshot::const_iterator i = _snapshot.begin(), ei = _snapshot.end(); i != ei; ++i) {
- if (isInjectedFile(i.key()))
- mergeEnvironment(i.key());
+ if (isInjectedFile(i.key().toString()))
+ mergeEnvironment(i.key().toString());
}
foreach (const Document::Include &i, doc->resolvedIncludes())
@@ -72,9 +75,11 @@ void FastPreprocessor::sourceNeeded(unsigned line, const QString &fileName, Incl
{
Q_UNUSED(initialIncludes)
Q_ASSERT(_currentDoc);
- // CHECKME: Is that cleanName needed?
- QString cleanName = QDir::cleanPath(fileName);
- _currentDoc->addIncludeFile(Document::Include(fileName, cleanName, line, mode));
+ if (_addIncludesToCurrentDoc) {
+ // CHECKME: Is that cleanName needed?
+ const QString cleanName = QDir::cleanPath(fileName);
+ _currentDoc->addIncludeFile(Document::Include(fileName, cleanName, line, mode));
+ }
mergeEnvironment(fileName);
}
diff --git a/src/libs/cplusplus/FastPreprocessor.h b/src/libs/cplusplus/FastPreprocessor.h
index 8556ebc601e..c5f4588a74a 100644
--- a/src/libs/cplusplus/FastPreprocessor.h
+++ b/src/libs/cplusplus/FastPreprocessor.h
@@ -49,6 +49,7 @@ class CPLUSPLUS_EXPORT FastPreprocessor: public Client
Preprocessor _preproc;
QSet<QString> _merged;
Document::Ptr _currentDoc;
+ bool _addIncludesToCurrentDoc;
void mergeEnvironment(const QString &fileName);
diff --git a/src/libs/cplusplus/LookupContext.cpp b/src/libs/cplusplus/LookupContext.cpp
index fdbbf744449..862ff1850ef 100644
--- a/src/libs/cplusplus/LookupContext.cpp
+++ b/src/libs/cplusplus/LookupContext.cpp
@@ -820,22 +820,38 @@ ClassOrNamespace *ClassOrNamespace::findType(const Name *name)
return lookupType_helper(name, &processed, /*searchInEnclosingScope =*/ false, this);
}
-ClassOrNamespace *ClassOrNamespace::findBlock(Block *block)
+ClassOrNamespace *ClassOrNamespace::findBlock_helper(Block *block,
+ QSet<ClassOrNamespace *> *processed,
+ bool searchInEnclosingScope)
{
- 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;
+ for (ClassOrNamespace *binding = this; binding; binding = binding->_parent) {
+ if (processed->contains(binding))
+ break;
+ processed->insert(binding);
+ binding->flush();
+ auto end = binding->_blocks.end();
+ auto citBlock = binding->_blocks.find(block);
+ if (citBlock != end)
+ return citBlock.value();
+
+ for (citBlock = binding->_blocks.begin(); citBlock != end; ++citBlock) {
+ if (ClassOrNamespace *foundNestedBlock =
+ citBlock.value()->findBlock_helper(block, processed, false)) {
+ return foundNestedBlock;
+ }
+ }
+ if (!searchInEnclosingScope)
+ break;
}
-
return 0;
}
+ClassOrNamespace *ClassOrNamespace::findBlock(Block *block)
+{
+ QSet<ClassOrNamespace *> processed;
+ return findBlock_helper(block, &processed, true);
+}
+
Symbol *ClassOrNamespace::lookupInScope(const QList<const Name *> &fullName)
{
if (!_scopeLookupCache) {
diff --git a/src/libs/cplusplus/LookupContext.h b/src/libs/cplusplus/LookupContext.h
index 5b35281e8c1..dbee30afabf 100644
--- a/src/libs/cplusplus/LookupContext.h
+++ b/src/libs/cplusplus/LookupContext.h
@@ -124,6 +124,9 @@ private:
ClassOrNamespace *lookupType_helper(const Name *name, QSet<ClassOrNamespace *> *processed,
bool searchInEnclosingScope, ClassOrNamespace *origin);
+ ClassOrNamespace *findBlock_helper(Block *block, QSet<ClassOrNamespace *> *processed,
+ bool searchInEnclosingScope);
+
ClassOrNamespace *nestedType(const Name *name, ClassOrNamespace *origin);
void instantiateNestedClasses(ClassOrNamespace *enclosingTemplateClass,
diff --git a/src/libs/cplusplus/LookupItem.cpp b/src/libs/cplusplus/LookupItem.cpp
index b97a96cc827..0621c1f6e92 100644
--- a/src/libs/cplusplus/LookupItem.cpp
+++ b/src/libs/cplusplus/LookupItem.cpp
@@ -38,7 +38,7 @@
using namespace CPlusPlus;
-uint CPlusPlus::qHash(const CPlusPlus::LookupItem &key)
+uint CPlusPlus::qHash(const LookupItem &key)
{
const uint h1 = QT_PREPEND_NAMESPACE(qHash)(key.type().type());
const uint h2 = QT_PREPEND_NAMESPACE(qHash)(key.scope());
diff --git a/src/libs/cplusplus/ResolveExpression.cpp b/src/libs/cplusplus/ResolveExpression.cpp
index 867669e33d2..c1a277f74e3 100644
--- a/src/libs/cplusplus/ResolveExpression.cpp
+++ b/src/libs/cplusplus/ResolveExpression.cpp
@@ -747,7 +747,7 @@ bool ResolveExpression::visit(SimpleNameAST *ast)
if (typeItems.empty())
continue;
- CPlusPlus::Clone cloner(_context.bindings()->control().data());
+ Clone cloner(_context.bindings()->control().data());
for (int n = 0; n < typeItems.size(); ++ n) {
FullySpecifiedType newType = cloner.type(typeItems[n].type(), 0);
diff --git a/src/libs/cplusplus/SimpleLexer.cpp b/src/libs/cplusplus/SimpleLexer.cpp
index 6bba9573260..ff2a5f6468c 100644
--- a/src/libs/cplusplus/SimpleLexer.cpp
+++ b/src/libs/cplusplus/SimpleLexer.cpp
@@ -41,7 +41,8 @@ using namespace CPlusPlus;
SimpleLexer::SimpleLexer()
: _lastState(0),
_skipComments(false),
- _endedJoined(false)
+ _endedJoined(false),
+ _ppMode(false)
{}
SimpleLexer::~SimpleLexer()
@@ -73,6 +74,7 @@ Tokens SimpleLexer::operator()(const QString &text, int state)
Lexer lex(firstChar, lastChar);
lex.setLanguageFeatures(_languageFeatures);
lex.setStartWithNewline(true);
+ lex.setPreprocessorMode(_ppMode);
if (! _skipComments)
lex.setScanCommentTokens(true);
diff --git a/src/libs/cplusplus/SimpleLexer.h b/src/libs/cplusplus/SimpleLexer.h
index e2eca1145fb..ef7fcbf0bdb 100644
--- a/src/libs/cplusplus/SimpleLexer.h
+++ b/src/libs/cplusplus/SimpleLexer.h
@@ -51,6 +51,9 @@ public:
bool skipComments() const;
void setSkipComments(bool skipComments);
+ void setPreprocessorMode(bool ppMode)
+ { _ppMode = ppMode; }
+
LanguageFeatures languageFeatures() const { return _languageFeatures; }
void setLanguageFeatures(LanguageFeatures features) { _languageFeatures = features; }
@@ -74,6 +77,7 @@ private:
LanguageFeatures _languageFeatures;
bool _skipComments: 1;
bool _endedJoined: 1;
+ bool _ppMode: 1;
};
} // namespace CPlusPlus
diff --git a/src/libs/cplusplus/cplusplus_dependencies.pri b/src/libs/cplusplus/cplusplus_dependencies.pri
index 0f89e4fabc4..ddb8945ec53 100644
--- a/src/libs/cplusplus/cplusplus_dependencies.pri
+++ b/src/libs/cplusplus/cplusplus_dependencies.pri
@@ -1,4 +1,4 @@
QTC_LIB_NAME = CPlusPlus
QTC_LIB_DEPENDS += \
- languageutils
+ utils
INCLUDEPATH *= $$IDE_SOURCE_TREE/src/libs/3rdparty
diff --git a/src/libs/cplusplus/pp-engine.cpp b/src/libs/cplusplus/pp-engine.cpp
index c0e6e3e827a..05a8f66c871 100644
--- a/src/libs/cplusplus/pp-engine.cpp
+++ b/src/libs/cplusplus/pp-engine.cpp
@@ -401,6 +401,9 @@ protected:
const char *end = spell + len;
char *vend = const_cast<char *>(end);
_value.set_long(strtol(spell, &vend, 0));
+ // TODO: if (vend != end) error(NaN)
+ // TODO: binary literals
+ // TODO: float literals
++(*_lex);
} else if (isTokenDefined()) {
++(*_lex);
@@ -902,7 +905,7 @@ void Preprocessor::skipPreprocesorDirective(PPToken *tk)
bool Preprocessor::handleIdentifier(PPToken *tk)
{
- ScopedBoolSwap s(m_state.m_inPreprocessorDirective, true);
+ ScopedBoolSwap s(m_state.m_inPreprocessorDirective, !tk->f.expanded);
static const QByteArray ppLine("__LINE__");
static const QByteArray ppFile("__FILE__");
@@ -1388,6 +1391,7 @@ void Preprocessor::preprocess(const QString &fileName, const QByteArray &source,
m_state.m_lexer = new Lexer(source.constBegin(), source.constEnd());
m_state.m_lexer->setScanKeywords(false);
m_state.m_lexer->setScanAngleStringLiteralTokens(false);
+ m_state.m_lexer->setPreprocessorMode(true);
if (m_keepComments)
m_state.m_lexer->setScanCommentTokens(true);
m_state.m_result = result;
@@ -1803,6 +1807,7 @@ const PPToken Preprocessor::evalExpression(PPToken *tk, Value &result)
PPToken lastConditionToken;
const QByteArray expanded = expand(tk, &lastConditionToken);
Lexer lexer(expanded.constData(), expanded.constData() + expanded.size());
+ lexer.setPreprocessorMode(true);
std::vector<Token> buf;
Token t;
do {
diff --git a/src/libs/extensionsystem/iplugin.cpp b/src/libs/extensionsystem/iplugin.cpp
index e1bda47cf9e..dbeff6cc876 100644
--- a/src/libs/extensionsystem/iplugin.cpp
+++ b/src/libs/extensionsystem/iplugin.cpp
@@ -205,6 +205,20 @@ IPlugin::~IPlugin()
}
/*!
+ \fn QList<QObject *> IPlugin::createTestObjects() const
+
+ Returns objects that are meant to be passed on to QTest::qExec().
+
+ This function will be called if the user starts \QC with '-test PluginName' or '-test all'.
+
+ The ownership of returned objects is transferred to caller.
+*/
+QList<QObject *> IPlugin::createTestObjects() const
+{
+ return QList<QObject *>();
+}
+
+/*!
\fn PluginSpec *IPlugin::pluginSpec() const
Returns the PluginSpec corresponding to this plugin.
This is not available in the constructor.
diff --git a/src/libs/extensionsystem/iplugin.h b/src/libs/extensionsystem/iplugin.h
index a349bca4bdc..32440880538 100644
--- a/src/libs/extensionsystem/iplugin.h
+++ b/src/libs/extensionsystem/iplugin.h
@@ -64,6 +64,7 @@ public:
virtual bool delayedInitialize() { return false; }
virtual ShutdownFlag aboutToShutdown() { return SynchronousShutdown; }
virtual QObject *remoteCommand(const QStringList & /* options */, const QStringList & /* arguments */) { return 0; }
+ virtual QList<QObject *> createTestObjects() const;
PluginSpec *pluginSpec() const;
diff --git a/src/libs/extensionsystem/pluginerroroverview.cpp b/src/libs/extensionsystem/pluginerroroverview.cpp
index 57b6b80dcfc..734e9de15d2 100644
--- a/src/libs/extensionsystem/pluginerroroverview.cpp
+++ b/src/libs/extensionsystem/pluginerroroverview.cpp
@@ -41,6 +41,8 @@ PluginErrorOverview::PluginErrorOverview(QWidget *parent) :
QDialog(parent),
m_ui(new Internal::Ui::PluginErrorOverview)
{
+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
+
m_ui->setupUi(this);
m_ui->buttonBox->addButton(tr("Continue"), QDialogButtonBox::AcceptRole);
@@ -53,8 +55,8 @@ PluginErrorOverview::PluginErrorOverview(QWidget *parent) :
}
}
- connect(m_ui->pluginList, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
- this, SLOT(showDetails(QListWidgetItem*)));
+ connect(m_ui->pluginList, &QListWidget::currentItemChanged,
+ this, &PluginErrorOverview::showDetails);
if (m_ui->pluginList->count() > 0)
m_ui->pluginList->setCurrentRow(0);
diff --git a/src/libs/extensionsystem/pluginmanager.cpp b/src/libs/extensionsystem/pluginmanager.cpp
index bea4e9f8f3e..20da164208b 100644
--- a/src/libs/extensionsystem/pluginmanager.cpp
+++ b/src/libs/extensionsystem/pluginmanager.cpp
@@ -51,18 +51,21 @@
#include <QTimer>
#include <QSysInfo>
+#include <utils/algorithm.h>
+#include <utils/qtcassert.h>
+
#ifdef WITH_TESTS
#include <QTest>
#endif
+#include <functional>
+
Q_LOGGING_CATEGORY(pluginLog, "qtc.extensionsystem")
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;
-
enum { debugLeaks = 0 };
/*!
@@ -103,8 +106,8 @@ enum { debugLeaks = 0 };
loading.
\code
// 'plugins' and subdirs will be searched for plugins
- ExtensionSystem::PluginManager::setPluginPaths(QStringList() << "plugins");
- ExtensionSystem::PluginManager::loadPlugins(); // try to load all the plugins
+ PluginManager::setPluginPaths(QStringList() << "plugins");
+ 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),
@@ -126,10 +129,10 @@ enum { debugLeaks = 0 };
// Plugin A provides a "MimeTypeHandler" extension point
// in plugin B:
MyMimeTypeHandler *handler = new MyMimeTypeHandler();
- ExtensionSystem::PluginManager::instance()->addObject(handler);
+ PluginManager::instance()->addObject(handler);
// In plugin A:
QList<MimeTypeHandler *> mimeHandlers =
- ExtensionSystem::PluginManager::getObjects<MimeTypeHandler>();
+ PluginManager::getObjects<MimeTypeHandler>();
\endcode
@@ -669,16 +672,13 @@ void PluginManager::formatOptions(QTextStream &str, int optionIndentation, int d
void PluginManager::formatPluginOptions(QTextStream &str, int optionIndentation, int descriptionIndentation)
{
- typedef PluginSpec::PluginArgumentDescriptions PluginArgumentDescriptions;
// Check plugins for options
- const PluginSpecSet::const_iterator pcend = d->pluginSpecs.constEnd();
- for (PluginSpecSet::const_iterator pit = d->pluginSpecs.constBegin(); pit != pcend; ++pit) {
- const PluginArgumentDescriptions pargs = (*pit)->argumentDescriptions();
+ foreach (PluginSpec *ps, d->pluginSpecs) {
+ const PluginSpec::PluginArgumentDescriptions pargs = ps->argumentDescriptions();
if (!pargs.empty()) {
- str << "\nPlugin: " << (*pit)->name() << '\n';
- const PluginArgumentDescriptions::const_iterator acend = pargs.constEnd();
- for (PluginArgumentDescriptions::const_iterator ait =pargs.constBegin(); ait != acend; ++ait)
- formatOption(str, ait->name, ait->parameter, ait->description, optionIndentation, descriptionIndentation);
+ str << "\nPlugin: " << ps->name() << '\n';
+ foreach (PluginArgumentDescription pad, pargs)
+ formatOption(str, pad.name, pad.parameter, pad.description, optionIndentation, descriptionIndentation);
}
}
}
@@ -688,96 +688,8 @@ void PluginManager::formatPluginOptions(QTextStream &str, int optionIndentation,
*/
void PluginManager::formatPluginVersions(QTextStream &str)
{
- const PluginSpecSet::const_iterator cend = d->pluginSpecs.constEnd();
- for (PluginSpecSet::const_iterator it = d->pluginSpecs.constBegin(); it != cend; ++it) {
- const PluginSpec *ps = *it;
+ foreach (PluginSpec *ps, d->pluginSpecs)
str << " " << ps->name() << ' ' << ps->version() << ' ' << ps->description() << '\n';
- }
-}
-
-void PluginManager::startTests()
-{
- if (PluginManager::hasError()) {
- qWarning("Errors occurred while loading plugins, skipping test run. "
- "For details, start without \"-test\" option.");
- QTimer::singleShot(1, QCoreApplication::instance(), SLOT(quit()));
- return;
- }
-
-#ifdef WITH_TESTS
- foreach (const PluginManagerPrivate::TestSpec &testSpec, d->testSpecs) {
- const PluginSpec * const pluginSpec = testSpec.pluginSpec;
- if (!pluginSpec->plugin())
- continue;
-
- // Collect all test functions of the plugin.
- QStringList allTestFunctions;
- const QMetaObject *metaObject = pluginSpec->plugin()->metaObject();
-
- for (int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) {
- const QByteArray signature = metaObject->method(i).methodSignature();
- if (signature.startsWith("test") && !signature.endsWith("_data()")) {
- const QString method = QString::fromLatin1(signature);
- const QString methodName = method.left(method.size() - 2);
- allTestFunctions.append(methodName);
- }
- }
-
- QStringList testFunctionsToExecute;
-
- // User did not specify any test functions, so add every test function.
- if (testSpec.testFunctions.isEmpty()) {
- testFunctionsToExecute = allTestFunctions;
-
- // User specified test functions. Add them if they are valid.
- } else {
- foreach (const QString &userTestFunction, testSpec.testFunctions) {
- // There might be a test data suffix like in "testfunction:testdata1".
- QString testFunctionName = userTestFunction;
- QString testDataSuffix;
- const int index = testFunctionName.indexOf(QLatin1Char(':'));
- if (index != -1) {
- testDataSuffix = testFunctionName.mid(index);
- testFunctionName = testFunctionName.left(index);
- }
-
- 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.
- foreach (const QString &matchingFunction, matchingFunctions)
- testFunctionsToExecute.append(matchingFunction + testDataSuffix);
- } else {
- QTextStream out(stdout);
- out << "No test function matches \"" << testFunctionName
- << "\" for plugin \"" << pluginSpec->name() << "\"." << endl
- << " Available test functions for plugin \"" << pluginSpec->name()
- << "\" are:" << endl;
- foreach (const QString &testFunction, allTestFunctions)
- out << " " << testFunction << endl;
- }
- }
- }
-
- // Don't run QTest::qExec without any test functions, that'd run
- // *all* slots as tests.
- if (!testFunctionsToExecute.isEmpty()) {
- // QTest::qExec() expects basically QCoreApplication::arguments(),
- QStringList qExecArguments = QStringList()
- << QLatin1String("arg0") // fake application name
- << QLatin1String("-maxwarnings") << QLatin1String("0"); // unlimit output
- qExecArguments << testFunctionsToExecute;
- QTest::qExec(pluginSpec->plugin(), qExecArguments);
- }
- }
- if (!d->testSpecs.isEmpty())
- QTimer::singleShot(1, QCoreApplication::instance(), SLOT(quit()));
-#endif
}
/*!
@@ -789,21 +701,6 @@ bool PluginManager::testRunRequested()
}
/*!
- * \internal
- */
-QString PluginManager::testDataDirectory()
-{
- QByteArray ba = qgetenv("QTCREATOR_TEST_DIR");
- QString s = QString::fromLocal8Bit(ba.constData(), ba.size());
- if (s.isEmpty()) {
- s = QLatin1String(IDE_TEST_DIR);
- s.append(QLatin1String("/tests"));
- }
- s = QDir::cleanPath(s);
- return s;
-}
-
-/*!
Creates a profiling entry showing the elapsed time if profiling is
activated.
*/
@@ -881,7 +778,7 @@ void PluginManagerPrivate::nextDelayedInitialize()
emit q->initializationDone();
#ifdef WITH_TESTS
if (q->testRunRequested())
- q->startTests();
+ startTests();
#endif
} else {
delayedInitializeTimer->start();
@@ -892,6 +789,7 @@ void PluginManagerPrivate::nextDelayedInitialize()
\internal
*/
PluginManagerPrivate::PluginManagerPrivate(PluginManager *pluginManager) :
+ m_failedTests(0),
delayedInitializeTimer(0),
shutdownEventLoop(0),
m_profileElapsedMS(0),
@@ -976,6 +874,234 @@ void PluginManagerPrivate::deleteAll()
}
}
+#ifdef WITH_TESTS
+
+typedef QMap<QObject *, QStringList> TestPlan; // Object -> selected test functions
+typedef QMapIterator<QObject *, QStringList> TestPlanIterator;
+
+static bool isTestFunction(const QMetaMethod &metaMethod)
+{
+ static const QList<QByteArray> blackList = QList<QByteArray>()
+ << "initTestCase()" << "cleanupTestCase()" << "init()" << "cleanup()";
+
+ if (metaMethod.methodType() != QMetaMethod::Slot)
+ return false;
+
+ if (metaMethod.access() != QMetaMethod::Private)
+ return false;
+
+ const QByteArray signature = metaMethod.methodSignature();
+ if (blackList.contains(signature))
+ return false;
+
+ if (!signature.startsWith("test"))
+ return false;
+
+ if (signature.endsWith("_data()"))
+ return false;
+
+ return true;
+}
+
+static QStringList testFunctions(const QMetaObject *metaObject)
+{
+
+ QStringList functions;
+
+ for (int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) {
+ const QMetaMethod metaMethod = metaObject->method(i);
+ if (isTestFunction(metaMethod)) {
+ const QByteArray signature = metaMethod.methodSignature();
+ const QString method = QString::fromLatin1(signature);
+ const QString methodName = method.left(method.size() - 2);
+ functions.append(methodName);
+ }
+ }
+
+ return functions;
+}
+
+static QStringList matchingTestFunctions(const QStringList &testFunctions,
+ const QString &matchText)
+{
+ // There might be a test data suffix like in "testfunction:testdata1".
+ QString testFunctionName = matchText;
+ QString testDataSuffix;
+ const int index = testFunctionName.indexOf(QLatin1Char(':'));
+ if (index != -1) {
+ testDataSuffix = testFunctionName.mid(index);
+ testFunctionName = testFunctionName.left(index);
+ }
+
+ const QRegExp regExp(testFunctionName, Qt::CaseSensitive, QRegExp::Wildcard);
+ QStringList matchingFunctions;
+ foreach (const QString &testFunction, testFunctions) {
+ if (regExp.exactMatch(testFunction)) {
+ // If the specified test data is invalid, the QTest framework will
+ // print a reasonable error message for us.
+ matchingFunctions.append(testFunction + testDataSuffix);
+ }
+ }
+
+ return matchingFunctions;
+}
+
+static QObject *objectWithClassName(const QList<QObject *> &objects, const QString &className)
+{
+ return Utils::findOr(objects, 0, [className] (QObject *object) -> bool {
+ QString candidate = QString::fromUtf8(object->metaObject()->className());
+ const int colonIndex = candidate.lastIndexOf(QLatin1Char(':'));
+ if (colonIndex != -1 && colonIndex < candidate.size() - 1)
+ candidate = candidate.mid(colonIndex + 1);
+ return candidate == className;
+ });
+}
+
+static int executeTestPlan(const TestPlan &testPlan)
+{
+ int failedTests = 0;
+
+ TestPlanIterator it(testPlan);
+ while (it.hasNext()) {
+ it.next();
+ QObject *testObject = it.key();
+ QStringList functions = it.value();
+
+ // Don't run QTest::qExec without any test functions, that'd run *all* slots as tests.
+ if (functions.isEmpty())
+ continue;
+
+ functions.removeDuplicates();
+
+ // QTest::qExec() expects basically QCoreApplication::arguments(),
+ QStringList qExecArguments = QStringList()
+ << QLatin1String("arg0") // fake application name
+ << QLatin1String("-maxwarnings") << QLatin1String("0"); // unlimit output
+ qExecArguments << functions;
+ failedTests += QTest::qExec(testObject, qExecArguments);
+ }
+
+ return failedTests;
+}
+
+/// Resulting plan consists of all test functions of the plugin object and
+/// all test functions of all test objects of the plugin.
+static TestPlan generateCompleteTestPlan(IPlugin *plugin, const QList<QObject *> &testObjects)
+{
+ TestPlan testPlan;
+
+ testPlan.insert(plugin, testFunctions(plugin->metaObject()));
+ foreach (QObject *testObject, testObjects) {
+ const QStringList allFunctions = testFunctions(testObject->metaObject());
+ testPlan.insert(testObject, allFunctions);
+ }
+
+ return testPlan;
+}
+
+/// Resulting plan consists of all matching test functions of the plugin object
+/// and all matching functions of all test objects of the plugin. However, if a
+/// match text denotes a test class, all test functions of that will be
+/// included and the class will not be considered further.
+///
+/// Since multiple match texts can match the same function, a test function might
+/// be included multiple times for a test object.
+static TestPlan generateCustomTestPlan(IPlugin *plugin, const QList<QObject *> &testObjects,
+ const QStringList &matchTexts)
+{
+ TestPlan testPlan;
+
+ const QStringList testFunctionsOfPluginObject = testFunctions(plugin->metaObject());
+ QStringList matchedTestFunctionsOfPluginObject;
+ QStringList remainingMatchTexts = matchTexts;
+ QList<QObject *> remainingTestObjectsOfPlugin = testObjects;
+
+ while (!remainingMatchTexts.isEmpty()) {
+ const QString matchText = remainingMatchTexts.takeFirst();
+ bool matched = false;
+
+ if (QObject *testObject = objectWithClassName(remainingTestObjectsOfPlugin, matchText)) {
+ // Add all functions of the matching test object
+ matched = true;
+ testPlan.insert(testObject, testFunctions(testObject->metaObject()));
+ remainingTestObjectsOfPlugin.removeAll(testObject);
+
+ } else {
+ // Add all matching test functions of all remaining test objects
+ foreach (QObject *testObject, remainingTestObjectsOfPlugin) {
+ const QStringList allFunctions = testFunctions(testObject->metaObject());
+ const QStringList matchingFunctions = matchingTestFunctions(allFunctions,
+ matchText);
+ if (!matchingFunctions.isEmpty()) {
+ matched = true;
+ testPlan[testObject] += matchingFunctions;
+ }
+ }
+ }
+
+ const QStringList currentMatchedTestFunctionsOfPluginObject
+ = matchingTestFunctions(testFunctionsOfPluginObject, matchText);
+ if (!currentMatchedTestFunctionsOfPluginObject.isEmpty()) {
+ matched = true;
+ matchedTestFunctionsOfPluginObject += currentMatchedTestFunctionsOfPluginObject;
+ }
+
+ if (!matched) {
+ QTextStream out(stdout);
+ out << "No test function or class matches \"" << matchText
+ << "\" in plugin \"" << plugin->metaObject()->className() << "\"." << endl;
+ }
+ }
+
+ // Add all matching test functions of plugin
+ if (!matchedTestFunctionsOfPluginObject.isEmpty())
+ testPlan.insert(plugin, matchedTestFunctionsOfPluginObject);
+
+ return testPlan;
+}
+
+class ExecuteOnDestruction
+{
+public:
+ ExecuteOnDestruction(std::function<void()> code) : destructionCode(code) {}
+ ~ExecuteOnDestruction() { if (destructionCode) destructionCode(); }
+
+private:
+ const std::function<void()> destructionCode;
+};
+
+void PluginManagerPrivate::startTests()
+{
+ if (PluginManager::hasError()) {
+ qWarning("Errors occurred while loading plugins, skipping test run. "
+ "For details, start without \"-test\" option.");
+ QTimer::singleShot(1, QCoreApplication::instance(), SLOT(quit()));
+ return;
+ }
+
+ foreach (const PluginManagerPrivate::TestSpec &testSpec, testSpecs) {
+ IPlugin *plugin = testSpec.pluginSpec->plugin();
+ if (!plugin)
+ continue; // plugin not loaded
+
+ const QList<QObject *> testObjects = plugin->createTestObjects();
+ ExecuteOnDestruction deleteTestObjects([&]() { qDeleteAll(testObjects); });
+
+ const bool hasDuplicateTestObjects = testObjects.size() != testObjects.toSet().size();
+ QTC_ASSERT(!hasDuplicateTestObjects, continue);
+ QTC_ASSERT(!testObjects.contains(plugin), continue);
+
+ const TestPlan testPlan = testSpec.testFunctionsOrObjects.isEmpty()
+ ? generateCompleteTestPlan(plugin, testObjects)
+ : generateCustomTestPlan(plugin, testObjects, testSpec.testFunctionsOrObjects);
+
+ m_failedTests += executeTestPlan(testPlan);
+ }
+ if (!testSpecs.isEmpty())
+ QTimer::singleShot(1, this, SLOT(exitWithNumberOfFailedTests()));
+}
+#endif
+
/*!
\internal
*/
@@ -1090,6 +1216,14 @@ void PluginManagerPrivate::asyncShutdownFinished()
/*!
\internal
*/
+void PluginManagerPrivate::exitWithNumberOfFailedTests()
+{
+ QCoreApplication::exit(m_failedTests);
+}
+
+/*!
+ \internal
+*/
QList<PluginSpec *> PluginManagerPrivate::loadQueue()
{
QList<PluginSpec *> queue;
@@ -1293,10 +1427,6 @@ void PluginManagerPrivate::resolveDependencies()
spec->d->resolveDependencies(pluginSpecs);
}
- // Reset disabledIndirectly flag
- foreach (PluginSpec *spec, loadQueue())
- spec->d->disabledIndirectly = false;
-
foreach (PluginSpec *spec, loadQueue()) {
spec->d->disableIndirectlyIfDependencyDisabled();
}
@@ -1306,18 +1436,13 @@ void PluginManagerPrivate::resolveDependencies()
PluginSpec *PluginManagerPrivate::pluginForOption(const QString &option, bool *requiresArgument) const
{
// Look in the plugins for an option
- typedef PluginSpec::PluginArgumentDescriptions PluginArgumentDescriptions;
-
*requiresArgument = false;
- const PluginSpecSet::const_iterator pcend = pluginSpecs.constEnd();
- for (PluginSpecSet::const_iterator pit = pluginSpecs.constBegin(); pit != pcend; ++pit) {
- PluginSpec *ps = *pit;
- const PluginArgumentDescriptions pargs = ps->argumentDescriptions();
+ foreach (PluginSpec *ps, pluginSpecs) {
+ const PluginSpec::PluginArgumentDescriptions pargs = ps->argumentDescriptions();
if (!pargs.empty()) {
- const PluginArgumentDescriptions::const_iterator acend = pargs.constEnd();
- for (PluginArgumentDescriptions::const_iterator ait = pargs.constBegin(); ait != acend; ++ait) {
- if (ait->name == option) {
- *requiresArgument = !ait->parameter.isEmpty();
+ foreach (PluginArgumentDescription pad, pargs) {
+ if (pad.name == option) {
+ *requiresArgument = !pad.parameter.isEmpty();
return ps;
}
}
@@ -1326,11 +1451,6 @@ PluginSpec *PluginManagerPrivate::pluginForOption(const QString &option, bool *r
return 0;
}
-void PluginManagerPrivate::disablePluginIndirectly(PluginSpec *spec)
-{
- spec->d->disabledIndirectly = true;
-}
-
PluginSpec *PluginManagerPrivate::pluginByName(const QString &name) const
{
foreach (PluginSpec *spec, pluginSpecs)
diff --git a/src/libs/extensionsystem/pluginmanager.h b/src/libs/extensionsystem/pluginmanager.h
index e1a028637d0..72b4402da83 100644
--- a/src/libs/extensionsystem/pluginmanager.h
+++ b/src/libs/extensionsystem/pluginmanager.h
@@ -145,7 +145,6 @@ public:
static QString serializedArguments();
static bool testRunRequested();
- static QString testDataDirectory();
static void profilingReport(const char *what, const PluginSpec *spec = 0);
@@ -162,8 +161,6 @@ public slots:
void remoteArguments(const QString &serializedArguments, QObject *socket);
void shutdown();
-private slots:
- void startTests();
friend class Internal::PluginManagerPrivate;
};
diff --git a/src/libs/extensionsystem/pluginmanager_p.h b/src/libs/extensionsystem/pluginmanager_p.h
index a39f1df2ba9..0400ceb0fc2 100644
--- a/src/libs/extensionsystem/pluginmanager_p.h
+++ b/src/libs/extensionsystem/pluginmanager_p.h
@@ -80,14 +80,13 @@ public:
void setGlobalSettings(QSettings *settings);
void readSettings();
void writeSettings();
- void disablePluginIndirectly(PluginSpec *spec);
class TestSpec {
public:
- TestSpec(PluginSpec *pluginSpec, const QStringList &testFunctions = QStringList())
- : pluginSpec(pluginSpec), testFunctions(testFunctions) {}
+ TestSpec(PluginSpec *pluginSpec, const QStringList &testFunctionsOrObjects = QStringList())
+ : pluginSpec(pluginSpec), testFunctionsOrObjects(testFunctionsOrObjects) {}
PluginSpec *pluginSpec;
- QStringList testFunctions;
+ QStringList testFunctionsOrObjects;
};
bool containsTestSpec(PluginSpec *pluginSpec) const
@@ -102,6 +101,7 @@ public:
QHash<QString, PluginCollection *> pluginCategories;
QList<PluginSpec *> pluginSpecs;
QList<TestSpec> testSpecs;
+ int m_failedTests;
QStringList pluginPaths;
QString pluginIID;
QList<QObject *> allObjects; // ### make this a QList<QPointer<QObject> > > ?
@@ -137,6 +137,7 @@ public:
private slots:
void nextDelayedInitialize();
void asyncShutdownFinished();
+ void exitWithNumberOfFailedTests();
private:
PluginCollection *defaultCollection;
@@ -148,6 +149,10 @@ private:
QList<PluginSpec *> &circularityCheckQueue);
void stopAll();
void deleteAll();
+
+#ifdef WITH_TESTS
+ void startTests();
+#endif
};
} // namespace Internal
diff --git a/src/libs/extensionsystem/pluginspec.cpp b/src/libs/extensionsystem/pluginspec.cpp
index 21854fa9b65..9d470cd5b20 100644
--- a/src/libs/extensionsystem/pluginspec.cpp
+++ b/src/libs/extensionsystem/pluginspec.cpp
@@ -136,7 +136,7 @@ using namespace ExtensionSystem::Internal;
/*!
\internal
*/
-uint ExtensionSystem::qHash(const ExtensionSystem::PluginDependency &value)
+uint ExtensionSystem::qHash(const PluginDependency &value)
{
return qHash(value.name);
}
@@ -332,7 +332,7 @@ bool PluginSpec::isForceDisabled() const
/*!
The plugin dependencies. This is valid after the PluginSpec::Read state is reached.
*/
-QList<PluginDependency> PluginSpec::dependencies() const
+QVector<PluginDependency> PluginSpec::dependencies() const
{
return d->dependencies;
}
@@ -542,11 +542,6 @@ void PluginSpec::setDisabledByDefault(bool value)
d->disabledByDefault = value;
}
-void PluginSpec::setDisabledIndirectly(bool value)
-{
- d->disabledIndirectly = value;
-}
-
void PluginSpec::setForceEnabled(bool value)
{
d->forceEnabled = value;
diff --git a/src/libs/extensionsystem/pluginspec.h b/src/libs/extensionsystem/pluginspec.h
index 689ad5bee52..9272403e9aa 100644
--- a/src/libs/extensionsystem/pluginspec.h
+++ b/src/libs/extensionsystem/pluginspec.h
@@ -34,8 +34,8 @@
#include "extensionsystem_global.h"
#include <QString>
-#include <QList>
#include <QHash>
+#include <QVector>
QT_BEGIN_NAMESPACE
class QStringList;
@@ -102,9 +102,9 @@ public:
bool isDisabledIndirectly() const;
bool isForceEnabled() const;
bool isForceDisabled() const;
- QList<PluginDependency> dependencies() const;
+ QVector<PluginDependency> dependencies() const;
- typedef QList<PluginArgumentDescription> PluginArgumentDescriptions;
+ typedef QVector<PluginArgumentDescription> PluginArgumentDescriptions;
PluginArgumentDescriptions argumentDescriptions() const;
// other information, valid after 'Read' state is reached
@@ -113,7 +113,6 @@ public:
void setEnabled(bool value);
void setDisabledByDefault(bool value);
- void setDisabledIndirectly(bool value);
void setForceEnabled(bool value);
void setForceDisabled(bool value);
diff --git a/src/libs/extensionsystem/pluginspec_p.h b/src/libs/extensionsystem/pluginspec_p.h
index 37c9438573a..b2169ec55d2 100644
--- a/src/libs/extensionsystem/pluginspec_p.h
+++ b/src/libs/extensionsystem/pluginspec_p.h
@@ -39,6 +39,7 @@
#include <QPluginLoader>
#include <QRegExp>
#include <QStringList>
+#include <QVector>
#include <QXmlStreamReader>
namespace ExtensionSystem {
@@ -80,7 +81,7 @@ public:
QString url;
QString category;
QRegExp platformSpecification;
- QList<PluginDependency> dependencies;
+ QVector<PluginDependency> dependencies;
bool enabledInSettings;
bool disabledIndirectly;
bool forceEnabled;
diff --git a/src/libs/extensionsystem/pluginview.cpp b/src/libs/extensionsystem/pluginview.cpp
index 345de0f8d70..21646f1d6ee 100644
--- a/src/libs/extensionsystem/pluginview.cpp
+++ b/src/libs/extensionsystem/pluginview.cpp
@@ -32,14 +32,17 @@
#include "pluginmanager.h"
#include "pluginspec.h"
#include "plugincollection.h"
+
+#include <utils/algorithm.h>
#include <utils/itemviews.h>
+#include <utils/treemodel.h>
#include <QDebug>
#include <QDir>
#include <QGridLayout>
#include <QHeaderView>
-#include <QPalette>
-#include <QTreeWidgetItem>
+#include <QSet>
+#include <QItemSelectionModel>
/*!
\class ExtensionSystem::PluginView
@@ -66,317 +69,320 @@
for example by a double-click.
*/
-using namespace ExtensionSystem;
-
Q_DECLARE_METATYPE(ExtensionSystem::PluginSpec*)
Q_DECLARE_METATYPE(ExtensionSystem::PluginCollection*)
-/*!
- Constructs a PluginView that gets the list of plugins from the
- given plugin \a manager with a given \a parent widget.
-*/
-PluginView::PluginView(QWidget *parent)
- : QWidget(parent),
- m_allowCheckStateUpdate(true),
- C_LOAD(1)
-{
- m_categoryWidget = new Utils::TreeWidget(this);
- m_categoryWidget->setAlternatingRowColors(true);
- m_categoryWidget->setIndentation(20);
- m_categoryWidget->setUniformRowHeights(true);
- m_categoryWidget->setSortingEnabled(true);
- m_categoryWidget->setColumnCount(4);
- m_categoryWidget->setColumnWidth(C_LOAD, 40);
- m_categoryWidget->header()->setDefaultSectionSize(120);
- m_categoryWidget->header()->setMinimumSectionSize(35);
- m_categoryWidget->setActivationMode(Utils::DoubleClickActivation);
-
- QTreeWidgetItem *headerItem = m_categoryWidget->headerItem();
- headerItem->setText(0, tr("Name"));
- headerItem->setText(1, tr("Load"));
- headerItem->setText(2, tr("Version"));
- headerItem->setText(3, tr("Vendor"));
-
- QGridLayout *gridLayout = new QGridLayout(this);
- gridLayout->setContentsMargins(2, 2, 2, 2);
- gridLayout->addWidget(m_categoryWidget, 1, 0, 1, 1);
-
- QHeaderView *header = m_categoryWidget->header();
- header->setSectionResizeMode(0, QHeaderView::ResizeToContents);
- header->setSectionResizeMode(2, QHeaderView::ResizeToContents);
+using namespace Utils;
- m_okIcon = QIcon(QLatin1String(":/extensionsystem/images/ok.png"));
- m_errorIcon = QIcon(QLatin1String(":/extensionsystem/images/error.png"));
- m_notLoadedIcon = QIcon(QLatin1String(":/extensionsystem/images/notloaded.png"));
+namespace ExtensionSystem {
- connect(PluginManager::instance(), SIGNAL(pluginsChanged()), this, SLOT(updateList()));
- connect(m_categoryWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
- this, SLOT(selectPlugin(QTreeWidgetItem*)));
- connect(m_categoryWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
- this, SLOT(activatePlugin(QTreeWidgetItem*)));
+enum Columns { NameColumn, LoadedColumn, VersionColumn, VendorColumn, };
- updateList();
-}
+enum IconIndex { OkIcon, ErrorIcon, NotLoadedIcon };
-/*!
- \internal
-*/
-PluginView::~PluginView()
+static const QIcon &icon(int num)
{
+ static QIcon icons[] = {
+ QIcon(QLatin1String(":/extensionsystem/images/ok.png")),
+ QIcon(QLatin1String(":/extensionsystem/images/error.png")),
+ QIcon(QLatin1String(":/extensionsystem/images/notloaded.png")),
+ };
+ return icons[num];
}
-/*!
- Returns the current selection in the list of plugins.
-*/
-PluginSpec *PluginView::currentPlugin() const
+class PluginItem : public TreeItem
{
- if (!m_categoryWidget->currentItem())
- return 0;
- if (!m_categoryWidget->currentItem()->data(0, Qt::UserRole).isNull())
- return m_categoryWidget->currentItem()->data(0, Qt::UserRole).value<PluginSpec *>();
- return 0;
-}
+public:
+ PluginItem(PluginSpec *spec, PluginView *view)
+ : m_spec(spec), m_view(view)
+ {}
+
+ int columnCount() const { return 4; }
+
+ QVariant data(int column, int role) const
+ {
+ switch (column) {
+ case NameColumn:
+ if (role == Qt::DisplayRole)
+ return m_spec->name();
+ if (role == Qt::ToolTipRole)
+ return QDir::toNativeSeparators(m_spec->filePath());
+ if (role == Qt::DecorationRole) {
+ bool ok = !m_spec->hasError();
+ QIcon i = icon(ok ? OkIcon : ErrorIcon);
+ if (ok && m_spec->state() != PluginSpec::Running)
+ i = icon(NotLoadedIcon);
+ return i;
+ }
+ break;
+
+ case LoadedColumn:
+ if (!m_spec->isAvailableForHostPlatform()) {
+ if (role == Qt::CheckStateRole)
+ return Qt::Unchecked;
+ if (role == Qt::ToolTipRole)
+ return PluginView::tr("Plugin is not available on this platform.");
+ } else if (m_spec->isRequired()) {
+ if (role == Qt::CheckStateRole)
+ return Qt::Checked;
+ if (role == Qt::ToolTipRole)
+ return PluginView::tr("Plugin is required.");
+ } else {
+ if (role == Qt::CheckStateRole)
+ return m_spec->isEnabledInSettings() ? Qt::Checked : Qt::Unchecked;
+ if (role == Qt::ToolTipRole)
+ return PluginView::tr("Load on startup");
+ }
+ break;
-void PluginView::updateList()
-{
- connect(m_categoryWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
- this, SLOT(updatePluginSettings(QTreeWidgetItem*,int)));
+ case VersionColumn:
+ if (role == Qt::DisplayRole)
+ return QString::fromLatin1("%1 (%2)").arg(m_spec->version(), m_spec->compatVersion());
+ break;
- PluginCollection *defaultCollection = 0;
- foreach (PluginCollection *collection, PluginManager::pluginCollections()) {
- if (collection->name().isEmpty() || collection->plugins().isEmpty()) {
- defaultCollection = collection;
- continue;
+ case VendorColumn:
+ if (role == Qt::DisplayRole)
+ return m_spec->vendor();
+ break;
}
- // State, name, load, version, vendor.
- QTreeWidgetItem *collectionItem = new QTreeWidgetItem(QStringList()
- << collection->name()
- << QString() // state
- << QString() // load
- << QString() // version
- << QString()); // vendor
- m_items.append(collectionItem);
-
- Qt::CheckState groupState = Qt::Unchecked;
- int state = parsePluginSpecs(collectionItem, groupState, collection->plugins());
-
- collectionItem->setIcon(0, iconForState(state));
- collectionItem->setData(C_LOAD, Qt::CheckStateRole, QVariant(groupState));
- collectionItem->setToolTip(C_LOAD, tr("Load on Startup"));
- collectionItem->setData(0, Qt::UserRole, qVariantFromValue(collection));
- }
- QList<PluginSpec *> plugins = defaultCollection ? defaultCollection->plugins() : QList<PluginSpec *>();
- if (!plugins.isEmpty()) {
- // add all non-categorized plugins into utilities. could also be added as root items
- // but that makes the tree ugly.
- QTreeWidgetItem *defaultCollectionItem = new QTreeWidgetItem(QStringList()
- << QString(tr("Utilities"))
- << QString()
- << QString()
- << QString()
- << QString());
-
- m_items.append(defaultCollectionItem);
- Qt::CheckState groupState = Qt::Unchecked;
- int state = parsePluginSpecs(defaultCollectionItem, groupState, plugins);
-
- defaultCollectionItem->setIcon(0, iconForState(state));
- defaultCollectionItem->setData(C_LOAD, Qt::CheckStateRole, QVariant(groupState));
- defaultCollectionItem->setToolTip(C_LOAD, tr("Load on Startup"));
- defaultCollectionItem->setData(0, Qt::UserRole, qVariantFromValue(defaultCollection));
+ return QVariant();
}
- updatePluginDependencies();
+ bool setData(int column, const QVariant &data, int role)
+ {
+ if (column == LoadedColumn && role == Qt::CheckStateRole) {
+ m_spec->setEnabled(data.toBool());
+ update();
+ parent()->update();
+ emit m_view->pluginSettingsChanged(m_spec);
+ return true;
+ }
+ return false;
+ }
- m_categoryWidget->clear();
- if (!m_items.isEmpty()) {
- m_categoryWidget->addTopLevelItems(m_items);
- m_categoryWidget->expandAll();
+ bool isEnabled() const
+ {
+ if (m_spec->isRequired() || !m_spec->isAvailableForHostPlatform())
+ return false;
+ foreach (PluginSpec *spec, m_view->m_pluginDependencies.value(m_spec))
+ if (!spec->isEnabledInSettings())
+ return false;
+ return true;
}
- m_categoryWidget->sortItems(0, Qt::AscendingOrder);
- if (m_categoryWidget->topLevelItemCount())
- m_categoryWidget->setCurrentItem(m_categoryWidget->topLevelItem(0));
-}
+ Qt::ItemFlags flags(int column) const
+ {
+ Qt::ItemFlags ret = Qt::ItemIsSelectable;
-int PluginView::parsePluginSpecs(QTreeWidgetItem *parentItem, Qt::CheckState &groupState, QList<PluginSpec*> plugins)
-{
- int ret = 0;
- int checkedCount = 0;
-
- for (int i = 0; i < plugins.length(); ++i) {
- PluginSpec *spec = plugins[i];
- if (spec->hasError())
- ret |= ParsedWithErrors;
-
- QTreeWidgetItem *pluginItem = new QTreeWidgetItem(QStringList()
- << spec->name()
- << QString() // load on startup
- << QString::fromLatin1("%1 (%2)").arg(spec->version(), spec->compatVersion())
- << spec->vendor());
-
- pluginItem->setToolTip(0, QDir::toNativeSeparators(spec->filePath()));
- bool ok = !spec->hasError();
- QIcon icon = ok ? m_okIcon : m_errorIcon;
- if (ok && (spec->state() != PluginSpec::Running))
- icon = m_notLoadedIcon;
-
- pluginItem->setIcon(0, icon);
- pluginItem->setData(0, Qt::UserRole, qVariantFromValue(spec));
-
- Qt::CheckState state = Qt::Unchecked;
- if (spec->isEnabledInSettings()) {
- state = Qt::Checked;
- ++checkedCount;
- }
+ if (isEnabled())
+ ret |= Qt::ItemIsEnabled;
- if (!spec->isAvailableForHostPlatform()) {
- pluginItem->setData(C_LOAD, Qt::CheckStateRole, Qt::Unchecked);
- pluginItem->setFlags(Qt::ItemIsSelectable);
- pluginItem->setToolTip(C_LOAD, tr("Plugin is not available on this platform."));
- } else if (spec->isRequired()){
- pluginItem->setData(C_LOAD, Qt::CheckStateRole, Qt::Checked);
- pluginItem->setFlags(Qt::ItemIsSelectable);
- pluginItem->setToolTip(C_LOAD, tr("Plugin is required."));
- } else {
- pluginItem->setData(C_LOAD, Qt::CheckStateRole, state);
- pluginItem->setToolTip(C_LOAD, tr("Load on startup"));
+ if (column == LoadedColumn) {
+ if (m_spec->isAvailableForHostPlatform() && !m_spec->isRequired())
+ ret |= Qt::ItemIsEditable | Qt ::ItemIsUserCheckable;
}
- m_specToItem.insert(spec, pluginItem);
-
- if (parentItem)
- parentItem->addChild(pluginItem);
- else
- m_items.append(pluginItem);
+ return ret;
}
- if (checkedCount == 0) {
- groupState = Qt::Unchecked;
- ret |= ParsedNone;
- } else if (checkedCount == plugins.length()) {
- groupState = Qt::Checked;
- ret |= ParsedAll;
- } else {
- groupState = Qt::PartiallyChecked;
- ret = ret | ParsedPartial;
- }
- return ret;
-}
+public:
+ PluginSpec *m_spec; // Not owned.
+ PluginView *m_view; // Not owned.
+};
-QIcon PluginView::iconForState(int state)
+class CollectionItem : public TreeItem
{
- if (state & ParsedWithErrors)
- return m_errorIcon;
+public:
+ CollectionItem(const QString &name, QList<PluginSpec *> plugins, PluginView *view)
+ : m_name(name), m_plugins(plugins), m_view(view)
+ {
+ foreach (PluginSpec *spec, plugins)
+ appendChild(new PluginItem(spec, view));
+ }
- if (state & ParsedNone || state & ParsedPartial)
- return m_notLoadedIcon;
+ int columnCount() const { return 4; }
+
+ QVariant data(int column, int role) const
+ {
+ if (column == NameColumn) {
+ if (role == Qt::DisplayRole)
+ return m_name;
+ if (role == Qt::DecorationRole) {
+ foreach (PluginSpec *spec, m_plugins) {
+ if (spec->hasError())
+ return icon(ErrorIcon);
+ if (!spec->isEnabledInSettings())
+ return icon(NotLoadedIcon);
+ }
+ return icon(OkIcon);
+ }
+ }
- return m_okIcon;
-}
+ if (column == LoadedColumn) {
+ if (role == Qt::ToolTipRole)
+ return PluginView::tr("Load on Startup");
+ if (role == Qt::CheckStateRole) {
+ int checkedCount = 0;
+ foreach (PluginSpec *spec, m_plugins) {
+ if (spec->isEnabledInSettings())
+ ++checkedCount;
+ }
-void PluginView::selectPlugin(QTreeWidgetItem *current)
-{
- if (!current)
- emit currentPluginChanged(0);
- else if (current->data(0, Qt::UserRole).canConvert<PluginSpec*>())
- emit currentPluginChanged(current->data(0, Qt::UserRole).value<PluginSpec *>());
- else
- emit currentPluginChanged(0);
+ if (checkedCount == 0)
+ return Qt::Unchecked;
+ if (checkedCount == m_plugins.length())
+ return Qt::Checked;
+ return Qt::PartiallyChecked;
+ }
+ }
-}
+ return QVariant();
+ }
-void PluginView::activatePlugin(QTreeWidgetItem *item)
-{
- if (item->data(0, Qt::UserRole).canConvert<PluginSpec*>()) {
- emit pluginActivated(item->data(0, Qt::UserRole).value<PluginSpec *>());
- } else
- emit pluginActivated(0);
-}
+ bool setData(int column, const QVariant &data, int role)
+ {
+ if (column == LoadedColumn && role == Qt::CheckStateRole) {
+ foreach (TreeItem *item, children())
+ static_cast<PluginItem *>(item)->setData(column, data, role);
+ update();
+ return true;
+ }
+ return false;
+ }
+
+ Qt::ItemFlags flags(int column) const
+ {
+ Qt::ItemFlags ret = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
+ if (column == LoadedColumn)
+ ret |= Qt::ItemIsEditable | Qt::ItemIsUserCheckable;
+ return ret;
+ }
+
+public:
+ QString m_name;
+ QList<PluginSpec *> m_plugins;
+ PluginView *m_view; // Not owned.
+};
-void PluginView::updatePluginSettings(QTreeWidgetItem *item, int column)
+/*!
+ Constructs a PluginView that gets the list of plugins from the
+ given plugin \a manager with a given \a parent widget.
+*/
+PluginView::PluginView(QWidget *parent)
+ : QWidget(parent)
{
- if (!m_allowCheckStateUpdate)
- return;
+ m_categoryView = new TreeView(this);
+ m_categoryView->setAlternatingRowColors(true);
+ m_categoryView->setIndentation(20);
+ m_categoryView->setUniformRowHeights(true);
+ m_categoryView->setSortingEnabled(true);
+ m_categoryView->setColumnWidth(LoadedColumn, 40);
+ m_categoryView->header()->setDefaultSectionSize(120);
+ m_categoryView->header()->setMinimumSectionSize(35);
+ m_categoryView->setActivationMode(DoubleClickActivation);
+ m_categoryView->setSelectionMode(QAbstractItemView::SingleSelection);
+ m_categoryView->setSelectionBehavior(QAbstractItemView::SelectRows);
+
+ m_model = new TreeModel(this);
+ m_model->setHeader(QStringList() << tr("Name") << tr("Load") << tr("Version") << tr("Vendor"));
+ m_categoryView->setModel(m_model);
- m_allowCheckStateUpdate = false;
+ QGridLayout *gridLayout = new QGridLayout(this);
+ gridLayout->setContentsMargins(2, 2, 2, 2);
+ gridLayout->addWidget(m_categoryView, 1, 0, 1, 1);
- bool loadOnStartup = item->data(C_LOAD, Qt::CheckStateRole).toBool();
+ QHeaderView *header = m_categoryView->header();
+ header->setSectionResizeMode(0, QHeaderView::ResizeToContents);
+ header->setSectionResizeMode(2, QHeaderView::ResizeToContents);
- if (item->data(0, Qt::UserRole).canConvert<PluginSpec*>()) {
- PluginSpec *spec = item->data(0, Qt::UserRole).value<PluginSpec *>();
+ connect(PluginManager::instance(), &PluginManager::pluginsChanged,
+ this, &PluginView::updatePlugins);
- if (column == C_LOAD) {
+ connect(m_categoryView, &QAbstractItemView::activated,
+ [this](const QModelIndex &idx) { pluginActivated(pluginForIndex(idx)); });
- spec->setEnabled(loadOnStartup);
- updatePluginDependencies();
+ connect(m_categoryView->selectionModel(), &QItemSelectionModel::currentChanged,
+ [this](const QModelIndex &idx) { currentPluginChanged(pluginForIndex(idx)); });
- if (item->parent()) {
- PluginCollection *collection = item->parent()->data(0, Qt::UserRole).value<PluginCollection *>();
- Qt::CheckState state = Qt::PartiallyChecked;
- int loadCount = 0;
- for (int i = 0; i < collection->plugins().length(); ++i) {
- if (collection->plugins().at(i)->isEnabledInSettings())
- ++loadCount;
- }
- if (loadCount == collection->plugins().length())
- state = Qt::Checked;
- else if (loadCount == 0)
- state = Qt::Unchecked;
+ updatePlugins();
+}
- item->parent()->setData(C_LOAD, Qt::CheckStateRole, state);
- }
+/*!
+ \internal
+*/
+PluginView::~PluginView()
+{
+}
- emit pluginSettingsChanged(spec);
- }
+/*!
+ Returns the current selection in the list of plugins.
+*/
+PluginSpec *PluginView::currentPlugin() const
+{
+ return pluginForIndex(m_categoryView->currentIndex());
+}
- } else {
- PluginCollection *collection = item->data(0, Qt::UserRole).value<PluginCollection *>();
- for (int i = 0; i < collection->plugins().length(); ++i) {
- PluginSpec *spec = collection->plugins().at(i);
- QTreeWidgetItem *child = m_specToItem.value(spec);
+PluginSpec *PluginView::pluginForIndex(const QModelIndex &index) const
+{
+ auto item = dynamic_cast<PluginItem *>(m_model->itemFromIndex(index));
+ return item ? item->m_spec: 0;
+}
- if (spec->isAvailableForHostPlatform() && !spec->isRequired()) {
- spec->setEnabled(loadOnStartup);
- Qt::CheckState state = (loadOnStartup ? Qt::Checked : Qt::Unchecked);
- child->setData(C_LOAD, Qt::CheckStateRole, state);
- }
+static void queryDependendPlugins(PluginSpec *spec, QSet<PluginSpec *> *dependencies)
+{
+ QHashIterator<PluginDependency, PluginSpec *> it(spec->dependencySpecs());
+ while (it.hasNext()) {
+ it.next();
+ PluginSpec *dep = it.value();
+ if (!dependencies->contains(dep)) {
+ dependencies->insert(dep);
+ queryDependendPlugins(dep, dependencies);
}
- updatePluginDependencies();
- if (!collection->plugins().isEmpty())
- emit pluginSettingsChanged(collection->plugins().first());
}
-
- m_allowCheckStateUpdate = true;
}
-void PluginView::updatePluginDependencies()
+void PluginView::updatePlugins()
{
+ // Dependencies.
+ m_pluginDependencies.clear();
foreach (PluginSpec *spec, PluginManager::loadQueue()) {
- bool disableIndirectly = false;
- if (spec->isRequired())
- continue;
+ QSet<PluginSpec *> deps;
+ queryDependendPlugins(spec, &deps);
+ m_pluginDependencies[spec] = deps;
+ }
- QHashIterator<PluginDependency, PluginSpec *> it(spec->dependencySpecs());
- while (it.hasNext()) {
- it.next();
- if (it.key().type == PluginDependency::Optional)
- continue;
- PluginSpec *depSpec = it.value();
- if (!depSpec->isEnabledInSettings() || depSpec->isDisabledIndirectly()) {
- disableIndirectly = true;
- break;
- }
- }
- QTreeWidgetItem *childItem = m_specToItem.value(spec);
- childItem->setDisabled(disableIndirectly || !spec->isAvailableForHostPlatform());
+ // Model.
+ m_model->removeItems();
- if (disableIndirectly == spec->isDisabledIndirectly())
+ PluginCollection *defaultCollection = 0;
+ QList<CollectionItem *> collections;
+ foreach (PluginCollection *collection, PluginManager::pluginCollections()) {
+ if (collection->name().isEmpty() || collection->plugins().isEmpty()) {
+ defaultCollection = collection;
continue;
- spec->setDisabledIndirectly(disableIndirectly);
+ }
+ collections.append(new CollectionItem(collection->name(), collection->plugins(), this));
+ }
+
+ QList<PluginSpec *> plugins;
+ if (defaultCollection)
+ plugins = defaultCollection->plugins();
- if (childItem->parent() && !childItem->parent()->isExpanded())
- childItem->parent()->setExpanded(true);
+ if (!plugins.isEmpty()) {
+ // add all non-categorized plugins into utilities. could also be added as root items
+ // but that makes the tree ugly.
+ collections.append(new CollectionItem(tr("Utilities"), plugins, this));
}
+
+ Utils::sort(collections, [](CollectionItem *a, CollectionItem *b) -> bool
+ { return a->m_name < b->m_name; });
+
+ foreach (CollectionItem *collection, collections)
+ m_model->rootItem()->appendChild(collection);
+
+ m_model->layoutChanged();
+ m_categoryView->expandAll();
}
+
+} // namespace ExtensionSystem
diff --git a/src/libs/extensionsystem/pluginview.h b/src/libs/extensionsystem/pluginview.h
index 51718ba9770..e3ffc30897d 100644
--- a/src/libs/extensionsystem/pluginview.h
+++ b/src/libs/extensionsystem/pluginview.h
@@ -33,21 +33,22 @@
#include "extensionsystem_global.h"
-#include <QHash>
#include <QWidget>
-#include <QIcon>
-
-QT_BEGIN_NAMESPACE
-class QTreeWidgetItem;
-QT_END_NAMESPACE
+#include <QSet>
+#include <QHash>
-namespace Utils { class TreeWidget; }
+namespace Utils {
+class TreeItem;
+class TreeModel;
+class TreeView;
+} // namespace Utils
namespace ExtensionSystem {
class PluginManager;
class PluginSpec;
-class PluginCollection;
+class PluginItem;
+class CollectionItem;
class EXTENSIONSYSTEM_EXPORT PluginView : public QWidget
{
@@ -64,28 +65,16 @@ signals:
void pluginActivated(ExtensionSystem::PluginSpec *spec);
void pluginSettingsChanged(ExtensionSystem::PluginSpec *spec);
-private slots:
- void updatePluginSettings(QTreeWidgetItem *item, int column);
- void updateList();
- void selectPlugin(QTreeWidgetItem *current);
- void activatePlugin(QTreeWidgetItem *item);
-
private:
- enum ParsedState { ParsedNone = 1, ParsedPartial = 2, ParsedAll = 4, ParsedWithErrors = 8};
- QIcon iconForState(int state);
- void updatePluginDependencies();
- int parsePluginSpecs(QTreeWidgetItem *parentItem, Qt::CheckState &groupState, QList<PluginSpec*> plugins);
-
- Utils::TreeWidget *m_categoryWidget;
- QList<QTreeWidgetItem*> m_items;
- QHash<PluginSpec*, QTreeWidgetItem*> m_specToItem;
+ PluginSpec *pluginForIndex(const QModelIndex &index) const;
+ void updatePlugins();
- QIcon m_okIcon;
- QIcon m_errorIcon;
- QIcon m_notLoadedIcon;
- bool m_allowCheckStateUpdate;
+ Utils::TreeView *m_categoryView;
+ Utils::TreeModel *m_model;
- const int C_LOAD;
+ friend class CollectionItem;
+ friend class PluginItem;
+ QHash<PluginSpec *, QSet<PluginSpec *>> m_pluginDependencies;
};
} // namespae ExtensionSystem
diff --git a/src/libs/glsl/glslengine.cpp b/src/libs/glsl/glslengine.cpp
index a7846daf85f..06f43d5e58f 100644
--- a/src/libs/glsl/glslengine.cpp
+++ b/src/libs/glsl/glslengine.cpp
@@ -231,7 +231,7 @@ bool DiagnosticMessage::isError() const
return _kind == Error;
}
-bool GLSL::DiagnosticMessage::isWarning() const
+bool DiagnosticMessage::isWarning() const
{
return _kind == Warning;
}
diff --git a/src/libs/glsl/glslmemorypool.cpp b/src/libs/glsl/glslmemorypool.cpp
index 0166eb133bf..46f581001ea 100644
--- a/src/libs/glsl/glslmemorypool.cpp
+++ b/src/libs/glsl/glslmemorypool.cpp
@@ -89,21 +89,6 @@ void *MemoryPool::allocate_helper(size_t size)
return addr;
}
-RecursiveMemoryPool::RecursiveMemoryPool(MemoryPool *pool)
- : _pool(pool),
- _blockCount(pool->_blockCount),
- _ptr(pool->_ptr),
- _end(pool->_end)
-{
-}
-
-RecursiveMemoryPool::~RecursiveMemoryPool()
-{
- _pool->_blockCount = _blockCount;
- _pool->_ptr = _ptr;
- _pool->_end = _end;
-}
-
Managed::Managed()
{ }
diff --git a/src/libs/glsl/glslmemorypool.h b/src/libs/glsl/glslmemorypool.h
index 42ebba28194..24daf6a52b7 100644
--- a/src/libs/glsl/glslmemorypool.h
+++ b/src/libs/glsl/glslmemorypool.h
@@ -37,7 +37,6 @@
namespace GLSL {
class MemoryPool;
-class RecursiveMemoryPool;
class GLSL_EXPORT MemoryPool
{
@@ -76,20 +75,6 @@ private:
BLOCK_SIZE = 8 * 1024,
DEFAULT_BLOCK_COUNT = 8
};
-
- friend class RecursiveMemoryPool;
-};
-
-class GLSL_EXPORT RecursiveMemoryPool
-{
- MemoryPool *_pool;
- int _blockCount;
- char *_ptr;
- char *_end;
-
-public:
- RecursiveMemoryPool(MemoryPool *pool);
- ~RecursiveMemoryPool();
};
class GLSL_EXPORT Managed
diff --git a/src/libs/glsl/glslsemantic.cpp b/src/libs/glsl/glslsemantic.cpp
index bef82f02522..18aecef0851 100644
--- a/src/libs/glsl/glslsemantic.cpp
+++ b/src/libs/glsl/glslsemantic.cpp
@@ -378,8 +378,8 @@ bool Semantic::visit(FunctionCallExpressionAST *ast)
_engine->error(ast->lineno, QString::fromLatin1("too many arguments"));
_expr.type = funTy->returnType();
} else if (const OverloadSet *overloads = id.type->asOverloadSetType()) {
- QVector<GLSL::Function *> candidates;
- foreach (GLSL::Function *f, overloads->functions()) {
+ QVector<Function *> candidates;
+ foreach (Function *f, overloads->functions()) {
if (f->argumentCount() == actuals.size()) {
int argc = 0;
for (; argc < actuals.size(); ++argc) {
diff --git a/src/libs/libs.pro b/src/libs/libs.pro
index bc8e6ac3e93..10860cfb766 100644
--- a/src/libs/libs.pro
+++ b/src/libs/libs.pro
@@ -12,7 +12,8 @@ SUBDIRS = \
qmldebug \
qmleditorwidgets \
glsl \
- ssh
+ ssh \
+ timeline
for(l, SUBDIRS) {
QTC_LIB_DEPENDS =
diff --git a/src/libs/libs.qbs b/src/libs/libs.qbs
index 6a43b7b2c0a..b0144285224 100644
--- a/src/libs/libs.qbs
+++ b/src/libs/libs.qbs
@@ -13,6 +13,7 @@ Project {
"qmldebug/qmldebug.qbs",
"qtcreatorcdbext/qtcreatorcdbext.qbs",
"ssh/ssh.qbs",
+ "timeline/timeline.qbs",
"utils/process_stub.qbs",
"utils/process_ctrlc_stub.qbs",
"utils/utils.qbs",
diff --git a/src/libs/qmleditorwidgets/contextpanetextwidget.cpp b/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
index 644c9881336..4a0d10fa8fd 100644
--- a/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
+++ b/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
@@ -67,31 +67,50 @@ ContextPaneTextWidget::ContextPaneTextWidget(QWidget *parent) :
ui->colorButton->setShowArrow(false);
ui->textColorButton->setShowArrow(false);
- connect(ui->colorButton, SIGNAL(toggled(bool)), this, SLOT(onColorButtonToggled(bool)));
- connect(ui->textColorButton, SIGNAL(toggled(bool)), this, SLOT(onTextColorButtonToggled(bool)));
+ connect(ui->colorButton, &QmlEditorWidgets::ColorButton::toggled,
+ this, &ContextPaneTextWidget::onColorButtonToggled);
+ connect(ui->textColorButton, &QmlEditorWidgets::ColorButton::toggled,
+ this, &ContextPaneTextWidget::onTextColorButtonToggled);
ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget());
- connect(parentContextWidget->colorDialog(), SIGNAL(accepted(QColor)), this, SLOT(onColorDialogApplied(QColor)));
- connect(parentContextWidget->colorDialog(), SIGNAL(rejected()), this, SLOT(onColorDialogCancled()));
-
- connect(ui->fontSizeSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onFontSizeChanged(int)));
- connect(ui->fontSizeSpinBox, SIGNAL(formatChanged()), this, SLOT(onFontFormatChanged()));
-
- connect(ui->boldButton, SIGNAL(toggled(bool)), this, SLOT(onBoldCheckedChanged(bool)));
- connect(ui->italicButton, SIGNAL(toggled(bool)), this, SLOT(onItalicCheckedChanged(bool)));
- connect(ui->underlineButton, SIGNAL(toggled(bool)), this, SLOT(onUnderlineCheckedChanged(bool)));
- connect(ui->strikeoutButton, SIGNAL(toggled(bool)), this, SLOT(onStrikeoutCheckedChanged(bool)));
- connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SLOT(onCurrentFontChanged(QFont)));
-
- connect(ui->centerHAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged()));
- connect(ui->leftAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged()));
- connect(ui->rightAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalAlignmentChanged()));
-
- connect(ui->centerVAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged()));
- connect(ui->topAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged()));
- connect(ui->bottomAlignmentButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalAlignmentChanged()));
-
- connect(ui->styleComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(onStyleComboBoxChanged(QString)));
+ connect(parentContextWidget->colorDialog(), &CustomColorDialog::accepted,
+ this, &ContextPaneTextWidget::onColorDialogApplied);
+ connect(parentContextWidget->colorDialog(), &CustomColorDialog::rejected,
+ this, &ContextPaneTextWidget::onColorDialogCancled);
+
+ connect(ui->fontSizeSpinBox,
+ static_cast<void (QmlEditorWidgets::FontSizeSpinBox::*)(int)>(&QmlEditorWidgets::FontSizeSpinBox::valueChanged),
+ this, &ContextPaneTextWidget::onFontSizeChanged);
+ connect(ui->fontSizeSpinBox, &QmlEditorWidgets::FontSizeSpinBox::formatChanged,
+ this, &ContextPaneTextWidget::onFontFormatChanged);
+
+ connect(ui->boldButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onBoldCheckedChanged);
+ connect(ui->italicButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onItalicCheckedChanged);
+ connect(ui->underlineButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onUnderlineCheckedChanged);
+ connect(ui->strikeoutButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onStrikeoutCheckedChanged);
+ connect(ui->fontComboBox, &QFontComboBox::currentFontChanged,
+ this, &ContextPaneTextWidget::onCurrentFontChanged);
+
+ connect(ui->centerHAlignmentButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onHorizontalAlignmentChanged);
+ connect(ui->leftAlignmentButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onHorizontalAlignmentChanged);
+ connect(ui->rightAlignmentButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onHorizontalAlignmentChanged);
+
+ connect(ui->centerVAlignmentButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onVerticalAlignmentChanged);
+ connect(ui->topAlignmentButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onVerticalAlignmentChanged);
+ connect(ui->bottomAlignmentButton, &QToolButton::toggled,
+ this, &ContextPaneTextWidget::onVerticalAlignmentChanged);
+
+ connect(ui->styleComboBox, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged),
+ this, &ContextPaneTextWidget::onStyleComboBoxChanged);
}
static inline bool checkIfBoolean(const QVariant &v)
diff --git a/src/libs/qmleditorwidgets/contextpanewidget.cpp b/src/libs/qmleditorwidgets/contextpanewidget.cpp
index 8bc8a326077..680bced6439 100644
--- a/src/libs/qmleditorwidgets/contextpanewidget.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidget.cpp
@@ -183,7 +183,7 @@ ContextPaneWidget::ContextPaneWidget(QWidget *parent) : DragWidget(parent), m_cu
m_toolButton->setFixedSize(16, 16);
m_toolButton->setToolTip(tr("Hides this toolbar."));
- connect(m_toolButton, SIGNAL(clicked()), this, SLOT(onTogglePane()));
+ connect(m_toolButton, &QToolButton::clicked, this, &ContextPaneWidget::onTogglePane);
layout->addWidget(m_toolButton, 0, 0, 1, 1);
colorDialog();
@@ -431,9 +431,12 @@ void ContextPaneWidget::protectedMoved()
QWidget* ContextPaneWidget::createFontWidget()
{
m_textWidget = new ContextPaneTextWidget(this);
- connect(m_textWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
- connect(m_textWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
- connect(m_textWidget, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)), this, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)));
+ connect(m_textWidget, &ContextPaneTextWidget::propertyChanged,
+ this, &ContextPaneWidget::propertyChanged);
+ connect(m_textWidget, &ContextPaneTextWidget::removeProperty,
+ this, &ContextPaneWidget::removeProperty);
+ connect(m_textWidget, &ContextPaneTextWidget::removeAndChangeProperty,
+ this, &ContextPaneWidget::removeAndChangeProperty);
return m_textWidget;
}
@@ -442,9 +445,12 @@ QWidget* ContextPaneWidget::createEasingWidget()
{
m_easingWidget = new EasingContextPane(this);
- connect(m_easingWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
- connect(m_easingWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
- connect(m_easingWidget, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)), this, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)));
+ connect(m_easingWidget, &EasingContextPane::propertyChanged,
+ this, &ContextPaneWidget::propertyChanged);
+ connect(m_easingWidget, &EasingContextPane::removeProperty,
+ this, &ContextPaneWidget::removeProperty);
+ connect(m_easingWidget, &EasingContextPane::removeAndChangeProperty,
+ this, &ContextPaneWidget::removeAndChangeProperty);
return m_easingWidget;
}
@@ -452,9 +458,12 @@ QWidget* ContextPaneWidget::createEasingWidget()
QWidget *ContextPaneWidget::createImageWidget()
{
m_imageWidget = new ContextPaneWidgetImage(this);
- connect(m_imageWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
- connect(m_imageWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
- connect(m_imageWidget, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)), this, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)));
+ connect(m_imageWidget, &ContextPaneWidgetImage::propertyChanged,
+ this, &ContextPaneWidget::propertyChanged);
+ connect(m_imageWidget, &ContextPaneWidgetImage::removeProperty,
+ this, &ContextPaneWidget::removeProperty);
+ connect(m_imageWidget, &ContextPaneWidgetImage::removeAndChangeProperty,
+ this, &ContextPaneWidget::removeAndChangeProperty);
return m_imageWidget;
}
@@ -462,9 +471,12 @@ QWidget *ContextPaneWidget::createImageWidget()
QWidget *ContextPaneWidget::createBorderImageWidget()
{
m_borderImageWidget = new ContextPaneWidgetImage(this, true);
- connect(m_borderImageWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
- connect(m_borderImageWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
- connect(m_borderImageWidget, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)), this, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)));
+ connect(m_borderImageWidget, &ContextPaneWidgetImage::propertyChanged,
+ this, &ContextPaneWidget::propertyChanged);
+ connect(m_borderImageWidget, &ContextPaneWidgetImage::removeProperty,
+ this, &ContextPaneWidget::removeProperty);
+ connect(m_borderImageWidget, &ContextPaneWidgetImage::removeAndChangeProperty,
+ this, &ContextPaneWidget::removeAndChangeProperty);
return m_borderImageWidget;
@@ -473,9 +485,12 @@ QWidget *ContextPaneWidget::createBorderImageWidget()
QWidget *ContextPaneWidget::createRectangleWidget()
{
m_rectangleWidget = new ContextPaneWidgetRectangle(this);
- connect(m_rectangleWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
- connect(m_rectangleWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
- connect(m_rectangleWidget, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)), this, SIGNAL(removeAndChangeProperty(QString,QString,QVariant,bool)));
+ connect(m_rectangleWidget, &ContextPaneWidgetRectangle::propertyChanged,
+ this, &ContextPaneWidget::propertyChanged);
+ connect(m_rectangleWidget, &ContextPaneWidgetRectangle::removeProperty,
+ this, &ContextPaneWidget::removeProperty);
+ connect(m_rectangleWidget, &ContextPaneWidgetRectangle::removeAndChangeProperty,
+ this, &ContextPaneWidget::removeAndChangeProperty);
return m_rectangleWidget;
}
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp b/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
index db683d6af4c..3e458c5ae28 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
@@ -89,18 +89,28 @@ ContextPaneWidgetImage::ContextPaneWidgetImage(QWidget *parent, bool borderImage
uiBorderImage->label->installEventFilter(labelFilter);
- connect(uiBorderImage->verticalTileRadioButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalStretchChanged()));
- connect(uiBorderImage->verticalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onVerticalStretchChanged()));
- connect(uiBorderImage->verticalTileRadioButtonNoCrop, SIGNAL(toggled(bool)), this, SLOT(onVerticalStretchChanged()));
-
- connect(uiBorderImage->horizontalTileRadioButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalStretchChanged()));
- connect(uiBorderImage->horizontalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onHorizontalStretchChanged()));
- connect(uiBorderImage->horizontalTileRadioButtonNoCrop, SIGNAL(toggled(bool)), this, SLOT(onHorizontalStretchChanged()));
+ connect(uiBorderImage->verticalTileRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onVerticalStretchChanged);
+ connect(uiBorderImage->verticalStretchRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onVerticalStretchChanged);
+ connect(uiBorderImage->verticalTileRadioButtonNoCrop, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onVerticalStretchChanged);
+
+ connect(uiBorderImage->horizontalTileRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onHorizontalStretchChanged);
+ connect(uiBorderImage->horizontalStretchRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onHorizontalStretchChanged);
+ connect(uiBorderImage->horizontalTileRadioButtonNoCrop, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onHorizontalStretchChanged);
PreviewLabel *previewLabel = previewDialog()->previewLabel();
- connect(previewLabel, SIGNAL(leftMarginChanged()), this, SLOT(onLeftMarginsChanged()));
- connect(previewLabel, SIGNAL(rightMarginChanged()), this, SLOT(onRightMarginsChanged()));
- connect(previewLabel, SIGNAL(topMarginChanged()), this, SLOT(onTopMarginsChanged()));
- connect(previewLabel, SIGNAL(bottomMarginChanged()), this, SLOT(onBottomMarginsChanged()));
+ connect(previewLabel, &PreviewLabel::leftMarginChanged,
+ this, &ContextPaneWidgetImage::onLeftMarginsChanged);
+ connect(previewLabel, &PreviewLabel::rightMarginChanged,
+ this, &ContextPaneWidgetImage::onRightMarginsChanged);
+ connect(previewLabel, &PreviewLabel::topMarginChanged,
+ this, &ContextPaneWidgetImage::onTopMarginsChanged);
+ connect(previewLabel, &PreviewLabel::bottomMarginChanged,
+ this, &ContextPaneWidgetImage::onBottomMarginsChanged);
} else {
ui = new Ui::ContextPaneWidgetImage;
@@ -110,19 +120,27 @@ ContextPaneWidgetImage::ContextPaneWidgetImage(QWidget *parent, bool borderImage
m_fileWidget = ui->fileWidget;
m_sizeLabel = ui->sizeLabel;
- connect(ui->stretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
- connect(ui->tileRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
- connect(ui->horizontalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
- connect(ui->verticalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
- connect(ui->preserveAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
- connect(ui->cropAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
+ connect(ui->stretchRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onStretchChanged);
+ connect(ui->tileRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onStretchChanged);
+ connect(ui->horizontalStretchRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onStretchChanged);
+ connect(ui->verticalStretchRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onStretchChanged);
+ connect(ui->preserveAspectFitRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onStretchChanged);
+ connect(ui->cropAspectFitRadioButton, &QRadioButton::toggled,
+ this, &ContextPaneWidgetImage::onStretchChanged);
}
previewDialog();
m_fileWidget->setShowComboBox(true);
m_fileWidget->setFilter(QLatin1String("*.png *.gif *.jpg"));
- connect(m_fileWidget, SIGNAL(fileNameChanged(QUrl)), this, SLOT(onFileNameChanged()));
- connect(labelFilter, SIGNAL(doubleClicked()), this, SLOT(onPixmapDoubleClicked()));
+ connect(m_fileWidget, &FileWidget::fileNameChanged,
+ this, &ContextPaneWidgetImage::onFileNameChanged);
+ connect(labelFilter, &LabelFilter::doubleClicked,
+ this, &ContextPaneWidgetImage::onPixmapDoubleClicked);
}
@@ -881,7 +899,7 @@ PreviewDialog::PreviewDialog(QWidget *parent) : DragWidget(parent)
toolButton->setIcon(icon);
toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
toolButton->setFixedSize(icon.availableSizes().value(0) + QSize(4, 4));
- connect(toolButton, SIGNAL(clicked()), this, SLOT(onTogglePane()));
+ connect(toolButton, &QToolButton::clicked, this, &PreviewDialog::onTogglePane);
QScrollArea *scrollArea = new QScrollArea(this);
WheelFilter *wheelFilter = new WheelFilter(scrollArea);
@@ -906,7 +924,7 @@ PreviewDialog::PreviewDialog(QWidget *parent) : DragWidget(parent)
wheelFilter->setTarget(this);
- connect(m_slider, SIGNAL(valueChanged(int)), this, SLOT(onSliderMoved(int)));
+ connect(m_slider, &QSlider::valueChanged, this, &PreviewDialog::onSliderMoved);
foreach (QWidget *childWidget, findChildren<QWidget*>()) {
childWidget->installEventFilter(wheelFilter);
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
index 544804720f1..1c5e83e729f 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
@@ -50,23 +50,33 @@ ContextPaneWidgetRectangle::ContextPaneWidgetRectangle(QWidget *parent) :
ui->colorColorButton->setShowArrow(false);
ui->borderColorButton->setShowArrow(false);
- connect(ui->colorColorButton, SIGNAL(toggled(bool)), this, SLOT(onColorButtonToggled(bool)));
- connect(ui->borderColorButton, SIGNAL(toggled(bool)), this, SLOT(onBorderColorButtonToggled(bool)));
+ connect(ui->colorColorButton, &QmlEditorWidgets::ColorButton::toggled,
+ this, &ContextPaneWidgetRectangle::onColorButtonToggled);
+ connect(ui->borderColorButton, &QmlEditorWidgets::ColorButton::toggled,
+ this, &ContextPaneWidgetRectangle::onBorderColorButtonToggled);
- connect(ui->colorSolid, SIGNAL(clicked()), this, SLOT(onColorSolidClicked()));
- connect(ui->borderSolid, SIGNAL(clicked()), this, SLOT(onBorderSolidClicked()));
+ connect(ui->colorSolid, &QToolButton::clicked,
+ this, &ContextPaneWidgetRectangle::onColorSolidClicked);
+ connect(ui->borderSolid, &QToolButton::clicked,
+ this, &ContextPaneWidgetRectangle::onBorderSolidClicked);
- connect(ui->colorNone, SIGNAL(clicked()), this, SLOT(onColorNoneClicked()));
- connect(ui->borderNone, SIGNAL(clicked()), this, SLOT(onBorderNoneClicked()));
+ connect(ui->colorNone, &QToolButton::clicked,
+ this, &ContextPaneWidgetRectangle::onColorNoneClicked);
+ connect(ui->borderNone, &QToolButton::clicked,
+ this, &ContextPaneWidgetRectangle::onBorderNoneClicked);
- connect(ui->colorGradient, SIGNAL(clicked()), this, SLOT(onGradientClicked()));
+ connect(ui->colorGradient, &QToolButton::clicked, this, &ContextPaneWidgetRectangle::onGradientClicked);
ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget());
- connect(parentContextWidget->colorDialog(), SIGNAL(accepted(QColor)), this, SLOT(onColorDialogApplied(QColor)));
- connect(parentContextWidget->colorDialog(), SIGNAL(rejected()), this, SLOT(onColorDialogCancled()));
-
- connect(ui->gradientLine, SIGNAL(openColorDialog(QPoint)), this, SLOT(onGradientLineDoubleClicked(QPoint)));
- connect(ui->gradientLine, SIGNAL(gradientChanged()), this, SLOT(onUpdateGradient()));
+ connect(parentContextWidget->colorDialog(), &CustomColorDialog::accepted,
+ this, &ContextPaneWidgetRectangle::onColorDialogApplied);
+ connect(parentContextWidget->colorDialog(), &CustomColorDialog::rejected,
+ this, &ContextPaneWidgetRectangle::onColorDialogCancled);
+
+ connect(ui->gradientLine, &QmlEditorWidgets::GradientLine::openColorDialog,
+ this, &ContextPaneWidgetRectangle::onGradientLineDoubleClicked);
+ connect(ui->gradientLine, &QmlEditorWidgets::GradientLine::gradientChanged,
+ this, &ContextPaneWidgetRectangle::onUpdateGradient);
}
ContextPaneWidgetRectangle::~ContextPaneWidgetRectangle()
diff --git a/src/libs/qmleditorwidgets/customcolordialog.cpp b/src/libs/qmleditorwidgets/customcolordialog.cpp
index 583f826a2eb..1e2343fee88 100644
--- a/src/libs/qmleditorwidgets/customcolordialog.cpp
+++ b/src/libs/qmleditorwidgets/customcolordialog.cpp
@@ -121,15 +121,23 @@ CustomColorDialog::CustomColorDialog(QWidget *parent) : QFrame(parent )
resize(sizeHint());
- connect(m_colorBox, SIGNAL(colorChanged()), this, SLOT(onColorBoxChanged()));
- connect(m_alphaSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged()));
- connect(m_rSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged()));
- connect(m_gSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged()));
- connect(m_bSpinBox, SIGNAL(valueChanged(double)), this, SLOT(spinBoxChanged()));
- connect(m_hueControl, SIGNAL(hueChanged(int)), this, SLOT(onHueChanged(int)));
-
- connect(applyButton, SIGNAL(pressed()), this, SLOT(onAccept()));
- connect(cancelButton, SIGNAL(pressed()), this, SIGNAL(rejected()));
+ connect(m_colorBox, &ColorBox::colorChanged, this, &CustomColorDialog::onColorBoxChanged);
+ connect(m_alphaSpinBox,
+ static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
+ this, &CustomColorDialog::spinBoxChanged);
+ connect(m_rSpinBox,
+ static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
+ this, &CustomColorDialog::spinBoxChanged);
+ connect(m_gSpinBox,
+ static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
+ this, &CustomColorDialog::spinBoxChanged);
+ connect(m_bSpinBox,
+ static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
+ this, &CustomColorDialog::spinBoxChanged);
+ connect(m_hueControl, &HueControl::hueChanged, this, &CustomColorDialog::onHueChanged);
+
+ connect(applyButton, &QPushButton::pressed, this, &CustomColorDialog::onAccept);
+ connect(cancelButton, &QPushButton::pressed, this, &CustomColorDialog::rejected);
m_alphaSpinBox->setMaximum(1);
m_rSpinBox->setMaximum(1);
diff --git a/src/libs/qmleditorwidgets/filewidget.cpp b/src/libs/qmleditorwidgets/filewidget.cpp
index 936dd4ef81f..537dcc891bb 100644
--- a/src/libs/qmleditorwidgets/filewidget.cpp
+++ b/src/libs/qmleditorwidgets/filewidget.cpp
@@ -62,9 +62,9 @@ FileWidget::FileWidget(QWidget *parent) :
m_comboBox->setEditable(true);
layout->addWidget(m_pushButton);
m_pushButton->setText(QLatin1String("..."));
- connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChanged()));
- connect(m_pushButton, SIGNAL(released()), this, SLOT(onButtonReleased()));
- connect(m_comboBox, SIGNAL(editTextChanged(QString)), this, SLOT(comboBoxChanged()));
+ connect(m_lineEdit, &QLineEdit::editingFinished, this, &FileWidget::lineEditChanged);
+ connect(m_pushButton, &QToolButton::released, this, &FileWidget::onButtonReleased);
+ connect(m_comboBox, &QComboBox::editTextChanged, this, &FileWidget::comboBoxChanged);
}
FileWidget::~FileWidget()
diff --git a/src/libs/qmleditorwidgets/fontsizespinbox.cpp b/src/libs/qmleditorwidgets/fontsizespinbox.cpp
index 07c9e444e0c..fbcc4608245 100644
--- a/src/libs/qmleditorwidgets/fontsizespinbox.cpp
+++ b/src/libs/qmleditorwidgets/fontsizespinbox.cpp
@@ -38,7 +38,8 @@ namespace QmlEditorWidgets {
FontSizeSpinBox::FontSizeSpinBox(QWidget *parent) :
QAbstractSpinBox(parent), m_isPointSize(true), m_value(0)
{
- connect(this, SIGNAL(editingFinished()), this, SLOT(onEditingFinished()));
+ connect(this, &FontSizeSpinBox::editingFinished,
+ this, &FontSizeSpinBox::onEditingFinished);
}
void FontSizeSpinBox::stepBy(int steps)
diff --git a/src/libs/qmljs/qmljsmodelmanagerinterface.cpp b/src/libs/qmljs/qmljsmodelmanagerinterface.cpp
index 34224193ddd..4ec0a70c865 100644
--- a/src/libs/qmljs/qmljsmodelmanagerinterface.cpp
+++ b/src/libs/qmljs/qmljsmodelmanagerinterface.cpp
@@ -977,7 +977,7 @@ struct ScanItem {
void ModelManagerInterface::importScan(QFutureInterface<void> &future,
ModelManagerInterface::WorkingCopy workingCopy,
PathsAndLanguages paths, ModelManagerInterface *modelManager,
- bool emitDocChangedOnDisk)
+ bool emitDocChangedOnDisk, bool libOnly)
{
// paths we have scanned for files and added to the files list
QSet<QString> scannedPaths;
@@ -1005,7 +1005,6 @@ void ModelManagerInterface::importScan(QFutureInterface<void> &future,
int progressRange = pathsToScan.size() * (1 << (2 + maxScanDepth));
int totalWork(progressRange), workDone(0);
future.setProgressRange(0, progressRange); // update max length while iterating?
- const bool libOnly = true; // FIXME remove when tested more
const Snapshot snapshot = modelManager->snapshot();
while (!pathsToScan.isEmpty() && !future.isCanceled()) {
ScanItem toScan = pathsToScan.last();
@@ -1087,7 +1086,7 @@ void ModelManagerInterface::maybeScan(const PathsAndLanguages &importPaths)
if (pathToScan.length() > 1) {
QFuture<void> result = QtConcurrent::run(&ModelManagerInterface::importScan,
workingCopyInternal(), pathToScan,
- this, true);
+ this, true, true);
if (m_synchronizer.futures().size() > 10) {
QList<QFuture<void> > futures = m_synchronizer.futures();
diff --git a/src/libs/qmljs/qmljsmodelmanagerinterface.h b/src/libs/qmljs/qmljsmodelmanagerinterface.h
index 8ec1d1361bf..8b4a91fc989 100644
--- a/src/libs/qmljs/qmljsmodelmanagerinterface.h
+++ b/src/libs/qmljs/qmljsmodelmanagerinterface.h
@@ -211,7 +211,7 @@ public:
WorkingCopy workingCopyInternal,
PathsAndLanguages paths,
ModelManagerInterface *modelManager,
- bool emitDocChangedOnDisk);
+ bool emitDocChangedOnDisk, bool libOnly = true);
public slots:
virtual void resetCodeModel();
void removeProjectInfo(ProjectExplorer::Project *project);
diff --git a/src/libs/qmljs/qmljsstaticanalysismessage.cpp b/src/libs/qmljs/qmljsstaticanalysismessage.cpp
index 5c71341b74d..bd8a7e78aab 100644
--- a/src/libs/qmljs/qmljsstaticanalysismessage.cpp
+++ b/src/libs/qmljs/qmljsstaticanalysismessage.cpp
@@ -231,7 +231,7 @@ StaticAnalysisMessages::StaticAnalysisMessages()
newMsg(ErrFunctionsNotSupportedInQmlUi, Error,
tr("Functions are not supported in a Qt Quick UI form."));
newMsg(ErrBlocksNotSupportedInQmlUi, Error,
- tr("Java Script blocks are not supported in a Qt Quick UI form."));
+ tr("JavaScript blocks are not supported in a Qt Quick UI form."));
newMsg(ErrBehavioursNotSupportedInQmlUi, Error,
tr("Behavior type is not supported in a Qt Quick UI form."));
newMsg(ErrStatesOnlyInRootItemInQmlUi, Error,
diff --git a/src/libs/qmljs/qmljstypedescriptionreader.cpp b/src/libs/qmljs/qmljstypedescriptionreader.cpp
index 625f0c1c35f..e37d72aba0a 100644
--- a/src/libs/qmljs/qmljstypedescriptionreader.cpp
+++ b/src/libs/qmljs/qmljstypedescriptionreader.cpp
@@ -224,7 +224,7 @@ void TypeDescriptionReader::readComponent(UiObjectDefinition *ast)
fmo->setIsComposite(readBoolBinding(script));
} else {
addWarning(script->firstSourceLocation(),
- tr("Expected only name, prototype, defaultProperty, attachedType, exports "
+ tr("Expected only name, prototype, defaultProperty, attachedType, exports, "
"isSingleton, isCreatable, isComposite and exportMetaObjectRevisions "
"script bindings, not \"%1\".").arg(name));
}
diff --git a/src/libs/qtcreatorcdbext/gdbmihelpers.cpp b/src/libs/qtcreatorcdbext/gdbmihelpers.cpp
index cd1026ae67d..1285ba905de 100644
--- a/src/libs/qtcreatorcdbext/gdbmihelpers.cpp
+++ b/src/libs/qtcreatorcdbext/gdbmihelpers.cpp
@@ -364,6 +364,34 @@ const wchar_t *valueType(ULONG type)
return L"";
}
+// Description of a DEBUG_VALUE type field
+const int valueSize(ULONG type)
+{
+ switch (type) {
+ case DEBUG_VALUE_INT8:
+ return 1;
+ case DEBUG_VALUE_INT16:
+ return 2;
+ case DEBUG_VALUE_INT32:
+ return 4;
+ case DEBUG_VALUE_INT64:
+ return 8;
+ case DEBUG_VALUE_FLOAT32:
+ return 4;
+ case DEBUG_VALUE_FLOAT64:
+ return 8;
+ case DEBUG_VALUE_FLOAT80:
+ return 10;
+ case DEBUG_VALUE_FLOAT128:
+ return 16;
+ case DEBUG_VALUE_VECTOR64:
+ return 8;
+ case DEBUG_VALUE_VECTOR128:
+ return 16;
+ }
+ return 0;
+}
+
// Format a 128bit vector register by adding digits in reverse order
void formatVectorRegister(std::ostream &str, const unsigned char *array, int size)
{
@@ -421,6 +449,7 @@ void formatDebugValue(std::ostream &str, const DEBUG_VALUE &dv, CIDebugControl *
Register::Register() : subRegister(false), pseudoRegister(false)
{
+ size = 0;
value.Type = DEBUG_VALUE_INT32;
value.I32 = 0;
}
@@ -497,6 +526,7 @@ Registers getRegisters(CIDebugRegisters *regs,
reg.pseudoRegister = true;
reg.name = buf;
reg.description = valueType(type);
+ reg.size = valueSize(type);
reg.value = value;
rc.push_back(reg);
}
diff --git a/src/libs/qtcreatorcdbext/gdbmihelpers.h b/src/libs/qtcreatorcdbext/gdbmihelpers.h
index e46abbb67dd..4ca96eb9dfc 100644
--- a/src/libs/qtcreatorcdbext/gdbmihelpers.h
+++ b/src/libs/qtcreatorcdbext/gdbmihelpers.h
@@ -129,6 +129,7 @@ struct Register
std::wstring name;
std::wstring description;
+ int size;
bool subRegister;
bool pseudoRegister;
DEBUG_VALUE value;
diff --git a/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp b/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp
index 3922f189591..d66854b8524 100644
--- a/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp
+++ b/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp
@@ -410,7 +410,7 @@ DumpCommandParameters::ParseOptionResult DumpCommandParameters::parseOption(Stri
// Display local variables of symbol group in GDBMI or debug output form.
// Takes an optional iname which is expanded before displaying (for updateWatchData)
-static std::string commmandLocals(ExtensionCommandContext &commandExtCtx,PCSTR args, int *token, std::string *errorMessage)
+static std::string commandLocals(ExtensionCommandContext &commandExtCtx,PCSTR args, int *token, std::string *errorMessage)
{
typedef WatchesSymbolGroup::InameExpressionMap InameExpressionMap;
typedef InameExpressionMap::value_type InameExpressionMapEntry;
@@ -565,7 +565,7 @@ extern "C" HRESULT CALLBACK locals(CIDebugClient *client, PCSTR args)
ExtensionCommandContext exc(client);
std::string errorMessage;
int token;
- const std::string output = commmandLocals(exc, args, &token, &errorMessage);
+ const std::string output = commandLocals(exc, args, &token, &errorMessage);
SymbolGroupValue::verbose = 0;
if (output.empty())
ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str());
diff --git a/src/libs/ssh/sftpchannel.cpp b/src/libs/ssh/sftpchannel.cpp
index eab1b03b07e..f68e4277025 100644
--- a/src/libs/ssh/sftpchannel.cpp
+++ b/src/libs/ssh/sftpchannel.cpp
@@ -87,18 +87,18 @@ SftpChannel::SftpChannel(quint32 channelId,
Internal::SshSendFacility &sendFacility)
: d(new Internal::SftpChannelPrivate(channelId, sendFacility, this))
{
- connect(d, SIGNAL(initialized()), this, SIGNAL(initialized()),
- Qt::QueuedConnection);
- connect(d, SIGNAL(channelError(QString)), this,
- SIGNAL(channelError(QString)), Qt::QueuedConnection);
- connect(d, SIGNAL(dataAvailable(QSsh::SftpJobId,QString)), this,
- SIGNAL(dataAvailable(QSsh::SftpJobId,QString)), Qt::QueuedConnection);
- connect(d, SIGNAL(fileInfoAvailable(QSsh::SftpJobId,QList<QSsh::SftpFileInfo>)), this,
- SIGNAL(fileInfoAvailable(QSsh::SftpJobId,QList<QSsh::SftpFileInfo>)),
- Qt::QueuedConnection);
- connect(d, SIGNAL(finished(QSsh::SftpJobId,QString)), this,
- SIGNAL(finished(QSsh::SftpJobId,QString)), Qt::QueuedConnection);
- connect(d, SIGNAL(closed()), this, SIGNAL(closed()), Qt::QueuedConnection);
+ connect(d, &Internal::SftpChannelPrivate::initialized,
+ this, &SftpChannel::initialized, Qt::QueuedConnection);
+ connect(d, &Internal::SftpChannelPrivate::channelError,
+ this, &SftpChannel::channelError, Qt::QueuedConnection);
+ connect(d, &Internal::SftpChannelPrivate::dataAvailable,
+ this, &SftpChannel::dataAvailable, Qt::QueuedConnection);
+ connect(d, &Internal::SftpChannelPrivate::fileInfoAvailable,
+ this, &SftpChannel::fileInfoAvailable, Qt::QueuedConnection);
+ connect(d, &Internal::SftpChannelPrivate::finished,
+ this, &SftpChannel::finished, Qt::QueuedConnection);
+ connect(d, &Internal::SftpChannelPrivate::closed,
+ this, &SftpChannel::closed, Qt::QueuedConnection);
}
SftpChannel::State SftpChannel::state() const
diff --git a/src/libs/ssh/sftpfilesystemmodel.cpp b/src/libs/ssh/sftpfilesystemmodel.cpp
index 31b00c2e385..fdba8d136f3 100644
--- a/src/libs/ssh/sftpfilesystemmodel.cpp
+++ b/src/libs/ssh/sftpfilesystemmodel.cpp
@@ -115,12 +115,14 @@ void SftpFileSystemModel::setSshConnection(const SshConnectionParameters &sshPar
{
QSSH_ASSERT_AND_RETURN(!d->sshConnection);
d->sshConnection = QSsh::acquireConnection(sshParams);
- connect(d->sshConnection, SIGNAL(error(QSsh::SshError)), SLOT(handleSshConnectionFailure()));
+ connect(d->sshConnection, &SshConnection::error,
+ this, &SftpFileSystemModel::handleSshConnectionFailure);
if (d->sshConnection->state() == SshConnection::Connected) {
handleSshConnectionEstablished();
return;
}
- connect(d->sshConnection, SIGNAL(connected()), SLOT(handleSshConnectionEstablished()));
+ connect(d->sshConnection, &SshConnection::connected,
+ this, &SftpFileSystemModel::handleSshConnectionEstablished);
if (d->sshConnection->state() == SshConnection::Unconnected)
d->sshConnection->connectToHost();
}
diff --git a/src/libs/ssh/sftpincomingpacket.cpp b/src/libs/ssh/sftpincomingpacket.cpp
index e89c1cf9c98..4953d5a7b55 100644
--- a/src/libs/ssh/sftpincomingpacket.cpp
+++ b/src/libs/ssh/sftpincomingpacket.cpp
@@ -88,7 +88,7 @@ quint32 SftpIncomingPacket::extractServerVersion() const
Q_ASSERT(type() == SSH_FXP_VERSION);
try {
return SshPacketParser::asUint32(m_data, TypeOffset + 1);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_FXP_VERSION packet.");
}
@@ -104,7 +104,7 @@ SftpHandleResponse SftpIncomingPacket::asHandleResponse() const
response.requestId = SshPacketParser::asUint32(m_data, &offset);
response.handle = SshPacketParser::asString(m_data, &offset);
return response;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_FXP_HANDLE packet");
}
@@ -122,7 +122,7 @@ SftpStatusResponse SftpIncomingPacket::asStatusResponse() const
response.errorString = SshPacketParser::asUserString(m_data, &offset);
response.language = SshPacketParser::asString(m_data, &offset);
return response;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_FXP_STATUS packet.");
}
@@ -140,7 +140,7 @@ SftpNameResponse SftpIncomingPacket::asNameResponse() const
for (quint32 i = 0; i < count; ++i)
response.files << asFile(offset);
return response;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_FXP_NAME packet.");
}
@@ -156,7 +156,7 @@ SftpDataResponse SftpIncomingPacket::asDataResponse() const
response.requestId = SshPacketParser::asUint32(m_data, &offset);
response.data = SshPacketParser::asString(m_data, &offset);
return response;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_FXP_DATA packet.");
}
@@ -172,7 +172,7 @@ SftpAttrsResponse SftpIncomingPacket::asAttrsResponse() const
response.requestId = SshPacketParser::asUint32(m_data, &offset);
response.attrs = asFileAttributes(offset);
return response;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_FXP_ATTRS packet.");
}
diff --git a/src/libs/ssh/sftpoperation.cpp b/src/libs/ssh/sftpoperation.cpp
index 7de96d8a7af..cd6c580ba69 100644
--- a/src/libs/ssh/sftpoperation.cpp
+++ b/src/libs/ssh/sftpoperation.cpp
@@ -66,8 +66,8 @@ SftpOutgoingPacket &SftpMakeDir::initialPacket(SftpOutgoingPacket &packet)
}
-SftpRmDir::SftpRmDir(SftpJobId, const QString &path)
- : AbstractSftpOperation(jobId), remoteDir(path)
+SftpRmDir::SftpRmDir(SftpJobId id, const QString &path)
+ : AbstractSftpOperation(id), remoteDir(path)
{
}
diff --git a/src/libs/ssh/sftpoperation_p.h b/src/libs/ssh/sftpoperation_p.h
index 62c12b13969..4f53f8d30c9 100644
--- a/src/libs/ssh/sftpoperation_p.h
+++ b/src/libs/ssh/sftpoperation_p.h
@@ -96,7 +96,7 @@ struct SftpRmDir : public AbstractSftpOperation
{
typedef QSharedPointer<SftpRmDir> Ptr;
- SftpRmDir(SftpJobId jobId, const QString &path);
+ SftpRmDir(SftpJobId id, const QString &path);
virtual Type type() const { return RmDir; }
virtual SftpOutgoingPacket &initialPacket(SftpOutgoingPacket &packet);
diff --git a/src/libs/ssh/ssh.pro b/src/libs/ssh/ssh.pro
index 511d31b1cf0..f2b8036e899 100644
--- a/src/libs/ssh/ssh.pro
+++ b/src/libs/ssh/ssh.pro
@@ -28,7 +28,8 @@ SOURCES = $$PWD/sshsendfacility.cpp \
$$PWD/sftpfilesystemmodel.cpp \
$$PWD/sshkeycreationdialog.cpp \
$$PWD/sshinit.cpp \
- $$PWD/sshdirecttcpiptunnel.cpp
+ $$PWD/sshdirecttcpiptunnel.cpp \
+ $$PWD/sshhostkeydatabase.cpp
HEADERS = $$PWD/sshsendfacility_p.h \
$$PWD/sshremoteprocess.h \
@@ -64,7 +65,8 @@ HEADERS = $$PWD/sshsendfacility_p.h \
$$PWD/ssh_global.h \
$$PWD/sshdirecttcpiptunnel_p.h \
$$PWD/sshinit_p.h \
- $$PWD/sshdirecttcpiptunnel.h
+ $$PWD/sshdirecttcpiptunnel.h \
+ $$PWD/sshhostkeydatabase.h
FORMS = $$PWD/sshkeycreationdialog.ui
diff --git a/src/libs/ssh/ssh.qbs b/src/libs/ssh/ssh.qbs
index 486fa212cd3..8062f1a58ed 100644
--- a/src/libs/ssh/ssh.qbs
+++ b/src/libs/ssh/ssh.qbs
@@ -27,6 +27,8 @@ QtcLibrary {
"sshdirecttcpiptunnel.h", "sshdirecttcpiptunnel_p.h", "sshdirecttcpiptunnel.cpp",
"ssherrors.h",
"sshexception_p.h",
+ "sshhostkeydatabase.cpp",
+ "sshhostkeydatabase.h",
"sshincomingpacket_p.h", "sshincomingpacket.cpp",
"sshinit_p.h", "sshinit.cpp",
"sshkeycreationdialog.cpp", "sshkeycreationdialog.h", "sshkeycreationdialog.ui",
diff --git a/src/libs/ssh/sshchannel.cpp b/src/libs/ssh/sshchannel.cpp
index 30b7c6d0f84..05e3ba78fb2 100644
--- a/src/libs/ssh/sshchannel.cpp
+++ b/src/libs/ssh/sshchannel.cpp
@@ -48,13 +48,13 @@ const quint32 NoChannel = 0xffffffffu;
AbstractSshChannel::AbstractSshChannel(quint32 channelId,
SshSendFacility &sendFacility)
- : m_sendFacility(sendFacility), m_timeoutTimer(new QTimer(this)),
+ : m_sendFacility(sendFacility),
m_localChannel(channelId), m_remoteChannel(NoChannel),
m_localWindowSize(initialWindowSize()), m_remoteWindowSize(0),
m_state(Inactive)
{
- m_timeoutTimer->setSingleShot(true);
- connect(m_timeoutTimer, SIGNAL(timeout()), this, SIGNAL(timeout()));
+ m_timeoutTimer.setSingleShot(true);
+ connect(&m_timeoutTimer, &QTimer::timeout, this, &AbstractSshChannel::timeout);
}
AbstractSshChannel::~AbstractSshChannel()
@@ -78,8 +78,8 @@ void AbstractSshChannel::requestSessionStart()
try {
m_sendFacility.sendSessionPacket(m_localChannel, initialWindowSize(), maxPacketSize());
setChannelState(SessionRequested);
- m_timeoutTimer->start(ReplyTimeout);
- } catch (Botan::Exception &e) {
+ m_timeoutTimer.start(ReplyTimeout);
+ } catch (const Botan::Exception &e) {
qDebug("Botan error: %s", e.what());
closeChannel();
}
@@ -90,7 +90,7 @@ void AbstractSshChannel::sendData(const QByteArray &data)
try {
m_sendBuffer += data;
flushSendBuffer();
- } catch (Botan::Exception &e) {
+ } catch (const Botan::Exception &e) {
qDebug("Botan error: %s", e.what());
closeChannel();
}
@@ -147,7 +147,7 @@ void AbstractSshChannel::handleOpenSuccess(quint32 remoteChannelId,
"Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet.");
}
- m_timeoutTimer->stop();
+ m_timeoutTimer.stop();
if (remoteMaxPacketSize < MinMaxPacketSize) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
@@ -181,7 +181,7 @@ void AbstractSshChannel::handleOpenFailure(const QString &reason)
"Unexpected SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet.");
}
- m_timeoutTimer->stop();
+ m_timeoutTimer.stop();
#ifdef CREATOR_SSH_DEBUG
qDebug("Channel open request failed for channel %u", m_localChannel);
@@ -257,7 +257,7 @@ int AbstractSshChannel::handleChannelOrExtendedChannelData(const QByteArray &dat
void AbstractSshChannel::closeChannel()
{
if (m_state == CloseRequested) {
- m_timeoutTimer->stop();
+ m_timeoutTimer.stop();
} else if (m_state != Closed) {
if (m_state == Inactive) {
setChannelState(Closed);
diff --git a/src/libs/ssh/sshchannel_p.h b/src/libs/ssh/sshchannel_p.h
index 8e60710f30f..e67558fda00 100644
--- a/src/libs/ssh/sshchannel_p.h
+++ b/src/libs/ssh/sshchannel_p.h
@@ -34,8 +34,7 @@
#include <QByteArray>
#include <QObject>
#include <QString>
-
-QT_FORWARD_DECLARE_CLASS(QTimer)
+#include <QTimer>
namespace QSsh {
namespace Internal {
@@ -95,7 +94,7 @@ protected:
void checkChannelActive();
SshSendFacility &m_sendFacility;
- QTimer * const m_timeoutTimer;
+ QTimer m_timeoutTimer;
private:
virtual void handleOpenSuccessInternal() = 0;
diff --git a/src/libs/ssh/sshchannelmanager.cpp b/src/libs/ssh/sshchannelmanager.cpp
index cb79e949d8b..50d20518be5 100644
--- a/src/libs/ssh/sshchannelmanager.cpp
+++ b/src/libs/ssh/sshchannelmanager.cpp
@@ -68,7 +68,7 @@ void SshChannelManager::handleChannelOpenFailure(const SshIncomingPacket &packet
ChannelIterator it = lookupChannelAsIterator(failure.localChannel);
try {
it.value()->handleOpenFailure(failure.reasonString);
- } catch (SshServerException &e) {
+ } catch (const SshServerException &e) {
removeChannel(it);
throw e;
}
diff --git a/src/libs/ssh/sshconnection.cpp b/src/libs/ssh/sshconnection.cpp
index f873e35b51d..956e45a0fbd 100644
--- a/src/libs/ssh/sshconnection.cpp
+++ b/src/libs/ssh/sshconnection.cpp
@@ -65,7 +65,8 @@ namespace QSsh {
const QByteArray ClientId("SSH-2.0-QtCreator\r\n");
SshConnectionParameters::SshConnectionParameters() :
- timeout(0), authenticationType(AuthenticationTypePublicKey), port(0)
+ timeout(0), authenticationType(AuthenticationTypePublicKey), port(0),
+ hostKeyCheckingMode(SshHostKeyCheckingNone)
{
options |= SshIgnoreDefaultProxy;
options |= SshEnableStrictConformanceChecks;
@@ -77,6 +78,7 @@ static inline bool equals(const SshConnectionParameters &p1, const SshConnection
&& p1.authenticationType == p2.authenticationType
&& (p1.authenticationType == SshConnectionParameters::AuthenticationTypePassword ?
p1.password == p2.password : p1.privateKeyFile == p2.privateKeyFile)
+ && p1.hostKeyCheckingMode == p2.hostKeyCheckingMode
&& p1.timeout == p2.timeout && p1.port == p2.port;
}
@@ -90,7 +92,6 @@ bool operator!=(const SshConnectionParameters &p1, const SshConnectionParameters
return !equals(p1, p2);
}
-// TODO: Mechanism for checking the host key. First connection to host: save, later: compare
SshConnection::SshConnection(const SshConnectionParameters &serverInfo, QObject *parent)
: QObject(parent)
@@ -329,13 +330,13 @@ void SshConnectionPrivate::handleIncomingData()
if (m_serverId.isEmpty())
handleServerId();
handlePackets();
- } catch (SshServerException &e) {
+ } catch (const SshServerException &e) {
closeConnection(e.error, SshProtocolError, e.errorStringServer,
tr("SSH Protocol error: %1").arg(e.errorStringUser));
- } catch (SshClientException &e) {
+ } catch (const SshClientException &e) {
closeConnection(SSH_DISCONNECT_BY_APPLICATION, e.error, "",
e.errorString);
- } catch (Botan::Exception &e) {
+ } catch (const Botan::Exception &e) {
closeConnection(SSH_DISCONNECT_BY_APPLICATION, SshInternalError, "",
tr("Botan library exception: %1").arg(QString::fromLatin1(e.what())));
}
@@ -411,7 +412,7 @@ void SshConnectionPrivate::handleServerId()
}
}
- m_keyExchange.reset(new SshKeyExchange(m_sendFacility));
+ m_keyExchange.reset(new SshKeyExchange(m_connParams, m_sendFacility));
m_keyExchange->sendKexInitPacket(m_serverId);
m_keyExchangeState = KexInitSent;
}
@@ -460,7 +461,7 @@ void SshConnectionPrivate::handleKeyExchangeInitPacket()
// Server-initiated re-exchange.
if (m_keyExchangeState == NoKeyExchange) {
- m_keyExchange.reset(new SshKeyExchange(m_sendFacility));
+ m_keyExchange.reset(new SshKeyExchange(m_connParams, m_sendFacility));
m_keyExchange->sendKexInitPacket(m_serverId);
}
@@ -784,7 +785,7 @@ void SshConnectionPrivate::closeConnection(SshErrorCode sshError,
try {
m_channelManager->closeAllChannels(SshChannelManager::CloseAllAndReset);
m_sendFacility.sendDisconnectPacket(sshError, serverErrorString);
- } catch (Botan::Exception &) {} // Nothing sensible to be done here.
+ } catch (const Botan::Exception &) {} // Nothing sensible to be done here.
if (m_error != SshNoError)
emit error(userError);
if (m_state == ConnectionEstablished)
diff --git a/src/libs/ssh/sshconnection.h b/src/libs/ssh/sshconnection.h
index e535a60522c..db08eb34336 100644
--- a/src/libs/ssh/sshconnection.h
+++ b/src/libs/ssh/sshconnection.h
@@ -32,6 +32,7 @@
#define SSHCONNECTION_H
#include "ssherrors.h"
+#include "sshhostkeydatabase.h"
#include "ssh_global.h"
@@ -56,6 +57,13 @@ enum SshConnectionOption {
Q_DECLARE_FLAGS(SshConnectionOptions, SshConnectionOption)
+enum SshHostKeyCheckingMode {
+ SshHostKeyCheckingNone,
+ SshHostKeyCheckingStrict,
+ SshHostKeyCheckingAllowNoMatch,
+ SshHostKeyCheckingAllowMismatch
+};
+
class QSSH_EXPORT SshConnectionParameters
{
public:
@@ -78,6 +86,8 @@ public:
AuthenticationType authenticationType;
quint16 port;
SshConnectionOptions options;
+ SshHostKeyCheckingMode hostKeyCheckingMode;
+ SshHostKeyDatabasePtr hostKeyDatabase;
};
QSSH_EXPORT bool operator==(const SshConnectionParameters &p1, const SshConnectionParameters &p2);
diff --git a/src/libs/ssh/sshconnectionmanager.cpp b/src/libs/ssh/sshconnectionmanager.cpp
index ee895210195..a52f64bf06d 100644
--- a/src/libs/ssh/sshconnectionmanager.cpp
+++ b/src/libs/ssh/sshconnectionmanager.cpp
@@ -38,9 +38,23 @@
#include <QMutexLocker>
#include <QObject>
#include <QThread>
+#include <QTimer>
namespace QSsh {
namespace Internal {
+class UnaquiredConnection {
+public:
+ UnaquiredConnection(SshConnection *conn) : connection(conn), scheduledForRemoval(false) {}
+
+ SshConnection *connection;
+ bool scheduledForRemoval;
+};
+bool operator==(const UnaquiredConnection &c1, const UnaquiredConnection &c2) {
+ return c1.connection == c2.connection;
+}
+bool operator!=(const UnaquiredConnection &c1, const UnaquiredConnection &c2) {
+ return !(c1 == c2);
+}
class SshConnectionManager : public QObject
{
@@ -50,13 +64,16 @@ public:
SshConnectionManager()
{
moveToThread(QCoreApplication::instance()->thread());
+ connect(&m_removalTimer, &QTimer::timeout,
+ this, &SshConnectionManager::removeInactiveConnections);
+ m_removalTimer.start(150000); // For a total timeout of five minutes.
}
~SshConnectionManager()
{
- foreach (SshConnection * const connection, m_unacquiredConnections) {
- disconnect(connection, 0, this, 0);
- delete connection;
+ foreach (const UnaquiredConnection &connection, m_unacquiredConnections) {
+ disconnect(connection.connection, 0, this, 0);
+ delete connection.connection;
}
QSSH_ASSERT(m_acquiredConnections.isEmpty());
@@ -73,17 +90,18 @@ public:
continue;
if (connection->thread() != QThread::currentThread())
- break;
+ continue;
if (m_deprecatedConnections.contains(connection)) // we were asked to no longer use this one...
- break;
+ continue;
m_acquiredConnections.append(connection);
return connection;
}
- // Checked cached open connections:
- foreach (SshConnection * const connection, m_unacquiredConnections) {
+ // Check cached open connections:
+ foreach (const UnaquiredConnection &c, m_unacquiredConnections) {
+ SshConnection * const connection = c.connection;
if (connection->state() != SshConnection::Connected
|| connection->connectionParameters() != sshParams)
continue;
@@ -97,14 +115,15 @@ public:
Q_ARG(QObject *, QThread::currentThread()));
}
- m_unacquiredConnections.removeOne(connection);
+ m_unacquiredConnections.removeOne(c);
m_acquiredConnections.append(connection);
return connection;
}
// create a new connection:
SshConnection * const connection = new SshConnection(sshParams);
- connect(connection, SIGNAL(disconnected()), this, SLOT(cleanup()));
+ connect(connection, &SshConnection::disconnected,
+ this, &SshConnectionManager::cleanup);
m_acquiredConnections.append(connection);
return connection;
@@ -125,21 +144,21 @@ public:
|| connection->state() != SshConnection::Connected) {
doDelete = true;
} else {
- QSSH_ASSERT_AND_RETURN(!m_unacquiredConnections.contains(connection));
+ QSSH_ASSERT_AND_RETURN(!m_unacquiredConnections.contains(UnaquiredConnection(connection)));
// It can happen that two or more connections with the same parameters were acquired
// if the clients were running in different threads. Only keep one of them in
// such a case.
bool haveConnection = false;
- foreach (SshConnection * const conn, m_unacquiredConnections) {
- if (conn->connectionParameters() == connection->connectionParameters()) {
+ foreach (const UnaquiredConnection &c, m_unacquiredConnections) {
+ if (c.connection->connectionParameters() == connection->connectionParameters()) {
haveConnection = true;
break;
}
}
if (!haveConnection) {
connection->closeAllChannels(); // Clean up after neglectful clients.
- m_unacquiredConnections.append(connection);
+ m_unacquiredConnections.append(UnaquiredConnection(connection));
} else {
doDelete = true;
}
@@ -157,7 +176,7 @@ public:
QMutexLocker locker(&m_listMutex);
for (int i = 0; i < m_unacquiredConnections.count(); ++i) {
- SshConnection * const connection = m_unacquiredConnections.at(i);
+ SshConnection * const connection = m_unacquiredConnections.at(i).connection;
if (connection->connectionParameters() == sshParams) {
disconnect(connection, 0, this, 0);
delete connection;
@@ -189,23 +208,39 @@ private slots:
if (!currentConnection)
return;
- if (m_unacquiredConnections.removeOne(currentConnection)) {
+ if (m_unacquiredConnections.removeOne(UnaquiredConnection(currentConnection))) {
disconnect(currentConnection, 0, this, 0);
currentConnection->deleteLater();
}
}
+ void removeInactiveConnections()
+ {
+ QMutexLocker locker(&m_listMutex);
+ for (int i = m_unacquiredConnections.count() - 1; i >= 0; --i) {
+ UnaquiredConnection &c = m_unacquiredConnections[i];
+ if (c.scheduledForRemoval) {
+ disconnect(c.connection, 0, this, 0);
+ c.connection->deleteLater();
+ m_unacquiredConnections.removeAt(i);
+ } else {
+ c.scheduledForRemoval = true;
+ }
+ }
+ }
+
private:
// We expect the number of concurrently open connections to be small.
// If that turns out to not be the case, we can still use a data
// structure with faster access.
- QList<SshConnection *> m_unacquiredConnections;
+ QList<UnaquiredConnection> m_unacquiredConnections;
// Can contain the same connection more than once; this acts as a reference count.
QList<SshConnection *> m_acquiredConnections;
QList<SshConnection *> m_deprecatedConnections;
QMutex m_listMutex;
+ QTimer m_removalTimer;
};
} // namespace Internal
diff --git a/src/libs/ssh/sshcryptofacility.cpp b/src/libs/ssh/sshcryptofacility.cpp
index 684cd07651c..d4647b59fd9 100644
--- a/src/libs/ssh/sshcryptofacility.cpp
+++ b/src/libs/ssh/sshcryptofacility.cpp
@@ -263,10 +263,10 @@ bool SshEncryptionFacility::createAuthenticationKeyFromPKCS8(const QByteArray &p
qWarning("%s: Unexpected code flow, expected success or exception.", Q_FUNC_INFO);
return false;
}
- } catch (const Botan::Exception &ex) {
+ } catch (const Exception &ex) {
error = QLatin1String(ex.what());
return false;
- } catch (const Botan::Decoding_Error &ex) {
+ } catch (const Decoding_Error &ex) {
error = QLatin1String(ex.what());
return false;
}
@@ -334,10 +334,10 @@ bool SshEncryptionFacility::createAuthenticationKeyFromOpenSSL(const QByteArray
sequence.discard_remaining();
sequence.verify_end();
- } catch (const Botan::Exception &ex) {
+ } catch (const Exception &ex) {
error = QLatin1String(ex.what());
return false;
- } catch (const Botan::Decoding_Error &ex) {
+ } catch (const Decoding_Error &ex) {
error = QLatin1String(ex.what());
return false;
}
diff --git a/src/libs/ssh/sshdirecttcpiptunnel.cpp b/src/libs/ssh/sshdirecttcpiptunnel.cpp
index d187adbd731..57277233e29 100644
--- a/src/libs/ssh/sshdirecttcpiptunnel.cpp
+++ b/src/libs/ssh/sshdirecttcpiptunnel.cpp
@@ -160,8 +160,8 @@ void SshDirectTcpIpTunnel::initialize()
d->m_remotePort, d->m_connectionInfo.localAddress.toString().toUtf8(),
d->m_connectionInfo.localPort);
d->setChannelState(AbstractSshChannel::SessionRequested);
- d->m_timeoutTimer->start(d->ReplyTimeout);
- } catch (Botan::Exception &e) { // Won't happen, but let's play it safe.
+ d->m_timeoutTimer.start(d->ReplyTimeout);
+ } catch (const Botan::Exception &e) { // Won't happen, but let's play it safe.
qDebug("Botan error: %s", e.what());
d->closeChannel();
}
diff --git a/src/libs/ssh/sshhostkeydatabase.cpp b/src/libs/ssh/sshhostkeydatabase.cpp
new file mode 100644
index 00000000000..c06edd22962
--- /dev/null
+++ b/src/libs/ssh/sshhostkeydatabase.cpp
@@ -0,0 +1,120 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "sshhostkeydatabase.h"
+
+#include <QByteArray>
+#include <QCoreApplication>
+#include <QDir>
+#include <QFile>
+#include <QHash>
+#include <QString>
+
+namespace QSsh {
+
+class SshHostKeyDatabase::SshHostKeyDatabasePrivate
+{
+public:
+ QHash<QString, QByteArray> hostKeys;
+};
+
+SshHostKeyDatabase::SshHostKeyDatabase() : d(new SshHostKeyDatabasePrivate)
+{
+}
+
+SshHostKeyDatabase::~SshHostKeyDatabase()
+{
+ delete d;
+}
+
+bool SshHostKeyDatabase::load(const QString &filePath, QString *error)
+{
+ QFile file(filePath);
+ if (!file.open(QIODevice::ReadOnly)) {
+ if (error) {
+ *error = QCoreApplication::translate("QSsh::Ssh",
+ "Failed to open key file \"%1\" for reading: %2")
+ .arg(QDir::toNativeSeparators(filePath), file.errorString());
+ }
+ return false;
+ }
+
+ d->hostKeys.clear();
+ const QByteArray content = file.readAll().trimmed();
+ if (content.isEmpty())
+ return true;
+ foreach (const QByteArray &line, content.split('\n')) {
+ const QList<QByteArray> &lineData = line.trimmed().split(' ');
+ if (lineData.count() != 2) {
+ qDebug("Unexpected line \"%s\" in file \"%s\".", line.constData(),
+ qPrintable(filePath));
+ continue;
+ }
+ d->hostKeys.insert(QString::fromUtf8(lineData.first()),
+ QByteArray::fromHex(lineData.last()));
+ }
+
+ return true;
+}
+
+bool SshHostKeyDatabase::store(const QString &filePath, QString *error) const
+{
+ QFile file(filePath);
+ if (!file.open(QIODevice::WriteOnly)) {
+ if (error) {
+ *error = QCoreApplication::translate("QSsh::Ssh",
+ "Failed to open key file \"%1\" for writing: %2")
+ .arg(QDir::toNativeSeparators(filePath), file.errorString());
+ }
+ return false;
+ }
+
+ file.resize(0);
+ for (auto it = d->hostKeys.constBegin(); it != d->hostKeys.constEnd(); ++it)
+ file.write(it.key().toUtf8() + ' ' + it.value().toHex() + '\n');
+ return true;
+}
+
+SshHostKeyDatabase::KeyLookupResult SshHostKeyDatabase::matchHostKey(const QString &hostName,
+ const QByteArray &key) const
+{
+ auto it = d->hostKeys.find(hostName);
+ if (it == d->hostKeys.constEnd())
+ return KeyLookupNoMatch;
+ if (it.value() == key)
+ return KeyLookupMatch;
+ return KeyLookupMismatch;
+}
+
+void SshHostKeyDatabase::insertHostKey(const QString &hostName, const QByteArray &key)
+{
+ d->hostKeys.insert(hostName, key);
+}
+
+} // namespace QSsh
diff --git a/src/libs/ssh/sshhostkeydatabase.h b/src/libs/ssh/sshhostkeydatabase.h
new file mode 100644
index 00000000000..8e5195375a7
--- /dev/null
+++ b/src/libs/ssh/sshhostkeydatabase.h
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 SSHHOSTKEYDATABASE_H
+#define SSHHOSTKEYDATABASE_H
+
+#include "ssh_global.h"
+
+#include <QSharedPointer>
+
+QT_BEGIN_NAMESPACE
+class QByteArray;
+class QString;
+QT_END_NAMESPACE
+
+namespace QSsh {
+class SshHostKeyDatabase;
+typedef QSharedPointer<SshHostKeyDatabase> SshHostKeyDatabasePtr;
+
+class QSSH_EXPORT SshHostKeyDatabase
+{
+ friend class QSharedPointer<SshHostKeyDatabase>; // To give create() access to our constructor.
+
+public:
+ enum KeyLookupResult {
+ KeyLookupMatch,
+ KeyLookupNoMatch,
+ KeyLookupMismatch
+ };
+
+ ~SshHostKeyDatabase();
+
+ bool load(const QString &filePath, QString *error = 0);
+ bool store(const QString &filePath, QString *error = 0) const;
+ KeyLookupResult matchHostKey(const QString &hostName, const QByteArray &key) const;
+ void insertHostKey(const QString &hostName, const QByteArray &key);
+
+private:
+ SshHostKeyDatabase();
+
+ class SshHostKeyDatabasePrivate;
+ SshHostKeyDatabasePrivate * const d;
+};
+
+} // namespace QSsh
+
+#endif // Include guard.
diff --git a/src/libs/ssh/sshincomingpacket.cpp b/src/libs/ssh/sshincomingpacket.cpp
index bd3835f21c9..bf2d220bb55 100644
--- a/src/libs/ssh/sshincomingpacket.cpp
+++ b/src/libs/ssh/sshincomingpacket.cpp
@@ -161,7 +161,7 @@ SshKeyExchangeInit SshIncomingPacket::extractKeyExchangeInitData() const
= SshPacketParser::asNameList(m_data, &offset);
exchangeData.firstKexPacketFollows
= SshPacketParser::asBool(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_KEY_EXCHANGE_FAILED,
"Key exchange failed: Server sent invalid SSH_MSG_KEXINIT packet.");
}
@@ -200,7 +200,7 @@ SshKeyExchangeReply SshIncomingPacket::extractKeyExchangeReply(const QByteArray
throw SshPacketParseException();
replyData.signatureBlob = SshPacketParser::asString(m_data, &offset);
return replyData;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_KEY_EXCHANGE_FAILED,
"Key exchange failed: "
"Server sent invalid SSH_MSG_KEXDH_REPLY packet.");
@@ -218,7 +218,7 @@ SshDisconnect SshIncomingPacket::extractDisconnect() const
msg.reasonCode = SshPacketParser::asUint32(m_data, &offset);
msg.description = SshPacketParser::asUserString(m_data, &offset);
msg.language = SshPacketParser::asString(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_DISCONNECT.");
}
@@ -237,7 +237,7 @@ SshUserAuthBanner SshIncomingPacket::extractUserAuthBanner() const
msg.message = SshPacketParser::asUserString(m_data, &offset);
msg.language = SshPacketParser::asString(m_data, &offset);
return msg;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_USERAUTH_BANNER.");
}
@@ -262,7 +262,7 @@ SshUserAuthInfoRequestPacket SshIncomingPacket::extractUserAuthInfoRequest() con
msg.echos << SshPacketParser::asBool(m_data, &offset);
}
return msg;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_USERAUTH_INFO_REQUEST.");
}
@@ -280,7 +280,7 @@ SshDebug SshIncomingPacket::extractDebug() const
msg.message = SshPacketParser::asUserString(m_data, &offset);
msg.language = SshPacketParser::asString(m_data, &offset);
return msg;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_DEBUG.");
}
@@ -296,7 +296,7 @@ SshUnimplemented SshIncomingPacket::extractUnimplemented() const
quint32 offset = TypeOffset + 1;
msg.invalidMsgSeqNr = SshPacketParser::asUint32(m_data, &offset);
return msg;
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_UNIMPLEMENTED.");
}
@@ -314,7 +314,7 @@ SshChannelOpenFailure SshIncomingPacket::extractChannelOpenFailure() const
openFailure.reasonCode = SshPacketParser::asUint32(m_data, &offset);
openFailure.reasonString = QString::fromLocal8Bit(SshPacketParser::asString(m_data, &offset));
openFailure.language = SshPacketParser::asString(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Server sent invalid SSH_MSG_CHANNEL_OPEN_FAILURE packet.");
}
@@ -333,7 +333,7 @@ SshChannelOpenConfirmation SshIncomingPacket::extractChannelOpenConfirmation() c
confirmation.remoteChannel = SshPacketParser::asUint32(m_data, &offset);
confirmation.remoteWindowSize = SshPacketParser::asUint32(m_data, &offset);
confirmation.remoteMaxPacketSize = SshPacketParser::asUint32(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Server sent invalid SSH_MSG_CHANNEL_OPEN_CONFIRMATION packet.");
}
@@ -350,7 +350,7 @@ SshChannelWindowAdjust SshIncomingPacket::extractWindowAdjust() const
quint32 offset = TypeOffset + 1;
adjust.localChannel = SshPacketParser::asUint32(m_data, &offset);
adjust.bytesToAdd = SshPacketParser::asUint32(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_CHANNEL_WINDOW_ADJUST packet.");
}
@@ -367,7 +367,7 @@ SshChannelData SshIncomingPacket::extractChannelData() const
quint32 offset = TypeOffset + 1;
data.localChannel = SshPacketParser::asUint32(m_data, &offset);
data.data = SshPacketParser::asString(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_CHANNEL_DATA packet.");
}
@@ -385,7 +385,7 @@ SshChannelExtendedData SshIncomingPacket::extractChannelExtendedData() const
data.localChannel = SshPacketParser::asUint32(m_data, &offset);
data.type = SshPacketParser::asUint32(m_data, &offset);
data.data = SshPacketParser::asString(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_CHANNEL_EXTENDED_DATA packet.");
}
@@ -407,7 +407,7 @@ SshChannelExitStatus SshIncomingPacket::extractChannelExitStatus() const
if (SshPacketParser::asBool(m_data, &offset))
throw SshPacketParseException();
exitStatus.exitStatus = SshPacketParser::asUint32(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid exit-status packet.");
}
@@ -432,7 +432,7 @@ SshChannelExitSignal SshIncomingPacket::extractChannelExitSignal() const
exitSignal.coreDumped = SshPacketParser::asBool(m_data, &offset);
exitSignal.error = SshPacketParser::asUserString(m_data, &offset);
exitSignal.language = SshPacketParser::asString(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid exit-signal packet.");
}
@@ -446,7 +446,7 @@ quint32 SshIncomingPacket::extractRecipientChannel() const
try {
quint32 offset = TypeOffset + 1;
return SshPacketParser::asUint32(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Server sent invalid packet.");
}
@@ -461,7 +461,7 @@ QByteArray SshIncomingPacket::extractChannelRequestType() const
quint32 offset = TypeOffset + 1;
SshPacketParser::asUint32(m_data, &offset);
return SshPacketParser::asString(m_data, &offset);
- } catch (SshPacketParseException &) {
+ } catch (const SshPacketParseException &) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Invalid SSH_MSG_CHANNEL_REQUEST packet.");
}
diff --git a/src/libs/ssh/sshkeycreationdialog.cpp b/src/libs/ssh/sshkeycreationdialog.cpp
index d9c3f37a78c..80118cde5ac 100644
--- a/src/libs/ssh/sshkeycreationdialog.cpp
+++ b/src/libs/ssh/sshkeycreationdialog.cpp
@@ -56,10 +56,14 @@ SshKeyCreationDialog::SshKeyCreationDialog(QWidget *parent)
+ QLatin1String("/.ssh/qtc_id");
setPrivateKeyFile(defaultPath);
- connect(m_ui->rsa, SIGNAL(toggled(bool)), this, SLOT(keyTypeChanged()));
- connect(m_ui->dsa, SIGNAL(toggled(bool)), this, SLOT(keyTypeChanged()));
- connect(m_ui->privateKeyFileButton, SIGNAL(clicked()), SLOT(handleBrowseButtonClicked()));
- connect(m_ui->generateButton, SIGNAL(clicked()), this, SLOT(generateKeys()));
+ connect(m_ui->rsa, &QRadioButton::toggled,
+ this, &SshKeyCreationDialog::keyTypeChanged);
+ connect(m_ui->dsa, &QRadioButton::toggled,
+ this, &SshKeyCreationDialog::keyTypeChanged);
+ connect(m_ui->privateKeyFileButton, &QPushButton::clicked,
+ this, &SshKeyCreationDialog::handleBrowseButtonClicked);
+ connect(m_ui->generateButton, &QPushButton::clicked,
+ this, &SshKeyCreationDialog::generateKeys);
}
SshKeyCreationDialog::~SshKeyCreationDialog()
diff --git a/src/libs/ssh/sshkeyexchange.cpp b/src/libs/ssh/sshkeyexchange.cpp
index 413f1be5cb8..12c26076482 100644
--- a/src/libs/ssh/sshkeyexchange.cpp
+++ b/src/libs/ssh/sshkeyexchange.cpp
@@ -76,8 +76,9 @@ namespace {
} // anonymous namespace
-SshKeyExchange::SshKeyExchange(SshSendFacility &sendFacility)
- : m_sendFacility(sendFacility)
+SshKeyExchange::SshKeyExchange(const SshConnectionParameters &connParams,
+ SshSendFacility &sendFacility)
+ : m_connParams(connParams), m_sendFacility(sendFacility)
{
}
@@ -210,8 +211,46 @@ void SshKeyExchange::sendNewKeysPacket(const SshIncomingPacket &dhReply,
"Invalid signature in SSH_MSG_KEXDH_REPLY packet.");
}
+ checkHostKey(reply.k_s);
+
m_sendFacility.sendNewKeysPacket();
}
+void SshKeyExchange::checkHostKey(const QByteArray &hostKey)
+{
+ if (m_connParams.hostKeyCheckingMode == SshHostKeyCheckingNone) {
+ if (m_connParams.hostKeyDatabase)
+ m_connParams.hostKeyDatabase->insertHostKey(m_connParams.host, hostKey);
+ return;
+ }
+
+ if (!m_connParams.hostKeyDatabase) {
+ throw SshClientException(SshInternalError,
+ SSH_TR("Host key database must exist "
+ "if host key checking is enabled."));
+ }
+
+ switch (m_connParams.hostKeyDatabase->matchHostKey(m_connParams.host, hostKey)) {
+ case SshHostKeyDatabase::KeyLookupMatch:
+ return; // Nothing to do.
+ case SshHostKeyDatabase::KeyLookupMismatch:
+ if (m_connParams.hostKeyCheckingMode != SshHostKeyCheckingAllowMismatch)
+ throwHostKeyException();
+ break;
+ case SshHostKeyDatabase::KeyLookupNoMatch:
+ if (m_connParams.hostKeyCheckingMode == SshHostKeyCheckingStrict)
+ throwHostKeyException();
+ break;
+ }
+ m_connParams.hostKeyDatabase->insertHostKey(m_connParams.host, hostKey);
+}
+
+void SshKeyExchange::throwHostKeyException()
+{
+ throw SshServerException(SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE, "Host key changed",
+ SSH_TR("Host key of machine \"%1\" has changed.")
+ .arg(m_connParams.host));
+}
+
} // namespace Internal
} // namespace QSsh
diff --git a/src/libs/ssh/sshkeyexchange_p.h b/src/libs/ssh/sshkeyexchange_p.h
index 5be771b2913..ae149cc982f 100644
--- a/src/libs/ssh/sshkeyexchange_p.h
+++ b/src/libs/ssh/sshkeyexchange_p.h
@@ -31,6 +31,8 @@
#ifndef SSHKEYEXCHANGE_P_H
#define SSHKEYEXCHANGE_P_H
+#include "sshconnection.h"
+
#include <QByteArray>
#include <QScopedPointer>
@@ -48,7 +50,7 @@ class SshIncomingPacket;
class SshKeyExchange
{
public:
- SshKeyExchange(SshSendFacility &sendFacility);
+ SshKeyExchange(const SshConnectionParameters &connParams, SshSendFacility &sendFacility);
~SshKeyExchange();
void sendKexInitPacket(const QByteArray &serverId);
@@ -68,6 +70,9 @@ public:
QByteArray hMacAlgoServerToClient() const { return m_s2cHMacAlgo; }
private:
+ void checkHostKey(const QByteArray &hostKey);
+ Q_NORETURN void throwHostKeyException();
+
QByteArray m_serverId;
QByteArray m_clientKexInitPayload;
QByteArray m_serverKexInitPayload;
@@ -80,6 +85,7 @@ private:
QByteArray m_c2sHMacAlgo;
QByteArray m_s2cHMacAlgo;
QScopedPointer<Botan::HashFunction> m_hash;
+ const SshConnectionParameters m_connParams;
SshSendFacility &m_sendFacility;
};
diff --git a/src/libs/ssh/sshkeygenerator.cpp b/src/libs/ssh/sshkeygenerator.cpp
index 6884db95844..d70819e97e4 100644
--- a/src/libs/ssh/sshkeygenerator.cpp
+++ b/src/libs/ssh/sshkeygenerator.cpp
@@ -78,20 +78,20 @@ bool SshKeyGenerator::generateKeys(KeyType type, PrivateKeyFormat format, int ke
generateOpenSslPublicKeyString(key);
}
return true;
- } catch (Botan::Exception &e) {
+ } catch (const Exception &e) {
m_error = tr("Error generating key: %1").arg(QString::fromLatin1(e.what()));
return false;
}
}
-void SshKeyGenerator::generatePkcs8KeyStrings(const KeyPtr &key, Botan::RandomNumberGenerator &rng)
+void SshKeyGenerator::generatePkcs8KeyStrings(const KeyPtr &key, RandomNumberGenerator &rng)
{
generatePkcs8KeyString(key, false, rng);
generatePkcs8KeyString(key, true, rng);
}
void SshKeyGenerator::generatePkcs8KeyString(const KeyPtr &key, bool privateKey,
- Botan::RandomNumberGenerator &rng)
+ RandomNumberGenerator &rng)
{
Pipe pipe;
pipe.start_msg();
diff --git a/src/libs/ssh/sshremoteprocess.cpp b/src/libs/ssh/sshremoteprocess.cpp
index 47a40afe90f..c5894e62b57 100644
--- a/src/libs/ssh/sshremoteprocess.cpp
+++ b/src/libs/ssh/sshremoteprocess.cpp
@@ -160,15 +160,18 @@ void SshRemoteProcess::setReadChannel(QProcess::ProcessChannel channel)
void SshRemoteProcess::init()
{
- connect(d, SIGNAL(started()), this, SIGNAL(started()),
- Qt::QueuedConnection);
- connect(d, SIGNAL(readyReadStandardOutput()), this, SIGNAL(readyReadStandardOutput()),
- Qt::QueuedConnection);
- connect(d, SIGNAL(readyRead()), this, SIGNAL(readyRead()), Qt::QueuedConnection);
- connect(d, SIGNAL(readyReadStandardError()), this,
- SIGNAL(readyReadStandardError()), Qt::QueuedConnection);
- connect(d, SIGNAL(closed(int)), this, SIGNAL(closed(int)), Qt::QueuedConnection);
- connect(d, SIGNAL(eof()), SIGNAL(readChannelFinished()), Qt::QueuedConnection);
+ connect(d, &Internal::SshRemoteProcessPrivate::started,
+ this, &SshRemoteProcess::started, Qt::QueuedConnection);
+ connect(d, &Internal::SshRemoteProcessPrivate::readyReadStandardOutput,
+ this, &SshRemoteProcess::readyReadStandardOutput, Qt::QueuedConnection);
+ connect(d, &Internal::SshRemoteProcessPrivate::readyRead,
+ this, &SshRemoteProcess::readyRead, Qt::QueuedConnection);
+ connect(d, &Internal::SshRemoteProcessPrivate::readyReadStandardError,
+ this, &SshRemoteProcess::readyReadStandardError, Qt::QueuedConnection);
+ connect(d, &Internal::SshRemoteProcessPrivate::closed,
+ this, &SshRemoteProcess::closed, Qt::QueuedConnection);
+ connect(d, &Internal::SshRemoteProcessPrivate::eof,
+ this, &SshRemoteProcess::readChannelFinished, Qt::QueuedConnection);
}
void SshRemoteProcess::addToEnvironment(const QByteArray &var, const QByteArray &value)
@@ -212,7 +215,7 @@ void SshRemoteProcess::sendSignal(Signal signal)
QSSH_ASSERT_AND_RETURN(signalString);
d->m_sendFacility.sendChannelSignalPacket(d->remoteChannel(), signalString);
}
- } catch (Botan::Exception &e) {
+ } catch (const Botan::Exception &e) {
setErrorString(QString::fromLatin1(e.what()));
d->closeChannel();
}
@@ -306,7 +309,7 @@ void SshRemoteProcessPrivate::handleOpenSuccessInternal()
else
m_sendFacility.sendExecPacket(remoteChannel(), m_command);
setProcState(ExecRequested);
- m_timeoutTimer->start(ReplyTimeout);
+ m_timeoutTimer.start(ReplyTimeout);
}
void SshRemoteProcessPrivate::handleOpenFailureInternal(const QString &reason)
@@ -321,7 +324,7 @@ void SshRemoteProcessPrivate::handleChannelSuccess()
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_SUCCESS message.");
}
- m_timeoutTimer->stop();
+ m_timeoutTimer.stop();
setProcState(Running);
}
@@ -331,7 +334,7 @@ void SshRemoteProcessPrivate::handleChannelFailure()
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
"Unexpected SSH_MSG_CHANNEL_FAILURE message.");
}
- m_timeoutTimer->stop();
+ m_timeoutTimer.stop();
setProcState(StartFailed);
closeChannel();
}
diff --git a/src/libs/ssh/sshremoteprocessrunner.cpp b/src/libs/ssh/sshremoteprocessrunner.cpp
index 4db53fa773b..d48eb67adbe 100644
--- a/src/libs/ssh/sshremoteprocessrunner.cpp
+++ b/src/libs/ssh/sshremoteprocessrunner.cpp
@@ -113,13 +113,14 @@ void SshRemoteProcessRunner::runInternal(const QByteArray &command,
d->m_exitCode = -1;
d->m_command = command;
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()));
+ connect(d->m_connection, &SshConnection::error,
+ this, &SshRemoteProcessRunner::handleConnectionError);
+ connect(d->m_connection, &SshConnection::disconnected,
+ this, &SshRemoteProcessRunner::handleDisconnected);
if (d->m_connection->state() == SshConnection::Connected) {
handleConnected();
} else {
- connect(d->m_connection, SIGNAL(connected()), SLOT(handleConnected()));
+ connect(d->m_connection, &SshConnection::connected, this, &SshRemoteProcessRunner::handleConnected);
if (d->m_connection->state() == SshConnection::Unconnected)
d->m_connection->connectToHost();
}
diff --git a/src/libs/timeline/README b/src/libs/timeline/README
new file mode 100644
index 00000000000..bc5b4331765
--- /dev/null
+++ b/src/libs/timeline/README
@@ -0,0 +1,34 @@
+
+The timeline library can be used to display timeline data, primarily for performance analysis. It
+provides a comprehensive set of visual components as well as a set of models that can be extended to
+hold custom timeline data. You can use all the provided QML to get a complete GUI similar to the QML
+profiler or you can mix and match the QML components with your own.
+
+Models
+------
+
+At the core of the timeline library is the TimelineModel. You can create multiple TimelineModels to
+represent different categories of data. The TimelineModelAggregator class is then used to manage
+those models. TimelineModels are expected to load their contents all at once and then only change if
+you clear() and possibly reload them. To complement that, you can use the TimelineNotesModel. The
+TimelineNotesModel is designed to hold less, but mutable, data that spans all TimelineModels in a
+TimelineModelAggregator.
+
+Views
+-----
+
+Expose the TimelineRenderer class to QML and add a TimelineModel to it to get a visualization of the
+data in the model. TimelineRenderer will generally use the TimelineRenderPasses the TimelineModel
+suggests. It contains a caching system for keeping different versions of the visualization,
+depending on position and zoom level, so that the picture always stays sharp and numerical overflows
+are avoided. To do that it needs a TimelineZoomControl which manages zooming and scrolling.
+
+A simplified display for the contents of a TimelineModel, based on the same render passes as the
+TimelineRenderer, can be found in TimelineOverviewRenderer. TimelineOverviewRenderer will squeeze
+the data into a fixed height and only allow all the data to be displayed at once. It won't react to
+zooming or scrolling and can easily be used for a more concise overview.
+
+Various utilities are provided in the QML code. CategoryLabels can be used to provide a legend for
+data rendered using a TimelineRenderer. TimeMarks provides colored bars that can be layered behind
+a TimelineRenderer to make the rows easier to distinguish. TimeDisplay provides a legend for the
+time spanned by a timeline.
diff --git a/src/plugins/qmlprofiler/qml/ButtonsBar.qml b/src/libs/timeline/qml/ButtonsBar.qml
index 0a7f03b368d..4f31c15d380 100644
--- a/src/plugins/qmlprofiler/qml/ButtonsBar.qml
+++ b/src/libs/timeline/qml/ButtonsBar.qml
@@ -84,7 +84,7 @@ ToolBar {
anchors.bottom: parent.bottom
implicitWidth: buttonWidth
- iconSource: "qrc:/qmlprofiler/ico_prev.png"
+ iconSource: "qrc:/timeline/ico_prev.png"
tooltip: qsTr("Jump to previous event.")
onClicked: buttons.jumpToPrev()
}
@@ -95,7 +95,7 @@ ToolBar {
anchors.bottom: parent.bottom
implicitWidth: buttonWidth
- iconSource: "qrc:/qmlprofiler/ico_next.png"
+ iconSource: "qrc:/timeline/ico_next.png"
tooltip: qsTr("Jump to next event.")
onClicked: buttons.jumpToNext()
}
@@ -106,7 +106,7 @@ ToolBar {
anchors.bottom: parent.bottom
implicitWidth: buttonWidth
- iconSource: "qrc:/qmlprofiler/ico_zoom.png"
+ iconSource: "qrc:/timeline/ico_zoom.png"
tooltip: qsTr("Show zoom slider.")
checkable: true
checked: false
@@ -119,7 +119,7 @@ ToolBar {
anchors.bottom: parent.bottom
implicitWidth: buttonWidth
- iconSource: "qrc:/qmlprofiler/ico_filter.png"
+ iconSource: "qrc:/timeline/ico_filter.png"
tooltip: qsTr("Filter Categories")
checkable: true
onCheckedChanged: buttons.filterMenuChanged()
@@ -131,8 +131,8 @@ ToolBar {
anchors.bottom: parent.bottom
implicitWidth: buttonWidth
- iconSource: checked ? "qrc:/qmlprofiler/ico_rangeselected.png" :
- "qrc:/qmlprofiler/ico_rangeselection.png"
+ iconSource: checked ? "qrc:/timeline/ico_rangeselected.png" :
+ "qrc:/timeline/ico_rangeselection.png"
tooltip: qsTr("Select range.")
checkable: true
checked: false
@@ -145,7 +145,7 @@ ToolBar {
anchors.bottom: parent.bottom
implicitWidth: buttonWidth
- iconSource: "qrc:/qmlprofiler/ico_selectionmode.png"
+ iconSource: "qrc:/timeline/ico_selectionmode.png"
tooltip: qsTr("View event information on mouseover.")
checkable: true
checked: false
diff --git a/src/libs/timeline/qml/CategoryLabel.qml b/src/libs/timeline/qml/CategoryLabel.qml
new file mode 100644
index 00000000000..3f474b4e7da
--- /dev/null
+++ b/src/libs/timeline/qml/CategoryLabel.qml
@@ -0,0 +1,245 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.1
+import QtQuick.Controls 1.2
+import QtQuick.Controls.Styles 1.2
+
+Item {
+ id: labelContainer
+
+ property QtObject model
+ property QtObject notesModel
+ property string text: model ? model.displayName : ""
+ property bool expanded: model && model.expanded
+ property var labels: model ? model.labels : []
+
+ property bool dragging
+ property int visualIndex
+ property int dragOffset
+ property Item draggerParent
+
+ signal dragStarted;
+ signal dragStopped;
+ signal dropped(int sourceIndex, int targetIndex)
+
+ signal selectById(int eventId)
+ signal selectNextBySelectionId(int selectionId)
+ signal selectPrevBySelectionId(int selectionId)
+
+ property bool reverseSelect: false
+
+ MouseArea {
+ id: dragArea
+ anchors.fill: txt
+ drag.target: dragger
+ cursorShape: dragging ? Qt.ClosedHandCursor : Qt.OpenHandCursor
+ drag.minimumY: dragging ? 0 : -dragOffset // Account for parent change below
+ drag.maximumY: draggerParent.height - (dragging ? 0 : dragOffset)
+ }
+
+ DropArea {
+ id: dropArea
+
+ onPositionChanged: {
+ var sourceIndex = drag.source.visualIndex;
+ if (drag.source.y === 0) {
+ // special case for first position: Always swap, no matter if upper border touched.
+ if (sourceIndex > visualIndex)
+ labelContainer.dropped(sourceIndex, visualIndex);
+ } else if (sourceIndex !== visualIndex && sourceIndex !== visualIndex + 1) {
+ labelContainer.dropped(sourceIndex, sourceIndex > visualIndex ? visualIndex + 1 :
+ visualIndex);
+ }
+ }
+
+ anchors.fill: parent
+ }
+
+ Text {
+ id: txt
+ x: 5
+ font.pixelSize: 12
+ text: labelContainer.text
+ color: "#232323"
+ height: model ? model.defaultRowHeight : 0
+ width: 140
+ verticalAlignment: Text.AlignVCenter
+ renderType: Text.NativeRendering
+ elide: Text.ElideRight
+ }
+
+ Column {
+ id: column
+ property QtObject parentModel: model
+ anchors.top: txt.bottom
+ visible: expanded
+ Repeater {
+ model: labels.length
+ SynchronousReloader {
+ id: loader
+ asynchronous: dragOffset - draggerParent.contentY + y + txt.height >
+ draggerParent.height
+
+ active: expanded
+ width: labelContainer.width
+ height: column.parentModel ? column.parentModel.rowHeight(index + 1) : 0
+
+ sourceComponent: RowLabel {
+ label: labels[index];
+ onSelectBySelectionId: {
+ if (labelContainer.reverseSelect) {
+ labelContainer.selectPrevBySelectionId(label.id);
+ } else {
+ labelContainer.selectNextBySelectionId(label.id);
+ }
+ }
+ onSetRowHeight: {
+ column.parentModel.setExpandedRowHeight(index + 1, newHeight);
+ loader.height = column.parentModel.rowHeight(index + 1);
+ }
+ }
+ }
+ }
+ }
+
+ ToolButton {
+ id: notesButton
+ anchors.verticalCenter: txt.verticalCenter
+ anchors.right: expandButton.left
+ implicitWidth: 17
+ implicitHeight: txt.height - 1
+ property var eventIds: []
+ property var texts: []
+ property int currentNote: -1
+ Connections {
+ target: notesModel
+ onChanged: {
+ // This will only be called if notesModel != null.
+ if (arguments[1] === -1 || arguments[1] === model.modelId) {
+ var notes = notesModel.byTimelineModel(model.modelId);
+ var newTexts = [];
+ var newEventIds = [];
+ for (var i in notes) {
+ newTexts.push(notesModel.text(notes[i]))
+ newEventIds.push(notesModel.timelineIndex(notes[i]));
+ }
+
+ // Bindings are only triggered when assigning the whole array.
+ notesButton.eventIds = newEventIds;
+ notesButton.texts = newTexts;
+ }
+ }
+ }
+
+ visible: eventIds.length > 0
+ iconSource: "ico_note.png"
+ tooltip: texts.join("\n");
+ onClicked: {
+ if (++currentNote >= eventIds.length)
+ currentNote = 0;
+ labelContainer.selectById(eventIds[currentNote]);
+ }
+ }
+
+ ToolButton {
+ id: expandButton
+ anchors.verticalCenter: txt.verticalCenter
+ anchors.right: parent.right
+ implicitWidth: 17
+ implicitHeight: txt.height - 1
+ enabled: expanded || (model && !model.empty)
+ iconSource: expanded ? "arrow_down.png" : "arrow_right.png"
+ tooltip: expanded ? qsTr("Collapse category") : qsTr("Expand category")
+ onClicked: model.expanded = !expanded
+ }
+
+ Rectangle {
+ id: dragger
+ property int visualIndex: labelContainer.visualIndex
+ width: labelContainer.width
+ height: 0
+ color: "black"
+ opacity: 0.5
+ anchors.left: parent.left
+
+ // anchor to top so that it reliably snaps back after dragging
+ anchors.top: parent.top
+
+ Drag.active: dragArea.drag.active
+ Drag.onActiveChanged: {
+ // We don't want height or text to be changed when reordering occurs, so we don't make
+ // them properties.
+ draggerText.text = txt.text;
+ if (Drag.active) {
+ height = labelContainer.height;
+ labelContainer.dragStarted();
+ } else {
+ height = 0;
+ labelContainer.dragStopped();
+ }
+ }
+
+ states: [
+ State {
+ when: dragger.Drag.active
+ ParentChange {
+ target: dragger
+ parent: draggerParent
+ }
+ PropertyChanges {
+ target: dragger
+ anchors.top: undefined
+ }
+ }
+ ]
+
+ Text {
+ id: draggerText
+ visible: parent.Drag.active
+ x: txt.x
+ font.pixelSize: txt.font.pixelSize
+ color: "white"
+ width: txt.width
+ height: txt.height
+ verticalAlignment: txt.verticalAlignment
+ renderType: txt.renderType
+ }
+ }
+
+ MouseArea {
+ anchors.top: dragArea.bottom
+ anchors.bottom: labelContainer.dragging ? labelContainer.bottom : dragArea.bottom
+ anchors.left: labelContainer.left
+ anchors.right: labelContainer.right
+ cursorShape: dragArea.cursorShape
+ }
+
+}
diff --git a/src/plugins/qmlprofiler/qml/Detail.qml b/src/libs/timeline/qml/Detail.qml
index 83bd262ba0c..83bd262ba0c 100644
--- a/src/plugins/qmlprofiler/qml/Detail.qml
+++ b/src/libs/timeline/qml/Detail.qml
diff --git a/src/libs/timeline/qml/MainView.qml b/src/libs/timeline/qml/MainView.qml
new file mode 100644
index 00000000000..6b3e171e356
--- /dev/null
+++ b/src/libs/timeline/qml/MainView.qml
@@ -0,0 +1,472 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.1
+import QtQuick.Controls 1.0
+
+Rectangle {
+ id: root
+
+ // ***** properties
+
+ property bool lockItemSelection : false
+
+ signal updateCursorPosition
+ property string fileName: ""
+ property int lineNumber: -1
+ property int columnNumber: 0
+ property int selectedModel: -1
+ property int selectedItem: -1
+
+ property bool selectionRangeMode: false
+ property bool selectionRangeReady: selectionRange.ready
+ property real selectionRangeStart: selectionRange.startTime
+ property real selectionRangeEnd: selectionRange.startTime + selectionRange.duration
+ property int typeId: content.typeId
+
+ onTypeIdChanged: updateCursorPosition()
+
+ color: "#dcdcdc"
+
+ // ***** connections with external objects
+ Connections {
+ target: zoomControl
+ onRangeChanged: {
+ zoomSliderToolBar.updateZoomLevel();
+ content.scroll();
+
+ // If you select something in the main view and then resize the current range by some
+ // other means, the selection should stay where it was.
+ var oldTimePerPixel = selectionRange.viewTimePerPixel;
+ selectionRange.viewTimePerPixel = zoomControl.rangeDuration / content.width;
+ if (selectionRange.creationState === selectionRange.creationFinished &&
+ oldTimePerPixel != selectionRange.viewTimePerPixel) {
+ var newWidth = selectionRange.rangeWidth * oldTimePerPixel /
+ selectionRange.viewTimePerPixel;
+ selectionRange.rangeLeft = selectionRange.rangeLeft * oldTimePerPixel /
+ selectionRange.viewTimePerPixel;
+ selectionRange.rangeRight = selectionRange.rangeLeft + newWidth;
+ }
+ }
+ onWindowChanged: {
+ content.scroll();
+ }
+ }
+
+
+ Connections {
+ target: timelineModelAggregator
+ onDataAvailable: {
+ content.clearChildren();
+ zoomControl.setRange(zoomControl.traceStart,
+ zoomControl.traceStart + zoomControl.traceDuration / 10);
+ }
+ }
+
+ onSelectionRangeModeChanged: {
+ selectionRange.reset();
+ buttonsBar.updateRangeButton(selectionRangeMode);
+ }
+
+ // ***** functions
+ function clear() {
+ content.clearChildren();
+ rangeDetails.hide();
+ selectionRangeMode = false;
+ zoomSlider.externalUpdate = true;
+ zoomSlider.value = zoomSlider.minimumValue;
+ }
+
+ function enableButtonsBar(enable) {
+ buttonsBar.enabled = enable;
+ }
+
+ function selectByTypeId(typeId)
+ {
+ if (lockItemSelection || typeId === -1)
+ return;
+
+ var itemIndex = -1;
+ var modelIndex = -1;
+
+ var notesModel = timelineModelAggregator.notes;
+ var notes = notesModel ? notesModel.byTypeId(typeId) : [];
+ if (notes.length !== 0) {
+ itemIndex = notesModel.timelineIndex(notes[0]);
+ var modelId = notesModel.timelineModel(notes[0]);
+ for (modelIndex = 0; modelIndex < timelineModelAggregator.models.length;
+ ++modelIndex) {
+ if (timelineModelAggregator.models[modelIndex].modelId === modelId)
+ break;
+ }
+ } else {
+ for (modelIndex = 0; modelIndex < timelineModelAggregator.models.length; ++modelIndex) {
+ if (modelIndex === selectedModel && selectedItem !== -1 &&
+ typeId === timelineModelAggregator.models[modelIndex].typeId(selectedItem))
+ break;
+
+ if (!timelineModelAggregator.models[modelIndex].handlesTypeId(typeId))
+ continue;
+
+ itemIndex = timelineModelAggregator.models[modelIndex].nextItemByTypeId(typeId,
+ zoomControl.rangeStart, selectedItem);
+ if (itemIndex !== -1)
+ break;
+ }
+ }
+
+ if (modelIndex !== -1 && modelIndex < timelineModelAggregator.models.length &&
+ itemIndex !== -1) {
+ // select an item, lock to it, and recenter if necessary
+ content.select(modelIndex, itemIndex);
+ content.selectionLocked = true;
+ }
+ }
+
+ focus: true
+ property bool shiftPressed: false;
+ Keys.onPressed: shiftPressed = (event.key === Qt.Key_Shift);
+ Keys.onReleased: shiftPressed = false;
+
+ TimelineLabels {
+ id: categories
+ anchors.top: buttonsBar.bottom
+ anchors.bottom: overview.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ contentY: content.contentY
+ selectedModel: root.selectedModel
+ selectedItem: root.selectedItem
+ color: root.color
+ modelProxy: timelineModelAggregator
+ zoomer: zoomControl
+ reverseSelect: shiftPressed
+
+ onMoveCategories: content.moveCategories(sourceIndex, targetIndex)
+ onSelectItem: content.select(modelIndex, eventIndex)
+ }
+
+ TimeDisplay {
+ id: timeDisplay
+ anchors.top: parent.top
+ anchors.left: buttonsBar.right
+ anchors.right: parent.right
+ anchors.bottom: overview.top
+ windowStart: zoomControl.windowStart
+ rangeDuration: Math.max(1, Math.round(zoomControl.rangeDuration))
+ contentX: content.contentX
+ clip: true
+ }
+
+ ButtonsBar {
+ id: buttonsBar
+ enabled: timelineModelAggregator.height > 0
+ anchors.top: parent.top
+ anchors.left: parent.left
+ width: 150
+ height: 24
+ onZoomControlChanged: zoomSliderToolBar.visible = !zoomSliderToolBar.visible
+ onFilterMenuChanged: filterMenu.visible = !filterMenu.visible
+ onJumpToNext: {
+ var next = timelineModelAggregator.nextItem(root.selectedModel, root.selectedItem,
+ zoomControl.rangeStart);
+ content.select(next.model, next.item);
+ }
+ onJumpToPrev: {
+ var prev = timelineModelAggregator.prevItem(root.selectedModel, root.selectedItem,
+ zoomControl.rangeEnd);
+ content.select(prev.model, prev.item);
+ }
+
+ onRangeSelectChanged: selectionRangeMode = rangeButtonChecked();
+ onLockChanged: content.selectionLocked = !lockButtonChecked();
+ }
+
+ TimelineContent {
+ id: content
+ anchors.left: buttonsBar.right
+ anchors.top: buttonsBar.bottom
+ anchors.bottom: overview.top
+ anchors.right: parent.right
+ selectionLocked: true
+ zoomer: zoomControl
+ modelProxy: timelineModelAggregator
+
+ onSelectionLockedChanged: {
+ buttonsBar.updateLockButton(selectionLocked);
+ }
+
+ onPropagateSelection: {
+ if (lockItemSelection || (newModel === selectedModel && newItem === selectedItem))
+ return;
+
+ lockItemSelection = true;
+ if (selectedModel !== -1 && selectedModel !== newModel)
+ select(selectedModel, -1);
+
+ selectedItem = newItem
+ selectedModel = newModel
+ if (selectedItem !== -1) {
+ // display details
+ rangeDetails.showInfo(selectedModel, selectedItem);
+
+ // update in other views
+ var model = timelineModelAggregator.models[selectedModel];
+ var eventLocation = model.location(selectedItem);
+ gotoSourceLocation(eventLocation.file, eventLocation.line,
+ eventLocation.column);
+ typeId = model.typeId(selectedItem);
+ } else {
+ rangeDetails.hide();
+ }
+ lockItemSelection = false;
+ }
+
+ onGotoSourceLocation: {
+ if (file !== undefined) {
+ root.fileName = file;
+ root.lineNumber = line;
+ root.columnNumber = column;
+ }
+ }
+ }
+
+ MouseArea {
+ id: selectionRangeControl
+ enabled: selectionRangeMode &&
+ selectionRange.creationState !== selectionRange.creationFinished
+ anchors.right: content.right
+ anchors.left: buttonsBar.right
+ anchors.top: content.top
+ anchors.bottom: content.bottom
+ hoverEnabled: enabled
+ z: 2
+
+ onReleased: {
+ if (selectionRange.creationState === selectionRange.creationSecondLimit) {
+ content.stayInteractive = true;
+ selectionRange.creationState = selectionRange.creationFinished;
+ }
+ }
+ onPressed: {
+ if (selectionRange.creationState === selectionRange.creationFirstLimit) {
+ content.stayInteractive = false;
+ selectionRange.setPos(selectionRangeControl.mouseX + content.contentX);
+ selectionRange.creationState = selectionRange.creationSecondLimit;
+ }
+ }
+ onPositionChanged: {
+ if (selectionRange.creationState === selectionRange.creationInactive)
+ selectionRange.creationState = selectionRange.creationFirstLimit;
+
+ if (selectionRangeControl.pressed ||
+ selectionRange.creationState !== selectionRange.creationFinished)
+ selectionRange.setPos(selectionRangeControl.mouseX + content.contentX);
+ }
+ onCanceled: pressed()
+ }
+
+ Flickable {
+ flickableDirection: Flickable.HorizontalFlick
+ clip: true
+ visible: selectionRangeMode &&
+ selectionRange.creationState !== selectionRange.creationInactive
+ interactive: false
+ x: content.x + content.flickableItem.x
+ y: content.y + content.flickableItem.y
+ height: content.flickableItem.height
+ width: content.flickableItem.width
+ contentX: content.contentX
+ contentWidth: content.contentWidth
+
+ SelectionRange {
+ id: selectionRange
+ zoomer: zoomControl
+ visible: parent.visible
+
+ onRangeDoubleClicked: {
+ zoomControl.setRange(startTime, endTime);
+ root.selectionRangeMode = false;
+ }
+
+ }
+ }
+
+ SelectionRangeDetails {
+ z: 1
+ x: 200
+ y: 125
+
+ id: selectionRangeDetails
+ visible: selectionRange.visible
+ startTime: selectionRange.startTime
+ duration: selectionRange.duration
+ endTime: selectionRange.endTime
+ showDuration: selectionRange.rangeWidth > 1
+
+ onRecenter: {
+ if ((selectionRange.startTime < zoomControl.rangeStart) ^
+ (selectionRange.endTime > zoomControl.rangeEnd)) {
+ var center = selectionRange.startTime + selectionRange.duration / 2;
+ var halfDuration = Math.max(selectionRange.duration, zoomControl.rangeDuration / 2);
+ zoomControl.setRange(center - halfDuration, center + halfDuration);
+ }
+ }
+
+ onClose: selectionRangeMode = false;
+ }
+
+ RangeDetails {
+ id: rangeDetails
+
+ z: 1
+ visible: false
+ x: 200
+ y: 25
+
+ locked: content.selectionLocked
+ models: timelineModelAggregator.models
+ notes: timelineModelAggregator.notes
+ onRecenterOnItem: {
+ content.gotoSourceLocation(file, line, column);
+ content.select(selectedModel, selectedItem)
+ }
+ onToggleSelectionLocked: {
+ content.selectionLocked = !content.selectionLocked;
+ }
+ onClearSelection: {
+ content.propagateSelection(-1, -1);
+ }
+ }
+
+ Rectangle {
+ anchors.left: buttonsBar.right
+ anchors.bottom: overview.top
+ anchors.top: parent.top
+ width: 1
+ color: "#B0B0B0"
+ }
+
+ Rectangle {
+ id: filterMenu
+ color: "#9b9b9b"
+ enabled: buttonsBar.enabled
+ visible: false
+ width: buttonsBar.width
+ anchors.left: parent.left
+ anchors.top: buttonsBar.bottom
+ height: timelineModelAggregator.models.length * buttonsBar.height
+
+ Repeater {
+ id: filterMenuInner
+ model: timelineModelAggregator.models
+ CheckBox {
+ anchors.left: filterMenu.left
+ anchors.right: filterMenu.right
+ height: buttonsBar.height
+ y: index * height
+ text: modelData.displayName
+ enabled: !modelData.empty
+ checked: enabled && !modelData.hidden
+ onCheckedChanged: modelData.hidden = !checked
+ }
+ }
+
+ }
+
+ Rectangle {
+ id: zoomSliderToolBar
+ objectName: "zoomSliderToolBar"
+ color: "#9b9b9b"
+ enabled: buttonsBar.enabled
+ visible: false
+ width: buttonsBar.width
+ height: buttonsBar.height
+ anchors.left: parent.left
+ anchors.top: buttonsBar.bottom
+
+ function updateZoomLevel() {
+ zoomSlider.externalUpdate = true;
+ zoomSlider.value = Math.pow(zoomControl.rangeDuration /
+ Math.max(1, zoomControl.windowDuration),
+ 1 / zoomSlider.exponent) * zoomSlider.maximumValue;
+ }
+
+ Slider {
+ id: zoomSlider
+ anchors.fill: parent
+ minimumValue: 1
+ maximumValue: 10000
+ stepSize: 100
+
+ property int exponent: 3
+ property bool externalUpdate: false
+ property int minWindowLength: 1e5 // 0.1 ms
+
+ onValueChanged: {
+ if (externalUpdate || zoomControl.windowEnd <= zoomControl.windowStart) {
+ // Zoom range is independently updated. We shouldn't mess
+ // with it here as otherwise we might introduce rounding
+ // or arithmetic errors.
+ externalUpdate = false;
+ return;
+ }
+
+ var windowLength = Math.max(
+ Math.pow(value / maximumValue, exponent) * zoomControl.windowDuration,
+ minWindowLength);
+
+ var fixedPoint = (zoomControl.rangeStart + zoomControl.rangeEnd) / 2;
+ if (root.selectedItem !== -1) {
+ // center on selected item if it's inside the current screen
+ var model = timelineModelAggregator.models[root.selectedModel]
+ var newFixedPoint = (model.startTime(root.selectedItem) +
+ model.endTime(root.selectedItem)) / 2;
+ if (newFixedPoint >= zoomControl.rangeStart &&
+ newFixedPoint < zoomControl.rangeEnd)
+ fixedPoint = newFixedPoint;
+ }
+
+ var startTime = Math.max(zoomControl.windowStart, fixedPoint - windowLength / 2)
+ zoomControl.setRange(startTime, startTime + windowLength);
+ }
+ }
+ }
+
+ Overview {
+ id: overview
+ height: 50
+ anchors.bottom: parent.bottom
+ anchors.right: parent.right
+ anchors.left: parent.left
+ modelProxy: timelineModelAggregator
+ zoomer: zoomControl
+ }
+}
diff --git a/src/libs/timeline/qml/Overview.qml b/src/libs/timeline/qml/Overview.qml
new file mode 100644
index 00000000000..f1cd43173aa
--- /dev/null
+++ b/src/libs/timeline/qml/Overview.qml
@@ -0,0 +1,197 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.1
+import TimelineOverviewRenderer 1.0
+
+Rectangle {
+ id: overview
+ objectName: "Overview"
+ color: parent.color
+
+ property QtObject modelProxy
+ property QtObject zoomer
+ property bool recursionGuard: false
+
+ function updateRange() {
+ if (recursionGuard)
+ return;
+ recursionGuard = true;
+ var newStartTime = rangeMover.rangeLeft * zoomer.traceDuration / width +
+ zoomer.traceStart;
+ var newEndTime = rangeMover.rangeRight * zoomer.traceDuration / width +
+ zoomer.traceStart;
+ if (isFinite(newStartTime) && isFinite(newEndTime) && newEndTime - newStartTime > 500)
+ zoomer.setRange(newStartTime, newEndTime);
+ recursionGuard = false;
+ }
+
+ Connections {
+ target: zoomer
+ onRangeChanged: {
+ if (recursionGuard)
+ return;
+ recursionGuard = true;
+ var newRangeX = (zoomer.rangeStart - zoomer.traceStart) * width /
+ zoomer.traceDuration;
+ var newWidth = zoomer.rangeDuration * width / zoomer.traceDuration;
+ var widthChanged = Math.abs(newWidth - rangeMover.rangeWidth) > 1;
+ var leftChanged = Math.abs(newRangeX - rangeMover.rangeLeft) > 1;
+ if (leftChanged)
+ rangeMover.rangeLeft = newRangeX;
+
+ if (leftChanged || widthChanged)
+ rangeMover.rangeRight = newRangeX + newWidth;
+ recursionGuard = false;
+ }
+ }
+
+ TimeDisplay {
+ id: timebar
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ textMargin: 2
+ bottomBorderHeight: 0
+ topBorderHeight: 1
+ height: 10
+ fontSize: 6
+ labelsHeight: 10
+ color1: "#cccccc"
+ color2: "#cccccc"
+ windowStart: zoomer.traceStart
+ alignedWindowStart: zoomer.traceStart
+ rangeDuration: zoomer.traceDuration
+ contentX: 0
+ offsetX: 0
+ }
+
+
+ Column {
+ anchors.top: timebar.bottom
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+
+ id: column
+
+ Repeater {
+ model: modelProxy.models
+ TimelineOverviewRenderer {
+ model: modelData
+ zoomer: overview.zoomer
+ notes: modelProxy.notes
+ width: column.width
+ height: column.height / modelProxy.models.length
+ }
+ }
+ }
+
+ Repeater {
+ id: noteSigns
+ property var modelsById: modelProxy.models.reduce(function(prev, model) {
+ prev[model.modelId] = model;
+ return prev;
+ }, {});
+
+ property int vertSpace: column.height / 7
+ property color noteColor: "orange"
+ readonly property double spacing: parent.width / zoomer.traceDuration
+
+ model: modelProxy.notes ? modelProxy.notes.count : 0
+ Item {
+ property int timelineIndex: modelProxy.notes.timelineIndex(index)
+ property int timelineModel: modelProxy.notes.timelineModel(index)
+ property double startTime: noteSigns.modelsById[timelineModel].startTime(timelineIndex)
+ property double endTime: noteSigns.modelsById[timelineModel].endTime(timelineIndex)
+ x: ((startTime + endTime) / 2 - zoomer.traceStart) * noteSigns.spacing
+ y: timebar.height + noteSigns.vertSpace
+ height: noteSigns.vertSpace * 5
+ width: 2
+ Rectangle {
+ color: noteSigns.noteColor
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: parent.top
+ height: noteSigns.vertSpace * 3
+ }
+
+ Rectangle {
+ color: noteSigns.noteColor
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.bottom: parent.bottom
+ height: noteSigns.vertSpace
+ }
+ }
+ }
+
+ // ***** child items
+ MouseArea {
+ anchors.fill: parent
+ function jumpTo(posX) {
+ var newX = posX - rangeMover.rangeWidth / 2;
+ if (newX < 0)
+ newX = 0;
+ if (newX + rangeMover.rangeWidth > overview.width)
+ newX = overview.width - rangeMover.rangeWidth;
+
+ if (newX < rangeMover.rangeLeft) {
+ // Changing left border will change width, so precompute right border here.
+ var right = newX + rangeMover.rangeWidth;
+ rangeMover.rangeLeft = newX;
+ rangeMover.rangeRight = right;
+ } else if (newX > rangeMover.rangeLeft) {
+ rangeMover.rangeRight = newX + rangeMover.rangeWidth;
+ rangeMover.rangeLeft = newX;
+ }
+ }
+
+ onPressed: {
+ jumpTo(mouse.x);
+ }
+ onPositionChanged: {
+ jumpTo(mouse.x);
+ }
+ }
+
+ RangeMover {
+ id: rangeMover
+ visible: modelProxy.height > 0
+ onRangeLeftChanged: overview.updateRange()
+ onRangeRightChanged: overview.updateRange()
+ }
+
+ Rectangle {
+ height: 1
+ width: parent.width
+ color: "#858585"
+ }
+}
diff --git a/src/plugins/qmlprofiler/qml/RangeDetails.qml b/src/libs/timeline/qml/RangeDetails.qml
index f1cab847e17..55d53c6de49 100644
--- a/src/plugins/qmlprofiler/qml/RangeDetails.qml
+++ b/src/libs/timeline/qml/RangeDetails.qml
@@ -29,7 +29,6 @@
****************************************************************************/
import QtQuick 2.1
-import Monitor 1.0
Item {
id: rangeDetails
@@ -45,14 +44,17 @@ Item {
property int selectedModel: -1
property int selectedItem: -1
- property bool locked: view.selectionLocked
+ property bool locked
+
+ property var models
+ property var notes
+
+ signal recenterOnItem
+ signal toggleSelectionLocked
+ signal clearSelection
width: col.width + 25
height: col.height + 30
- z: 1
- visible: false
- x: 200
- y: 25
function hide() {
noteEdit.focus = false;
@@ -67,9 +69,9 @@ Item {
isBindingLoop = false;
}
- // keep inside view
Connections {
- target: root
+ target: rangeDetails.parent
+ // keep inside view
onWidthChanged: fitInView();
onHeightChanged: fitInView();
}
@@ -84,7 +86,8 @@ Item {
selectedModel = model;
selectedItem = item;
- var eventData = qmlProfilerModelProxy.details(selectedModel, selectedItem)
+ var timelineModel = models[selectedModel];
+ var eventData = timelineModel.details(selectedItem)
eventInfo.clear();
for (var k in eventData) {
if (k === "displayName") {
@@ -96,7 +99,7 @@ Item {
}
rangeDetails.visible = true;
- var location = qmlProfilerModelProxy.location(selectedModel, selectedItem)
+ var location = timelineModel.location(selectedItem)
if (location.hasOwnProperty("file")) { // not empty
file = location.file;
line = location.line;
@@ -109,20 +112,21 @@ Item {
}
noteEdit.focus = false;
- noteEdit.text = qmlProfilerModelProxy.noteText(selectedModel, selectedItem);
+ var noteId = notes ? notes.get(timelineModel.modelId, selectedItem) : -1;
+ noteEdit.text = (noteId !== -1) ? notes.text(noteId) : "";
}
function fitInView() {
// don't reposition if it does not fit
- if (root.width < width || root.height < height)
+ if (parent.width < width || parent.height < height)
return;
- if (x + width > root.width)
- x = root.width - width;
+ if (x + width > parent.width)
+ x = parent.width - width;
if (x < 0)
x = 0;
- if (y + height > root.height)
- y = root.height - height;
+ if (y + height > parent.height)
+ y = parent.height - height;
if (y < 0)
y = 0;
}
@@ -214,7 +218,7 @@ Item {
anchors.bottomMargin: 5
anchors.top: col.bottom
- visible: text.length > 0 || focus
+ visible: notes && (text.length > 0 || focus)
width: col.width
wrapMode: Text.Wrap
color: "orange"
@@ -225,16 +229,16 @@ Item {
onFocusChanged: {
if (!focus && selectedModel != -1 && selectedItem != -1) {
saveTimer.stop();
- qmlProfilerModelProxy.setNoteText(selectedModel, selectedItem, text);
+ if (notes)
+ notes.setText(models[selectedModel].modelId, selectedItem, text);
}
}
Timer {
id: saveTimer
onTriggered: {
- if (selectedModel != -1 && selectedItem != -1)
- qmlProfilerModelProxy.setNoteText(selectedModel, selectedItem,
- noteEdit.text);
+ if (notes && selectedModel != -1 && selectedItem != -1)
+ notes.setText(models[selectedModel].modelId, selectedItem, noteEdit.text);
}
interval: 1000
}
@@ -245,13 +249,10 @@ Item {
anchors.fill: parent
drag.target: parent
drag.minimumX: 0
- drag.maximumX: root.width - parent.width
+ drag.maximumX: rangeDetails.parent.width - rangeDetails.width
drag.minimumY: 0
- drag.maximumY: root.height - parent.height
- onClicked: {
- root.gotoSourceLocation(file, line, column);
- root.recenterOnItem(view.selectedModel, view.selectedItem);
- }
+ drag.maximumY: rangeDetails.parent.height - rangeDetails.height
+ onClicked: rangeDetails.recenterOnItem()
}
Image {
@@ -260,6 +261,7 @@ Item {
anchors.top: closeIcon.top
anchors.right: lockIcon.left
anchors.rightMargin: 4
+ visible: notes
width: 8
height: 12
MouseArea {
@@ -278,9 +280,7 @@ Item {
height: 12
MouseArea {
anchors.fill: parent
- onClicked: {
- root.selectionLocked = !root.selectionLocked;
- }
+ onClicked: rangeDetails.toggleSelectionLocked()
}
}
@@ -294,10 +294,7 @@ Item {
renderType: Text.NativeRendering
MouseArea {
anchors.fill: parent
- onClicked: {
- rangeDetails.hide();
- view.selectFromEventIndex(view.selectedModel, -1);
- }
+ onClicked: rangeDetails.clearSelection()
}
}
diff --git a/src/plugins/qmlprofiler/qml/RangeMover.qml b/src/libs/timeline/qml/RangeMover.qml
index 09396368c1a..09396368c1a 100644
--- a/src/plugins/qmlprofiler/qml/RangeMover.qml
+++ b/src/libs/timeline/qml/RangeMover.qml
diff --git a/src/libs/timeline/qml/RowLabel.qml b/src/libs/timeline/qml/RowLabel.qml
new file mode 100644
index 00000000000..4f2afd80fff
--- /dev/null
+++ b/src/libs/timeline/qml/RowLabel.qml
@@ -0,0 +1,83 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+import QtQuick.Controls 1.2
+import QtQuick.Controls.Styles 1.2
+
+Button {
+ id: button
+ property var label
+
+ readonly property int dragHeight: 5
+
+ signal selectBySelectionId()
+ signal setRowHeight(int newHeight)
+
+ property string labelText: label.description ? label.description : qsTr("[unknown]")
+ action: Action {
+ onTriggered: button.selectBySelectionId();
+ tooltip: button.labelText + (label.displayName ? (" (" + label.displayName + ")") : "")
+ }
+
+ style: ButtonStyle {
+ background: Rectangle {
+ border.width: 1
+ border.color: "#c8c8c8"
+ color: "#eaeaea"
+ }
+ label: Text {
+ text: button.labelText
+ textFormat: Text.PlainText
+ verticalAlignment: Text.AlignVCenter
+ horizontalAlignment: Text.AlignLeft
+ elide: Text.ElideRight
+ renderType: Text.NativeRendering
+ }
+ }
+ MouseArea {
+ hoverEnabled: true
+ property bool resizing: false
+ onPressed: resizing = true
+ onReleased: resizing = false
+
+ height: dragHeight
+ anchors.bottom: parent.bottom
+ anchors.left: parent.left
+ anchors.right: parent.right
+ cursorShape: Qt.SizeVerCursor
+
+ onMouseYChanged: {
+ if (resizing)
+ button.setRowHeight(y + mouseY)
+ }
+ }
+}
+
diff --git a/src/plugins/qmlprofiler/qml/SelectionRange.qml b/src/libs/timeline/qml/SelectionRange.qml
index 399ca0b6bc0..b25e9d2d174 100644
--- a/src/plugins/qmlprofiler/qml/SelectionRange.qml
+++ b/src/libs/timeline/qml/SelectionRange.qml
@@ -32,40 +32,26 @@ import QtQuick 2.1
RangeMover {
id: selectionRange
+ property QtObject zoomer;
- property bool ready: visible && creationState === 3
+ readonly property int creationInactive: 0
+ readonly property int creationFirstLimit: 1
+ readonly property int creationSecondLimit: 2
+ readonly property int creationFinished: 3
- property string startTimeString: detailedPrintTime(startTime)
- property string endTimeString: detailedPrintTime(startTime+duration)
- property string durationString: detailedPrintTime(duration)
+ property bool ready: visible && creationState === creationFinished
- property double startTime: rangeLeft * viewTimePerPixel + zoomControl.windowStart()
+ property double startTime: rangeLeft * viewTimePerPixel + zoomer.windowStart
property double duration: Math.max(rangeWidth * viewTimePerPixel, 500)
+ property double endTime: startTime + duration
+
property double viewTimePerPixel: 1
property double creationReference : 0
- property int creationState : 0
-
- Connections {
- target: zoomControl
- onRangeChanged: {
- var oldTimePerPixel = selectionRange.viewTimePerPixel;
- selectionRange.viewTimePerPixel = Math.abs(zoomControl.endTime() - zoomControl.startTime()) / view.intWidth;
- if (creationState === 3 && oldTimePerPixel != selectionRange.viewTimePerPixel) {
- var newWidth = rangeWidth * oldTimePerPixel / viewTimePerPixel;
- rangeLeft = rangeLeft * oldTimePerPixel / viewTimePerPixel;
- rangeRight = rangeLeft + newWidth;
- }
- }
- }
-
- onRangeDoubleClicked: {
- zoomControl.setRange(startTime, startTime + duration);
- root.selectionRangeMode = false;
- }
+ property int creationState : creationInactive
function reset() {
rangeRight = rangeLeft + 1;
- creationState = 0;
+ creationState = creationInactive;
creationReference = 0;
}
@@ -76,12 +62,12 @@ RangeMover {
pos = width;
switch (creationState) {
- case 1:
+ case creationFirstLimit:
creationReference = pos;
rangeLeft = pos;
rangeRight = pos + 1;
break;
- case 2:
+ case creationSecondLimit:
if (pos > creationReference) {
rangeLeft = creationReference;
rangeRight = pos;
@@ -92,43 +78,4 @@ RangeMover {
break;
}
}
-
-
- function detailedPrintTime( t )
- {
- if (t <= 0) return "0";
- if (t<1000) return t+" ns";
- t = Math.floor(t/1000);
- if (t<1000) return t+" μs";
- if (t<1e6) return (t/1000) + " ms";
- return (t/1e6) + " s";
- }
-
- // creation control
- function releasedOnCreation() {
- if (selectionRange.creationState === 2) {
- flick.stayInteractive = true;
- selectionRange.creationState = 3;
- selectionRangeControl.enabled = false;
- }
- }
-
- function pressedOnCreation() {
- if (selectionRange.creationState === 1) {
- flick.stayInteractive = false;
- selectionRange.setPos(selectionRangeControl.mouseX + flick.contentX);
- selectionRange.creationState = 2;
- }
- }
-
- function movedOnCreation() {
- if (selectionRange.creationState === 0) {
- selectionRange.creationState = 1;
- }
-
- if (!selectionRangeControl.pressed && selectionRange.creationState==3)
- return;
-
- selectionRange.setPos(selectionRangeControl.mouseX + flick.contentX);
- }
}
diff --git a/src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml b/src/libs/timeline/qml/SelectionRangeDetails.qml
index 037d3d28dd5..db142251ab7 100644
--- a/src/plugins/qmlprofiler/qml/SelectionRangeDetails.qml
+++ b/src/libs/timeline/qml/SelectionRangeDetails.qml
@@ -29,11 +29,13 @@
****************************************************************************/
import QtQuick 2.1
-import Monitor 1.0
Item {
id: selectionRangeDetails
+ signal recenter
+ signal close
+
property string startTime
property string endTime
property string duration
@@ -41,29 +43,35 @@ Item {
width: Math.max(150, col.width + 25)
height: col.height + 30
- z: 1
- visible: false
- x: 200
- y: 125
// keep inside view
Connections {
- target: root
+ target: selectionRangeDetails.parent
onWidthChanged: fitInView();
onHeightChanged: fitInView();
}
+ function detailedPrintTime( t )
+ {
+ if (t <= 0) return "0";
+ if (t<1000) return t+" ns";
+ t = Math.floor(t/1000);
+ if (t<1000) return t+" μs";
+ if (t<1e6) return (t/1000) + " ms";
+ return (t/1e6) + " s";
+ }
+
function fitInView() {
// don't reposition if it does not fit
- if (root.width < width || root.height < height)
+ if (parent.width < width || parent.height < height)
return;
- if (x + width > root.width)
- x = root.width - width;
+ if (x + width > parent.width)
+ x = parent.width - width;
if (x < 0)
x = 0;
- if (y + height > root.height)
- y = root.height - height;
+ if (y + height > parent.height)
+ y = parent.height - height;
if (y < 0)
y = 0;
}
@@ -138,11 +146,11 @@ Item {
Repeater {
model: [
qsTr("Start") + ":",
- startTime,
+ detailedPrintTime(startTime),
showDuration ? (qsTr("End") + ":") : "",
- showDuration ? endTime : "",
+ showDuration ? detailedPrintTime(endTime) : "",
showDuration ? (qsTr("Duration") + ":") : "",
- showDuration ? duration : ""
+ showDuration ? detailedPrintTime(duration) : ""
]
Detail {
isLabel: index % 2 === 0
@@ -156,14 +164,10 @@ Item {
anchors.fill: parent
drag.target: parent
drag.minimumX: 0
- drag.maximumX: root.width - parent.width
+ drag.maximumX: selectionRangeDetails.parent.width - width
drag.minimumY: 0
- drag.maximumY: root.height - parent.height + 0
- onClicked: {
- if ((selectionRange.x < flick.contentX) ^ (selectionRange.x+selectionRange.width > flick.contentX + flick.width)) {
- root.recenter(selectionRange.startTime + selectionRange.duration/2);
- }
- }
+ drag.maximumY: selectionRangeDetails.parent.height - height
+ onClicked: selectionRangeDetails.recenter()
}
Text {
@@ -176,11 +180,7 @@ Item {
MouseArea {
anchors.fill: parent
anchors.leftMargin: -8
- onClicked: {
- root.selectionRangeMode = false;
- root.updateRangeButton();
- }
+ onClicked: selectionRangeDetails.close()
}
}
-
}
diff --git a/src/libs/timeline/qml/SynchronousReloader.qml b/src/libs/timeline/qml/SynchronousReloader.qml
new file mode 100644
index 00000000000..9092327e9c4
--- /dev/null
+++ b/src/libs/timeline/qml/SynchronousReloader.qml
@@ -0,0 +1,43 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Loader {
+ onAsynchronousChanged: {
+ if (!asynchronous && active && status !== Loader.Ready) {
+ // Trigger a synchronous reload to avoid glitches
+ var component = sourceComponent;
+ sourceComponent = undefined;
+ sourceComponent = component;
+ }
+ }
+}
+
diff --git a/src/libs/timeline/qml/TimeDisplay.qml b/src/libs/timeline/qml/TimeDisplay.qml
new file mode 100644
index 00000000000..e1372e7c3e4
--- /dev/null
+++ b/src/libs/timeline/qml/TimeDisplay.qml
@@ -0,0 +1,187 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.1
+
+Item {
+ id: timeDisplay
+
+ property double windowStart
+ property double rangeDuration
+
+ property int topBorderHeight: 2
+ property int bottomBorderHeight: 1
+ property int textMargin: 5
+ property int labelsHeight: 24
+ property int fontSize: 8
+ property color color1: "#E6E6E6"
+ property color color2: "white"
+ property int initialBlockLength: 120
+ property double spacing: width / rangeDuration
+
+ property double timePerBlock: Math.pow(2, Math.floor(Math.log(initialBlockLength / spacing) /
+ Math.LN2))
+
+ property double alignedWindowStart: Math.round(windowStart - (windowStart % timePerBlock))
+ property double pixelsPerBlock: timeDisplay.timePerBlock * timeDisplay.spacing
+ property double pixelsPerSection: pixelsPerBlock / 5
+
+ property int contentX
+ property int offsetX: contentX + Math.round((windowStart % timePerBlock) * spacing)
+
+ readonly property var timeUnits: ["μs", "ms", "s"]
+ function prettyPrintTime(t, rangeDuration) {
+ var round = 1;
+ var barrier = 1;
+
+ for (var i = 0; i < timeUnits.length; ++i) {
+ barrier *= 1000;
+ if (rangeDuration < barrier)
+ round *= 1000;
+ else if (rangeDuration < barrier * 10)
+ round *= 100;
+ else if (rangeDuration < barrier * 100)
+ round *= 10;
+ if (t < barrier * 1000)
+ return Math.floor(t / (barrier / round)) / round + timeUnits[i];
+ }
+
+ t /= barrier;
+ var m = Math.floor(t / 60);
+ var s = Math.floor((t - m * 60) * round) / round;
+ return m + "m" + s + "s";
+ }
+
+ Item {
+ x: Math.floor(firstBlock * timeDisplay.pixelsPerBlock - timeDisplay.offsetX)
+ y: 0
+ id: row
+
+ property int firstBlock: timeDisplay.offsetX / timeDisplay.pixelsPerBlock
+ property int offset: firstBlock % repeater.model
+
+ Repeater {
+ id: repeater
+ model: Math.floor(timeDisplay.width / timeDisplay.initialBlockLength * 2 + 2)
+
+ Item {
+ id: column
+
+ // Changing the text in text nodes is expensive. We minimize the number of changes
+ // by rotating the nodes during scrolling.
+ property int stableIndex: row.offset > index ? repeater.model - row.offset + index :
+ index - row.offset
+ height: timeDisplay.height
+ y: 0
+ x: width * stableIndex
+ width: timeDisplay.pixelsPerBlock
+
+ // Manually control this. We don't want it to happen when firstBlock
+ // changes before stableIndex changes.
+ onStableIndexChanged: block = row.firstBlock + stableIndex
+ property int block: -1
+ property double blockStartTime: block * timeDisplay.timePerBlock +
+ timeDisplay.alignedWindowStart
+
+ Rectangle {
+ id: timeLabel
+
+ anchors.top: parent.top
+ anchors.left: parent.left
+ anchors.right: parent.right
+ height: timeDisplay.labelsHeight
+
+ color: (Math.round(column.block + timeDisplay.alignedWindowStart /
+ timeDisplay.timePerBlock) % 2) ? color1 : color2;
+
+ Text {
+ id: labelText
+ renderType: Text.NativeRendering
+ font.pixelSize: timeDisplay.fontSize
+ font.family: "sans-serif"
+ anchors.fill: parent
+ anchors.leftMargin: timeDisplay.textMargin
+ anchors.bottomMargin: timeDisplay.textMargin
+ verticalAlignment: Text.AlignBottom
+ text: prettyPrintTime(column.blockStartTime, timeDisplay.rangeDuration)
+ }
+ }
+
+ Row {
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: timeLabel.bottom
+ anchors.bottom: parent.bottom
+
+ Repeater {
+ model: 4
+ Item {
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ width: timeDisplay.pixelsPerSection
+
+ Rectangle {
+ color: "#CCCCCC"
+ width: 1
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ anchors.right: parent.right
+ }
+ }
+ }
+ }
+
+ Rectangle {
+ color: "#B0B0B0"
+ width: 1
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ anchors.right: parent.right
+ }
+ }
+ }
+ }
+
+ Rectangle {
+ height: topBorderHeight
+ anchors.left: parent.left
+ anchors.right: parent.right
+ y: labelsHeight - topBorderHeight
+ color: "#B0B0B0"
+ }
+
+ Rectangle {
+ height: bottomBorderHeight
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: row.bottom
+ color: "#B0B0B0"
+ }
+}
diff --git a/src/libs/timeline/qml/TimeMarks.qml b/src/libs/timeline/qml/TimeMarks.qml
new file mode 100644
index 00000000000..12d9a021f92
--- /dev/null
+++ b/src/libs/timeline/qml/TimeMarks.qml
@@ -0,0 +1,147 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.1
+
+Item {
+ id: timeMarks
+ visible: model && (mockup || (!model.hidden && !model.empty))
+ property QtObject model
+ property bool startOdd
+ property bool mockup
+
+ readonly property int scaleMinHeight: 60
+ readonly property int scaleStepping: 30
+ readonly property string units: " kMGT"
+
+
+ property int rowCount: model ? model.rowCount : 0
+
+ function prettyPrintScale(amount) {
+ var unitOffset = 0;
+ for (unitOffset = 0; amount > (1 << ((unitOffset + 1) * 10)); ++unitOffset) {}
+ var result = (amount >> (unitOffset * 10));
+ if (result < 100) {
+ var comma = Math.round(((amount >> ((unitOffset - 1) * 10)) & 1023) *
+ (result < 10 ? 100 : 10) / 1024);
+ if (comma < 10 && result < 10)
+ return result + ".0" + comma + units[unitOffset];
+ else
+ return result + "." + comma + units[unitOffset];
+ } else {
+ return result + units[unitOffset];
+ }
+ }
+
+ Connections {
+ target: model
+ onExpandedRowHeightChanged: {
+ if (model && model.expanded && row >= 0)
+ rowRepeater.itemAt(row).height = height;
+ }
+ }
+
+
+ Column {
+ id: rows
+ anchors.left: parent.left
+ anchors.right: parent.right
+ Repeater {
+ id: rowRepeater
+ model: timeMarks.rowCount
+ Rectangle {
+ id: row
+ color: ((index + (startOdd ? 1 : 0)) % 2) ? "#f0f0f0" : "white"
+ anchors.left: rows.left
+ anchors.right: rows.right
+ height: timeMarks.model ? timeMarks.model.rowHeight(index) : 0
+
+ property int minVal: timeMarks.model ? timeMarks.model.rowMinValue(index) : 0
+ property int maxVal: timeMarks.model ? timeMarks.model.rowMaxValue(index) : 0
+ property int valDiff: maxVal - minVal
+ property bool scaleVisible: timeMarks.model && timeMarks.model.expanded &&
+ height > scaleMinHeight && valDiff > 0
+
+ property int stepVal: {
+ var ret = 1;
+ var ugly = Math.ceil(valDiff / Math.floor(height / scaleStepping));
+ while (isFinite(ugly) && ugly > 1) {
+ ugly >>= 1;
+ ret <<= 1;
+ }
+ return ret;
+ }
+
+ Text {
+ id: scaleTopLabel
+ renderType: Text.NativeRendering
+ visible: parent.scaleVisible
+ color: "#B0B0B0"
+ font.pixelSize: 8
+ anchors.top: parent.top
+ anchors.leftMargin: 2
+ anchors.topMargin: 2
+ anchors.left: parent.left
+ text: prettyPrintScale(row.maxVal)
+ }
+
+ Repeater {
+ model: parent.scaleVisible ? row.valDiff / row.stepVal : 0
+
+ Item {
+ anchors.left: row.left
+ anchors.right: row.right
+ height: row.stepVal * row.height / row.valDiff
+ y: row.height - (index + 1) * height
+ visible: y > scaleTopLabel.height
+ Text {
+ renderType: Text.NativeRendering
+ color: "#B0B0B0"
+ font.pixelSize: 8
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 2
+ anchors.leftMargin: 2
+ anchors.left: parent.left
+ text: prettyPrintScale(index * row.stepVal)
+ }
+
+ Rectangle {
+ height: 1
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.bottom: parent.bottom
+ color: "#B0B0B0"
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/libs/timeline/qml/TimelineContent.qml b/src/libs/timeline/qml/TimelineContent.qml
new file mode 100644
index 00000000000..998c5c108ba
--- /dev/null
+++ b/src/libs/timeline/qml/TimelineContent.qml
@@ -0,0 +1,215 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+import QtQuick.Controls 1.2
+import TimelineRenderer 1.0
+import QtQml.Models 2.1
+
+ScrollView {
+ id: scroller
+
+ property QtObject zoomer
+ property QtObject modelProxy
+
+ property int contentX: flick.contentX
+ property int contentY: flick.contentY
+ property int contentWidth: flick.contentWidth
+ property int contentHeight: flick.contentHeight
+ property bool selectionLocked
+ property int typeId
+
+ signal propagateSelection(int newModel, int newItem)
+ signal gotoSourceLocation(string file, int line, int column)
+
+ function clearChildren()
+ {
+ timelineView.clearChildren();
+ }
+
+ function select(modelIndex, eventIndex)
+ {
+ timelineView.select(modelIndex, eventIndex);
+ }
+
+ function moveCategories(sourceIndex, targetIndex)
+ {
+ timelineModel.items.move(sourceIndex, targetIndex)
+ }
+
+ function scroll()
+ {
+ flick.scroll();
+ }
+
+ // ScrollView will try to deinteractivate it. We don't want that
+ // as the horizontal flickable is interactive, too. We do occasionally
+ // switch to non-interactive ourselves, though.
+ property bool stayInteractive: true
+ onStayInteractiveChanged: flick.interactive = stayInteractive
+
+ Flickable {
+ id: flick
+ contentHeight: timelineView.height + height
+ flickableDirection: Flickable.HorizontalAndVerticalFlick
+ boundsBehavior: Flickable.StopAtBounds
+ pixelAligned: true
+
+ onInteractiveChanged: interactive = stayInteractive
+
+ property bool recursionGuard: false
+
+ // Update the zoom control on srolling.
+ onContentXChanged: {
+ if (recursionGuard)
+ return;
+
+ recursionGuard = true;
+
+ var newStartTime = contentX * zoomer.rangeDuration / scroller.width +
+ zoomer.windowStart;
+ if (isFinite(newStartTime) && Math.abs(newStartTime - zoomer.rangeStart) >= 1) {
+ var newEndTime = (contentX + scroller.width) * zoomer.rangeDuration /
+ scroller.width + zoomer.windowStart;
+ if (isFinite(newEndTime))
+ zoomer.setRange(newStartTime, newEndTime);
+ }
+ recursionGuard = false;
+ }
+
+ // Scroll when the zoom control is updated
+ function scroll() {
+ if (recursionGuard || zoomer.rangeDuration <= 0)
+ return;
+ recursionGuard = true;
+
+ var newWidth = zoomer.windowDuration * scroller.width / zoomer.rangeDuration;
+ if (isFinite(newWidth) && Math.abs(newWidth - contentWidth) >= 1)
+ contentWidth = newWidth;
+
+ var newStartX = (zoomer.rangeStart - zoomer.windowStart) * scroller.width /
+ zoomer.rangeDuration;
+ if (isFinite(newStartX) && Math.abs(newStartX - contentX) >= 1)
+ contentX = newStartX;
+
+ recursionGuard = false;
+ }
+
+ Column {
+ id: timelineView
+
+ signal clearChildren
+ signal select(int modelIndex, int eventIndex)
+
+ DelegateModel {
+ id: timelineModel
+ model: modelProxy.models
+ delegate: TimelineRenderer {
+ id: renderer
+ model: modelData
+ notes: modelProxy.notes
+ zoomer: scroller.zoomer
+ selectionLocked: scroller.selectionLocked
+ x: 0
+ height: modelData.height
+ property int visualIndex: DelegateModel.itemsIndex
+
+ // paint "under" the vertical scrollbar, so that it always matches with the
+ // timemarks
+ width: flick.contentWidth
+
+ Connections {
+ target: timelineView
+ onClearChildren: renderer.clearData()
+ onSelect: {
+ if (modelIndex === index || modelIndex === -1) {
+ renderer.selectedItem = eventIndex;
+ if (eventIndex !== -1)
+ renderer.recenter();
+ }
+ }
+ }
+
+ Connections {
+ target: scroller
+ onSelectionLockedChanged: {
+ renderer.selectionLocked = scroller.selectionLocked;
+ }
+ }
+
+ onSelectionLockedChanged: {
+ scroller.selectionLocked = renderer.selectionLocked;
+ }
+
+ function recenter() {
+ if (modelData.endTime(selectedItem) < zoomer.rangeStart ||
+ modelData.startTime(selectedItem) > zoomer.rangeEnd) {
+
+ var newStart = (modelData.startTime(selectedItem) +
+ modelData.endTime(selectedItem) -
+ zoomer.rangeDuration) / 2;
+ zoomer.setRange(Math.max(newStart, zoomer.traceStart),
+ Math.min(newStart + zoomer.rangeDuration,
+ zoomer.traceEnd));
+ }
+
+ var row = modelData.row(selectedItem);
+ var rowStart = modelData.rowOffset(row) + y;
+ var rowEnd = rowStart + modelData.rowHeight(row);
+ if (rowStart < flick.contentY || rowEnd - scroller.height > flick.contentY)
+ flick.contentY = (rowStart + rowEnd - scroller.height) / 2;
+ }
+
+ onSelectedItemChanged: {
+ scroller.propagateSelection(index, selectedItem);
+ }
+
+ onItemPressed: {
+ if (pressedItem === -1) {
+ // User clicked on empty space. Remove selection.
+ scroller.propagateSelection(-1, -1);
+ } else {
+ var location = model.location(pressedItem);
+ if (location.hasOwnProperty("file")) // not empty
+ scroller.gotoSourceLocation(location.file, location.line,
+ location.column);
+ scroller.typeId = model.typeId(pressedItem);
+ }
+ }
+ }
+ }
+
+ Repeater {
+ id: repeater
+ model: timelineModel
+ }
+ }
+ }
+}
diff --git a/src/libs/timeline/qml/TimelineLabels.qml b/src/libs/timeline/qml/TimelineLabels.qml
new file mode 100644
index 00000000000..604658572bf
--- /dev/null
+++ b/src/libs/timeline/qml/TimelineLabels.qml
@@ -0,0 +1,174 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+import QtQml.Models 2.1
+
+Flickable {
+ id: categories
+ flickableDirection: Flickable.VerticalFlick
+ interactive: false
+ property color color
+
+ property int selectedModel
+ property int selectedItem
+ property bool reverseSelect
+ property QtObject modelProxy
+ property QtObject zoomer
+
+ signal selectItem(int modelIndex, int eventIndex)
+ signal moveCategories(int sourceIndex, int targetIndex)
+
+ // reserve some more space than needed to prevent weird effects when resizing
+ contentHeight: categoryContent.height + height
+
+ // Dispatch the cursor shape to all labels. When dragging the DropArea receiving
+ // the drag events is not necessarily related to the MouseArea receiving the mouse
+ // events, so we can't use the drag events to determine the cursor shape.
+ property bool dragging: false
+
+ Column {
+ id: categoryContent
+ anchors.left: parent.left
+ anchors.right: parent.right
+
+ DelegateModel {
+ id: labelsModel
+
+ // As we cannot retrieve items by visible index we keep an array of row counts here,
+ // for the time marks to draw the row backgrounds in the right colors.
+ property var rowCounts: new Array(modelProxy.models.length)
+
+ function updateRowCount(visualIndex, rowCount) {
+ if (rowCounts[visualIndex] !== rowCount) {
+ rowCounts[visualIndex] = rowCount;
+ // Array don't "change" if entries change. We have to signal manually.
+ rowCountsChanged();
+ }
+ }
+
+ model: modelProxy.models
+ delegate: SynchronousReloader {
+ id: loader
+ asynchronous: y < categories.contentY + categories.height &&
+ y + height > categories.contentY
+ active: modelData !== null &&
+ (modelProxy.height === 0 || (!modelData.hidden && !modelData.empty))
+ height: active ? Math.max(modelData.height, modelData.defaultRowHeight) : 0
+ width: categories.width
+ property int visualIndex: DelegateModel.itemsIndex
+
+ sourceComponent: Rectangle {
+ color: categories.color
+ height: loader.height
+ width: loader.width
+
+ CategoryLabel {
+ id: label
+ model: modelData
+ notesModel: modelProxy.notes
+ visualIndex: loader.visualIndex
+ dragging: categories.dragging
+ reverseSelect: categories.reverseSelect
+ onDragStarted: categories.dragging = true
+ onDragStopped: categories.dragging = false
+ draggerParent: categories
+ width: 150
+ height: parent.height
+ dragOffset: parent.y
+
+ onDropped: {
+ categories.moveCategories(sourceIndex, targetIndex);
+ labelsModel.items.move(sourceIndex, targetIndex);
+ }
+
+ onSelectById: {
+ categories.selectItem(index, eventId)
+ }
+
+ onSelectNextBySelectionId: {
+ categories.selectItem(index, modelData.nextItemBySelectionId(
+ selectionId, zoomer.rangeStart,
+ categories.selectedModel === index ? categories.selectedItem :
+ -1));
+ }
+
+ onSelectPrevBySelectionId: {
+ categories.selectItem(index, modelData.prevItemBySelectionId(
+ selectionId, zoomer.rangeStart,
+ categories.selectedModel === index ? categories.selectedItem :
+ -1));
+ }
+ }
+
+ TimeMarks {
+ id: timeMarks
+ model: modelData
+ mockup: modelProxy.height === 0
+ anchors.right: parent.right
+ anchors.left: label.right
+ anchors.top: parent.top
+ anchors.bottom: parent.bottom
+ property int visualIndex: loader.visualIndex
+
+ // Quite a mouthful, but works fine: Add up all the row counts up to the one
+ // for this visual index and check if the result is even or odd.
+ startOdd: (labelsModel.rowCounts.slice(0, visualIndex).reduce(
+ function(prev, rows) {return prev + rows}, 0) % 2) === 0
+
+ onRowCountChanged: labelsModel.updateRowCount(visualIndex, rowCount)
+ onVisualIndexChanged: labelsModel.updateRowCount(visualIndex, rowCount)
+ }
+
+ Rectangle {
+ opacity: loader.y === 0 ? 0 : 1
+ color: "#B0B0B0"
+ height: 1
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: parent.top
+ }
+ }
+ }
+ }
+
+ Repeater {
+ model: labelsModel
+ }
+ }
+
+ Rectangle {
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.top: categoryContent.bottom
+ height: 1
+ color: "#B0B0B0"
+ }
+}
diff --git a/src/plugins/qmlprofiler/qml/arrow_down.png b/src/libs/timeline/qml/arrow_down.png
index bbc8ec3c179..bbc8ec3c179 100644
--- a/src/plugins/qmlprofiler/qml/arrow_down.png
+++ b/src/libs/timeline/qml/arrow_down.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/arrow_right.png b/src/libs/timeline/qml/arrow_right.png
index 2d64649dc75..2d64649dc75 100644
--- a/src/plugins/qmlprofiler/qml/arrow_right.png
+++ b/src/libs/timeline/qml/arrow_right.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/dialog_shadow.png b/src/libs/timeline/qml/dialog_shadow.png
index 2d697325c33..2d697325c33 100644
--- a/src/plugins/qmlprofiler/qml/dialog_shadow.png
+++ b/src/libs/timeline/qml/dialog_shadow.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_edit.png b/src/libs/timeline/qml/ico_edit.png
index f235e86c839..f235e86c839 100644
--- a/src/plugins/qmlprofiler/qml/ico_edit.png
+++ b/src/libs/timeline/qml/ico_edit.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_filter.png b/src/libs/timeline/qml/ico_filter.png
index edfb9fc86b6..edfb9fc86b6 100644
--- a/src/plugins/qmlprofiler/qml/ico_filter.png
+++ b/src/libs/timeline/qml/ico_filter.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_next.png b/src/libs/timeline/qml/ico_next.png
index dad2f241c22..dad2f241c22 100644
--- a/src/plugins/qmlprofiler/qml/ico_next.png
+++ b/src/libs/timeline/qml/ico_next.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_note.png b/src/libs/timeline/qml/ico_note.png
index fa5c2b5bc95..fa5c2b5bc95 100644
--- a/src/plugins/qmlprofiler/qml/ico_note.png
+++ b/src/libs/timeline/qml/ico_note.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_prev.png b/src/libs/timeline/qml/ico_prev.png
index 7794d3d2911..7794d3d2911 100644
--- a/src/plugins/qmlprofiler/qml/ico_prev.png
+++ b/src/libs/timeline/qml/ico_prev.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_rangeselected.png b/src/libs/timeline/qml/ico_rangeselected.png
index c6a422461a2..c6a422461a2 100644
--- a/src/plugins/qmlprofiler/qml/ico_rangeselected.png
+++ b/src/libs/timeline/qml/ico_rangeselected.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_rangeselection.png b/src/libs/timeline/qml/ico_rangeselection.png
index f303a21c8c8..f303a21c8c8 100644
--- a/src/plugins/qmlprofiler/qml/ico_rangeselection.png
+++ b/src/libs/timeline/qml/ico_rangeselection.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_selectionmode.png b/src/libs/timeline/qml/ico_selectionmode.png
index ac23d47b261..ac23d47b261 100644
--- a/src/plugins/qmlprofiler/qml/ico_selectionmode.png
+++ b/src/libs/timeline/qml/ico_selectionmode.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/ico_zoom.png b/src/libs/timeline/qml/ico_zoom.png
index 9235535eaa5..9235535eaa5 100644
--- a/src/plugins/qmlprofiler/qml/ico_zoom.png
+++ b/src/libs/timeline/qml/ico_zoom.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/lock_closed.png b/src/libs/timeline/qml/lock_closed.png
index e6f86fa753e..e6f86fa753e 100644
--- a/src/plugins/qmlprofiler/qml/lock_closed.png
+++ b/src/libs/timeline/qml/lock_closed.png
Binary files differ
diff --git a/src/plugins/qmlprofiler/qml/lock_open.png b/src/libs/timeline/qml/lock_open.png
index ab6c820dfbd..ab6c820dfbd 100644
--- a/src/plugins/qmlprofiler/qml/lock_open.png
+++ b/src/libs/timeline/qml/lock_open.png
Binary files differ
diff --git a/src/libs/timeline/qml/notes.frag b/src/libs/timeline/qml/notes.frag
new file mode 100644
index 00000000000..472c0174db0
--- /dev/null
+++ b/src/libs/timeline/qml/notes.frag
@@ -0,0 +1,37 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+vec4 orange = vec4(1.0, 165.0 / 255.0, 0.0, 1.0);
+varying float d;
+
+void main()
+{
+ gl_FragColor = orange * float(d < (2.0 / 3.0) || d > (5.0 / 6.0));
+}
diff --git a/src/plugins/qmldesigner/qmldesignerwarning.cpp b/src/libs/timeline/qml/notes.vert
index 14e61520ad8..0a37ef7ccfd 100644
--- a/src/plugins/qmldesigner/qmldesignerwarning.cpp
+++ b/src/libs/timeline/qml/notes.vert
@@ -28,17 +28,16 @@
**
****************************************************************************/
-#include "qmldesignerwarning.h"
+attribute vec4 vertexCoord;
+attribute float distanceFromTop;
-#include <coreplugin/icore.h>
+uniform mat4 matrix;
+varying float d;
-#include <QMessageBox>
-
-void QmlDesigner::QmlDesignerWarning::show(const QString &title, const QString &desciption)
+void main()
{
- QMessageBox *messageBox = new QMessageBox(QMessageBox::Warning, title, desciption, QMessageBox::
- Ok, Core::ICore::dialogParent());
- messageBox->setAttribute(Qt::WA_DeleteOnClose);
- messageBox->setModal(true);
- messageBox->show();
+ gl_Position = matrix * vertexCoord;
+ gl_Position.z -= 0.1;
+ gl_Position.w = 1.0;
+ d = distanceFromTop;
}
diff --git a/src/plugins/qmlprofiler/qml/range_handle.png b/src/libs/timeline/qml/range_handle.png
index f44fb3337ff..f44fb3337ff 100644
--- a/src/plugins/qmlprofiler/qml/range_handle.png
+++ b/src/libs/timeline/qml/range_handle.png
Binary files differ
diff --git a/src/libs/timeline/qml/timeline.qrc b/src/libs/timeline/qml/timeline.qrc
new file mode 100644
index 00000000000..540244538c0
--- /dev/null
+++ b/src/libs/timeline/qml/timeline.qrc
@@ -0,0 +1,38 @@
+<RCC>
+ <qresource prefix="/timeline">
+ <file>Detail.qml</file>
+ <file>CategoryLabel.qml</file>
+ <file>MainView.qml</file>
+ <file>RangeDetails.qml</file>
+ <file>RangeMover.qml</file>
+ <file>TimeDisplay.qml</file>
+ <file>lock_closed.png</file>
+ <file>lock_open.png</file>
+ <file>ico_edit.png</file>
+ <file>TimeMarks.qml</file>
+ <file>Overview.qml</file>
+ <file>SelectionRange.qml</file>
+ <file>SelectionRangeDetails.qml</file>
+ <file>arrow_down.png</file>
+ <file>arrow_right.png</file>
+ <file>dialog_shadow.png</file>
+ <file>range_handle.png</file>
+ <file>ico_selectionmode.png</file>
+ <file>ico_zoom.png</file>
+ <file>ico_prev.png</file>
+ <file>ico_next.png</file>
+ <file>ico_rangeselection.png</file>
+ <file>ico_rangeselected.png</file>
+ <file>ico_note.png</file>
+ <file>ButtonsBar.qml</file>
+ <file>ico_filter.png</file>
+ <file>timelineitems.vert</file>
+ <file>timelineitems.frag</file>
+ <file>notes.vert</file>
+ <file>notes.frag</file>
+ <file>TimelineLabels.qml</file>
+ <file>TimelineContent.qml</file>
+ <file>RowLabel.qml</file>
+ <file>SynchronousReloader.qml</file>
+ </qresource>
+</RCC>
diff --git a/src/libs/timeline/qml/timelineitems.frag b/src/libs/timeline/qml/timelineitems.frag
new file mode 100644
index 00000000000..0ee0ad2aba6
--- /dev/null
+++ b/src/libs/timeline/qml/timelineitems.frag
@@ -0,0 +1,46 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+varying lowp vec3 edgeColor;
+varying lowp vec3 color;
+varying lowp vec2 barycentric;
+
+vec4 zero = vec4(0.0);
+void main()
+{
+ vec2 d = fwidth(barycentric) * 5.0;
+ vec4 edge_closeness = smoothstep(zero, vec4(d.x, d.y, d.x, d.y),
+ vec4(barycentric.x, barycentric.y, 1.0 - barycentric.x, 1.0 - barycentric.y));
+ float total = min(min(edge_closeness[0], edge_closeness[1]),
+ min(edge_closeness[2], edge_closeness[3]));
+ // square to make lines sharper
+ total = total > 0.5 ? (1.0 - (1.0 - total) * (1.0 - total) * 2.0) : total * total * 2.0;
+ gl_FragColor.rgb = mix(edgeColor, color, total);
+}
diff --git a/src/libs/timeline/qml/timelineitems.vert b/src/libs/timeline/qml/timelineitems.vert
new file mode 100644
index 00000000000..58f28b558a9
--- /dev/null
+++ b/src/libs/timeline/qml/timelineitems.vert
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+attribute vec4 vertexCoord;
+attribute vec2 rectSize;
+attribute float selectionId;
+attribute vec4 vertexColor;
+
+uniform vec2 scale;
+uniform mat4 matrix;
+uniform vec4 selectionColor;
+uniform float selectedItem;
+
+varying vec3 color;
+varying vec3 edgeColor;
+varying vec2 barycentric;
+
+void main()
+{
+ gl_Position = matrix * vertexCoord;
+
+ // Make very narrow events somewhat wider so that they don't collapse into 0 pixels
+ highp float scaledWidth = scale.x * rectSize.x;
+ highp float shift = sign(scaledWidth) * max(0, 3.0 - abs(scaledWidth)) * 0.0005;
+ gl_Position.x += shift;
+
+ // Ditto for events with very small height
+ highp float scaledHeight = scale.y * rectSize.y;
+ gl_Position.y += float(rectSize.y > 0.0) * max(0, 3.0 - scaledHeight) * 0.003;
+
+ barycentric = vec2(rectSize.x > 0.0 ? 1.0 : 0.0, rectSize.y > 0.0 ? 1.0 : 0.0);
+ color = vertexColor.rgb;
+ float selected = min(1.0, abs(selectionId - selectedItem));
+ edgeColor = mix(selectionColor.rgb, vertexColor.rgb, selected);
+ gl_Position.z += mix(0.0, (shift + 0.0015) / 10.0, selected);
+ gl_Position.w = 1.0;
+}
diff --git a/src/libs/timeline/timeline.pro b/src/libs/timeline/timeline.pro
new file mode 100644
index 00000000000..4b556057588
--- /dev/null
+++ b/src/libs/timeline/timeline.pro
@@ -0,0 +1,45 @@
+QT += qml quick
+DEFINES += TIMELINE_LIBRARY
+
+include(../../qtcreatorlibrary.pri)
+
+SOURCES += \
+ $$PWD/timelinemodel.cpp \
+ $$PWD/timelinemodelaggregator.cpp \
+ $$PWD/timelinerenderer.cpp \
+ $$PWD/timelinezoomcontrol.cpp \
+ $$PWD/timelineitemsrenderpass.cpp \
+ $$PWD/timelineselectionrenderpass.cpp \
+ $$PWD/timelinenotesrenderpass.cpp \
+ $$PWD/timelinerenderpass.cpp \
+ $$PWD/timelinerenderstate.cpp \
+ $$PWD/timelinenotesmodel.cpp \
+ $$PWD/timelineabstractrenderer.cpp \
+ $$PWD/timelineoverviewrenderer.cpp
+
+
+HEADERS += \
+ $$PWD/timeline_global.h \
+ $$PWD/timelinemodel.h \
+ $$PWD/timelinemodel_p.h \
+ $$PWD/timelinemodelaggregator.h \
+ $$PWD/timelinerenderer.h \
+ $$PWD/timelinezoomcontrol.h \
+ $$PWD/timelineitemsrenderpass.h \
+ $$PWD/timelineselectionrenderpass.h \
+ $$PWD/timelinenotesrenderpass.h \
+ $$PWD/timelinerenderpass.h \
+ $$PWD/timelinerenderstate.h \
+ $$PWD/timelinenotesmodel.h \
+ $$PWD/timelinenotesmodel_p.h \
+ $$PWD/timelinerenderer_p.h \
+ $$PWD/timelinerenderstate_p.h \
+ $$PWD/timelineabstractrenderer.h \
+ $$PWD/timelineabstractrenderer_p.h \
+ $$PWD/timelineoverviewrenderer_p.h \
+ $$PWD/timelineoverviewrenderer.h
+
+RESOURCES += \
+ $$PWD/qml/timeline.qrc
+
+DISTFILES += README
diff --git a/src/libs/timeline/timeline.qbs b/src/libs/timeline/timeline.qbs
new file mode 100644
index 00000000000..19ba995612d
--- /dev/null
+++ b/src/libs/timeline/timeline.qbs
@@ -0,0 +1,39 @@
+import qbs 1.0
+
+import QtcLibrary
+
+QtcLibrary {
+ name: "Timeline"
+
+ Depends { name: "Qt"; submodules: ["qml", "quick", "gui"] }
+ Depends { name: "Utils" }
+
+ Group {
+ name: "General"
+ files: [
+ "README",
+ "timelineabstractrenderer.cpp", "timelineabstractrenderer.h",
+ "timelineabstractrenderer_p.h",
+ "timelineitemsrenderpass.cpp", "timelineitemsrenderpass.h",
+ "timelinemodel.cpp", "timelinemodel.h", "timelinemodel_p.h",
+ "timelinemodelaggregator.cpp", "timelinemodelaggregator.h",
+ "timelinenotesmodel.cpp", "timelinenotesmodel.h", "timelinenotesmodel_p.h",
+ "timelinenotesrenderpass.cpp", "timelinenotesrenderpass.h",
+ "timelineoverviewrenderer.cpp", "timelineoverviewrenderer.h",
+ "timelineoverviewrenderer_p.h",
+ "timelinerenderer.cpp", "timelinerenderer.h", "timelinerenderer_p.h",
+ "timelinerenderpass.cpp", "timelinerenderpass.h",
+ "timelinerenderstate.cpp", "timelinerenderstate.h", "timelinerenderstate_p.h",
+ "timelineselectionrenderpass.cpp", "timelineselectionrenderpass.h",
+ "timelinezoomcontrol.cpp", "timelinezoomcontrol.h"
+ ]
+ }
+
+ Group {
+ name: "QML"
+ prefix: "qml/"
+ files: ["timeline.qrc"]
+ }
+
+ cpp.defines: base.concat("TIMELINE_LIBRARY")
+}
diff --git a/src/libs/timeline/timeline_dependencies.pri b/src/libs/timeline/timeline_dependencies.pri
new file mode 100644
index 00000000000..2a17a9cb38e
--- /dev/null
+++ b/src/libs/timeline/timeline_dependencies.pri
@@ -0,0 +1,4 @@
+QTC_LIB_NAME = Timeline
+
+QTC_LIB_DEPENDS = utils
+
diff --git a/src/libs/timeline/timeline_global.h b/src/libs/timeline/timeline_global.h
new file mode 100644
index 00000000000..09a312e1ca7
--- /dev/null
+++ b/src/libs/timeline/timeline_global.h
@@ -0,0 +1,43 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINE_GLOBAL_H
+#define TIMELINE_GLOBAL_H
+
+#include <QtGlobal>
+
+#if defined(TIMELINE_LIBRARY)
+# define TIMELINE_EXPORT Q_DECL_EXPORT
+#else
+# define TIMELINE_EXPORT Q_DECL_IMPORT
+#endif
+
+#endif // TIMELINE_GLOBAL_H
+
diff --git a/src/libs/timeline/timelineabstractrenderer.cpp b/src/libs/timeline/timelineabstractrenderer.cpp
new file mode 100644
index 00000000000..4a5f2fb6a30
--- /dev/null
+++ b/src/libs/timeline/timelineabstractrenderer.cpp
@@ -0,0 +1,205 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelineabstractrenderer_p.h"
+
+namespace Timeline {
+
+TimelineAbstractRenderer::TimelineAbstractRendererPrivate::TimelineAbstractRendererPrivate() :
+ selectedItem(-1), selectionLocked(true), model(0), notes(0), zoomer(0), modelDirty(false),
+ rowHeightsDirty(false), notesDirty(false)
+{
+}
+
+TimelineAbstractRenderer::TimelineAbstractRenderer(TimelineAbstractRendererPrivate &dd,
+ QQuickItem *parent) :
+ QQuickItem(parent), d_ptr(&dd)
+{
+}
+
+int TimelineAbstractRenderer::selectedItem() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->selectedItem;
+}
+
+void TimelineAbstractRenderer::setSelectedItem(int itemIndex)
+{
+ Q_D(TimelineAbstractRenderer);
+ if (d->selectedItem != itemIndex) {
+ d->selectedItem = itemIndex;
+ update();
+ emit selectedItemChanged(itemIndex);
+ }
+}
+
+TimelineAbstractRenderer::TimelineAbstractRenderer(QQuickItem *parent) : QQuickItem(parent),
+ d_ptr(new TimelineAbstractRendererPrivate)
+{
+}
+
+bool TimelineAbstractRenderer::selectionLocked() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->selectionLocked;
+}
+
+void TimelineAbstractRenderer::setSelectionLocked(bool locked)
+{
+ Q_D(TimelineAbstractRenderer);
+ if (d->selectionLocked != locked) {
+ d->selectionLocked = locked;
+ update();
+ emit selectionLockedChanged(locked);
+ }
+}
+
+TimelineModel *TimelineAbstractRenderer::model() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->model;
+}
+
+void TimelineAbstractRenderer::setModel(TimelineModel *model)
+{
+ Q_D(TimelineAbstractRenderer);
+ if (d->model == model)
+ return;
+
+ if (d->model) {
+ disconnect(d->model, &TimelineModel::expandedChanged, this, &QQuickItem::update);
+ disconnect(d->model, &TimelineModel::hiddenChanged, this, &QQuickItem::update);
+ disconnect(d->model, &TimelineModel::expandedRowHeightChanged,
+ this, &TimelineAbstractRenderer::setRowHeightsDirty);
+ disconnect(d->model, &TimelineModel::emptyChanged,
+ this, &TimelineAbstractRenderer::setModelDirty);
+ }
+
+ d->model = model;
+ if (d->model) {
+ connect(d->model, &TimelineModel::expandedChanged, this, &QQuickItem::update);
+ connect(d->model, &TimelineModel::hiddenChanged, this, &QQuickItem::update);
+ connect(d->model, &TimelineModel::expandedRowHeightChanged,
+ this, &TimelineAbstractRenderer::setRowHeightsDirty);
+ connect(d->model, &TimelineModel::emptyChanged,
+ this, &TimelineAbstractRenderer::setModelDirty);
+ d->renderPasses = d->model->supportedRenderPasses();
+ }
+
+ setModelDirty();
+ emit modelChanged(d->model);
+}
+
+TimelineNotesModel *TimelineAbstractRenderer::notes() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->notes;
+}
+
+void TimelineAbstractRenderer::setNotes(TimelineNotesModel *notes)
+{
+ Q_D(TimelineAbstractRenderer);
+ if (d->notes == notes)
+ return;
+
+ if (d->notes)
+ disconnect(d->notes, &TimelineNotesModel::changed,
+ this, &TimelineAbstractRenderer::setNotesDirty);
+
+ d->notes = notes;
+ if (d->notes)
+ connect(d->notes, &TimelineNotesModel::changed,
+ this, &TimelineAbstractRenderer::setNotesDirty);
+
+ setNotesDirty();
+ emit notesChanged(d->notes);
+}
+
+TimelineZoomControl *TimelineAbstractRenderer::zoomer() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->zoomer;
+}
+
+void TimelineAbstractRenderer::setZoomer(TimelineZoomControl *zoomer)
+{
+ Q_D(TimelineAbstractRenderer);
+ if (zoomer != d->zoomer) {
+ if (d->zoomer != 0)
+ disconnect(d->zoomer, SIGNAL(windowChanged(qint64,qint64)), this, SLOT(update()));
+ d->zoomer = zoomer;
+ if (d->zoomer != 0)
+ connect(d->zoomer, SIGNAL(windowChanged(qint64,qint64)), this, SLOT(update()));
+ emit zoomerChanged(zoomer);
+ update();
+ }
+}
+
+bool TimelineAbstractRenderer::modelDirty() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->modelDirty;
+}
+
+bool TimelineAbstractRenderer::notesDirty() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->notesDirty;
+}
+
+bool TimelineAbstractRenderer::rowHeightsDirty() const
+{
+ Q_D(const TimelineAbstractRenderer);
+ return d->rowHeightsDirty;
+}
+
+void TimelineAbstractRenderer::setModelDirty()
+{
+ Q_D(TimelineAbstractRenderer);
+ d->modelDirty = true;
+ update();
+}
+
+void TimelineAbstractRenderer::setRowHeightsDirty()
+{
+ Q_D(TimelineAbstractRenderer);
+ d->rowHeightsDirty = true;
+ update();
+}
+
+void TimelineAbstractRenderer::setNotesDirty()
+{
+ Q_D(TimelineAbstractRenderer);
+ d->notesDirty = true;
+ update();
+}
+
+} // namespace Timeline
+
diff --git a/src/libs/timeline/timelineabstractrenderer.h b/src/libs/timeline/timelineabstractrenderer.h
new file mode 100644
index 00000000000..50a9a21ad7d
--- /dev/null
+++ b/src/libs/timeline/timelineabstractrenderer.h
@@ -0,0 +1,100 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEABSTRACTRENDERER_H
+#define TIMELINEABSTRACTRENDERER_H
+
+#include "timelinezoomcontrol.h"
+#include "timelinemodel.h"
+#include "timelinenotesmodel.h"
+#include "timelinerenderpass.h"
+
+#include <QSGTransformNode>
+#include <QQuickItem>
+
+namespace Timeline {
+
+class TimelineRenderPass;
+class TimelineRenderState;
+
+class TIMELINE_EXPORT TimelineAbstractRenderer : public QQuickItem
+{
+ Q_OBJECT
+ Q_PROPERTY(Timeline::TimelineModel *model READ model WRITE setModel NOTIFY modelChanged)
+ Q_PROPERTY(Timeline::TimelineNotesModel *notes READ notes WRITE setNotes NOTIFY notesChanged)
+ Q_PROPERTY(Timeline::TimelineZoomControl *zoomer READ zoomer WRITE setZoomer NOTIFY zoomerChanged)
+ Q_PROPERTY(bool selectionLocked READ selectionLocked WRITE setSelectionLocked NOTIFY selectionLockedChanged)
+ Q_PROPERTY(int selectedItem READ selectedItem WRITE setSelectedItem NOTIFY selectedItemChanged)
+
+public:
+ TimelineAbstractRenderer(QQuickItem *parent = 0);
+
+ bool selectionLocked() const;
+ int selectedItem() const;
+
+ TimelineModel *model() const;
+ void setModel(TimelineModel *model);
+
+ TimelineNotesModel *notes() const;
+ void setNotes(TimelineNotesModel *notes);
+
+ TimelineZoomControl *zoomer() const;
+ void setZoomer(TimelineZoomControl *zoomer);
+
+ bool modelDirty() const;
+ bool notesDirty() const;
+ bool rowHeightsDirty() const;
+
+signals:
+ void modelChanged(TimelineModel *model);
+ void notesChanged(TimelineNotesModel *notes);
+ void zoomerChanged(TimelineZoomControl *zoomer);
+ void selectionLockedChanged(bool locked);
+ void selectedItemChanged(int itemIndex);
+
+public slots:
+ void setSelectedItem(int itemIndex);
+ void setSelectionLocked(bool locked);
+
+ void setModelDirty();
+ void setNotesDirty();
+ void setRowHeightsDirty();
+
+protected:
+ class TimelineAbstractRendererPrivate;
+ TimelineAbstractRenderer(TimelineAbstractRendererPrivate &dd, QQuickItem *parent = 0);
+ TimelineAbstractRendererPrivate *d_ptr;
+ Q_DECLARE_PRIVATE(TimelineAbstractRenderer)
+};
+
+} // namespace Timeline
+
+
+#endif // TIMELINEABSTRACTRENDERER_H
diff --git a/src/libs/timeline/timelineabstractrenderer_p.h b/src/libs/timeline/timelineabstractrenderer_p.h
new file mode 100644
index 00000000000..b29fce55672
--- /dev/null
+++ b/src/libs/timeline/timelineabstractrenderer_p.h
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEABSTRACTRENDERER_P_H
+#define TIMELINEABSTRACTRENDERER_P_H
+
+#include "timelineabstractrenderer.h"
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineAbstractRenderer::TimelineAbstractRendererPrivate {
+public:
+ TimelineAbstractRendererPrivate();
+
+ int selectedItem;
+ bool selectionLocked;
+ TimelineModel *model;
+ TimelineNotesModel *notes;
+ TimelineZoomControl *zoomer;
+
+ bool modelDirty;
+ bool rowHeightsDirty;
+ bool notesDirty;
+
+ QList<const TimelineRenderPass *> renderPasses;
+};
+
+}
+
+#endif // TIMELINEABSTRACTRENDERER_P_H
+
diff --git a/src/libs/timeline/timelineitemsrenderpass.cpp b/src/libs/timeline/timelineitemsrenderpass.cpp
new file mode 100644
index 00000000000..41f0a362cd2
--- /dev/null
+++ b/src/libs/timeline/timelineitemsrenderpass.cpp
@@ -0,0 +1,461 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelineitemsrenderpass.h"
+#include "timelinerenderstate.h"
+#include <QSGSimpleRectNode>
+#include <QSGVertexColorMaterial>
+#include <QtAlgorithms>
+
+namespace Timeline {
+
+class TimelineItemsMaterial : public QSGMaterial {
+public:
+ TimelineItemsMaterial();
+ QVector2D scale() const;
+ void setScale(QVector2D scale);
+
+ float selectedItem() const;
+ void setSelectedItem(float selectedItem);
+
+ QColor selectionColor() const;
+ void setSelectionColor(QColor selectionColor);
+
+ QSGMaterialType *type() const;
+ QSGMaterialShader *createShader() const;
+private:
+ QVector2D m_scale;
+ float m_selectedItem;
+ QColor m_selectionColor;
+};
+
+struct TimelineItemsRenderPassState : public TimelineRenderPass::State {
+ TimelineItemsRenderPassState() : indexFrom(std::numeric_limits<int>::max()), indexTo(-1) {}
+ int indexFrom;
+ int indexTo;
+ TimelineItemsMaterial collapsedRowMaterial;
+
+ QVector<QSGNode *> m_expandedRows;
+ QVector<QSGNode *> m_collapsedRows;
+ const QVector<QSGNode *> &expandedRows() const { return m_expandedRows; }
+ const QVector<QSGNode *> &collapsedRows() const { return m_collapsedRows; }
+};
+
+struct OpaqueColoredPoint2DWithSize {
+ float x, y, w, h, id;
+ unsigned char r, g, b, a;
+ void set(float nx, float ny, float nw, float nh, float nid, uchar nr, uchar ng, uchar nb);
+};
+
+struct TimelineItemsGeometry {
+ // Alternating nodes with with 7 and 4 vertices; and vertex indices are 16bit
+ static const int maxEventsPerNode = 0xffff * 2 / (7 + 4);
+
+ static const QSGGeometry::AttributeSet &opaqueColoredPoint2DWithSize();
+
+ TimelineItemsGeometry() : allocatedVertices(0), usedVertices(0), node(0) {
+ prevNode.set(0, TimelineModel::defaultRowHeight(), 0, 0, 0, 0, 0, 0);
+ }
+
+ uint allocatedVertices;
+ uint usedVertices;
+
+ OpaqueColoredPoint2DWithSize prevNode;
+
+ QSGGeometryNode *node;
+ OpaqueColoredPoint2DWithSize *vertexData();
+
+ void allocate(QSGMaterial *material);
+ void addVertices(float itemTop);
+ void addEvent(float itemLeft, float itemTop, float itemWidth, float selectionId, uchar red,
+ uchar green, uchar blue);
+};
+
+void TimelineItemsGeometry::addEvent(float itemLeft, float itemTop, float itemWidth,
+ float selectionId, uchar red, uchar green,
+ uchar blue)
+{
+ float rowHeight = TimelineModel::defaultRowHeight();
+ float itemHeight = rowHeight - itemTop;
+ OpaqueColoredPoint2DWithSize *v = vertexData();
+ if (prevNode.y == rowHeight) {
+ // "Z" form, bottom to top
+ v[usedVertices++].set(itemLeft, rowHeight, -itemWidth, -itemHeight, selectionId, red, green,
+ blue);
+ v[usedVertices++].set(itemLeft + itemWidth, rowHeight, itemWidth, -itemHeight, selectionId,
+ red, green, blue);
+ v[usedVertices++].set(itemLeft, itemTop, -itemWidth, itemHeight, selectionId, red, green,
+ blue);
+ v[usedVertices++].set(itemLeft + itemWidth, itemTop, itemWidth, itemHeight, selectionId,
+ red, green, blue);
+ prevNode = v[usedVertices - 1];
+ } else {
+ if (prevNode.y != itemTop) {
+ // 2 extra vertices to degenerate the surplus triangles
+ v[usedVertices++] = prevNode;
+ v[usedVertices++].set(itemLeft, itemTop, -itemWidth, itemHeight, selectionId, red,
+ green, blue);
+ }
+ // "Z" form, top to bottom
+ v[usedVertices++].set(itemLeft, itemTop, -itemWidth, itemHeight, selectionId, red, green,
+ blue);
+ v[usedVertices++].set(itemLeft + itemWidth, itemTop, itemWidth, itemHeight, selectionId,
+ red, green, blue);
+ v[usedVertices++].set(itemLeft, rowHeight, - itemWidth, -itemHeight, selectionId, red,
+ green, blue);
+ v[usedVertices++].set(itemLeft + itemWidth, rowHeight, itemWidth, -itemHeight, selectionId,
+ red, green, blue);
+ prevNode = v[usedVertices - 1];
+ }
+
+
+}
+
+OpaqueColoredPoint2DWithSize *TimelineItemsGeometry::vertexData()
+{
+ QSGGeometry *geometry = node->geometry();
+ Q_ASSERT(geometry->attributeCount() == 4);
+ Q_ASSERT(geometry->sizeOfVertex() == sizeof(OpaqueColoredPoint2DWithSize));
+ const QSGGeometry::Attribute *attributes = geometry->attributes();
+ Q_ASSERT(attributes[0].position == 0);
+ Q_ASSERT(attributes[0].tupleSize == 2);
+ Q_ASSERT(attributes[0].type == GL_FLOAT);
+ Q_ASSERT(attributes[1].position == 1);
+ Q_ASSERT(attributes[1].tupleSize == 2);
+ Q_ASSERT(attributes[1].type == GL_FLOAT);
+ Q_ASSERT(attributes[2].position == 2);
+ Q_ASSERT(attributes[2].tupleSize == 1);
+ Q_ASSERT(attributes[2].type == GL_FLOAT);
+ Q_ASSERT(attributes[3].position == 3);
+ Q_ASSERT(attributes[3].tupleSize == 4);
+ Q_ASSERT(attributes[3].type == GL_UNSIGNED_BYTE);
+ Q_UNUSED(attributes);
+ return static_cast<OpaqueColoredPoint2DWithSize *>(node->geometry()->vertexData());
+}
+
+void TimelineItemsGeometry::allocate(QSGMaterial *material)
+{
+ QSGGeometry *geometry = new QSGGeometry(opaqueColoredPoint2DWithSize(), usedVertices);
+ geometry->setIndexDataPattern(QSGGeometry::StaticPattern);
+ geometry->setVertexDataPattern(QSGGeometry::StaticPattern);
+ node = new QSGGeometryNode;
+ node->setGeometry(geometry);
+ node->setFlag(QSGNode::OwnsGeometry, true);
+ node->setMaterial(material);
+ allocatedVertices = usedVertices;
+ usedVertices = 0;
+ prevNode.set(0, TimelineModel::defaultRowHeight(), 0, 0, 0, 0, 0, 0);
+}
+
+void TimelineItemsGeometry::addVertices(float itemTop)
+{
+ if (prevNode.y == TimelineModel::defaultRowHeight()) {
+ usedVertices += 4;
+ prevNode.y = itemTop;
+ } else {
+ usedVertices += (prevNode.y != itemTop ? 6 : 4);
+ prevNode.y = TimelineModel::defaultRowHeight();
+ }
+}
+
+class TimelineExpandedRowNode : public QSGNode {
+public:
+ TimelineItemsMaterial material;
+ virtual ~TimelineExpandedRowNode() {}
+};
+
+static void updateNodes(int from, int to, const TimelineModel *model,
+ const TimelineRenderState *parentState, TimelineItemsRenderPassState *state)
+{
+ float defaultRowHeight = TimelineModel::defaultRowHeight();
+
+ QVector<TimelineItemsGeometry> expandedPerRow(model->expandedRowCount());
+ QVector<TimelineItemsGeometry> collapsedPerRow(model->collapsedRowCount());
+
+ for (int i = from; i < to; ++i) {
+ qint64 start = qMax(parentState->start(), model->startTime(i));
+ qint64 end = qMin(parentState->end(), model->startTime(i) + model->duration(i));
+ if (start >= end)
+ continue;
+
+ float itemTop = (1.0 - model->relativeHeight(i)) * defaultRowHeight;
+ expandedPerRow[model->expandedRow(i)].addVertices(itemTop);
+ collapsedPerRow[model->collapsedRow(i)].addVertices(itemTop);
+ }
+
+ for (int i = 0; i < model->expandedRowCount(); ++i) {
+ TimelineItemsGeometry &row = expandedPerRow[i];
+ if (row.usedVertices > 0) {
+ row.allocate(&static_cast<TimelineExpandedRowNode *>(
+ state->m_expandedRows[i])->material);
+ state->m_expandedRows[i]->appendChildNode(row.node);
+ }
+ }
+
+ for (int i = 0; i < model->collapsedRowCount(); ++i) {
+ TimelineItemsGeometry &row = collapsedPerRow[i];
+ if (row.usedVertices > 0) {
+ row.allocate(&state->collapsedRowMaterial);
+ state->m_collapsedRows[i]->appendChildNode(row.node);
+ }
+ }
+
+ for (int i = from; i < to; ++i) {
+ qint64 start = qMax(parentState->start(), model->startTime(i));
+ qint64 end = qMin(parentState->end(), model->startTime(i) + model->duration(i));
+ if (start >= end)
+ continue;
+
+ QColor color = model->color(i);
+ uchar red = color.red();
+ uchar green = color.green();
+ uchar blue = color.blue();
+
+ float itemWidth = (end - start) * parentState->scale();
+ float itemLeft = (start - parentState->start()) * parentState->scale();
+
+ // This has to be the exact same expression as above, to guarantee determinism.
+ float itemTop = (1.0 - model->relativeHeight(i)) * defaultRowHeight;
+ float selectionId = model->selectionId(i);
+
+ expandedPerRow[model->expandedRow(i)].addEvent(itemLeft, itemTop, itemWidth, selectionId,
+ red, green, blue);
+ collapsedPerRow[model->collapsedRow(i)].addEvent(itemLeft, itemTop, itemWidth, selectionId,
+ red, green, blue);
+ }
+}
+
+const QSGGeometry::AttributeSet &TimelineItemsGeometry::opaqueColoredPoint2DWithSize()
+{
+ static QSGGeometry::Attribute data[] = {
+ QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true),
+ QSGGeometry::Attribute::create(1, 2, GL_FLOAT),
+ QSGGeometry::Attribute::create(2, 1, GL_FLOAT),
+ QSGGeometry::Attribute::create(3, 4, GL_UNSIGNED_BYTE)
+ };
+ static QSGGeometry::AttributeSet attrs = {
+ 4,
+ sizeof(OpaqueColoredPoint2DWithSize),
+ data
+ };
+ return attrs;
+}
+
+const TimelineItemsRenderPass *TimelineItemsRenderPass::instance()
+{
+ static const TimelineItemsRenderPass pass;
+ return &pass;
+}
+
+TimelineRenderPass::State *TimelineItemsRenderPass::update(const TimelineAbstractRenderer *renderer,
+ const TimelineRenderState *parentState,
+ State *oldState, int indexFrom,
+ int indexTo, bool stateChanged,
+ qreal spacing) const
+{
+ Q_UNUSED(stateChanged);
+ const TimelineModel *model = renderer->model();
+ if (!model || indexFrom < 0 || indexTo > model->count() || indexFrom >= indexTo)
+ return oldState;
+
+ QColor selectionColor = (renderer->selectionLocked() ? QColor(96,0,255) :
+ QColor(Qt::blue)).lighter(130);
+
+ TimelineItemsRenderPassState *state;
+ if (oldState == 0)
+ state = new TimelineItemsRenderPassState;
+ else
+ state = static_cast<TimelineItemsRenderPassState *>(oldState);
+
+
+ float selectedItem = renderer->selectedItem() == -1 ? -1 :
+ model->selectionId(renderer->selectedItem());
+
+ state->collapsedRowMaterial.setScale(QVector2D(spacing / parentState->scale(), 1));
+ state->collapsedRowMaterial.setSelectedItem(selectedItem);
+ state->collapsedRowMaterial.setSelectionColor(selectionColor);
+
+ if (state->m_expandedRows.isEmpty()) {
+ state->m_expandedRows.reserve(model->expandedRowCount());
+ state->m_collapsedRows.reserve(model->collapsedRowCount());
+ for (int i = 0; i < model->expandedRowCount(); ++i)
+ state->m_expandedRows << new TimelineExpandedRowNode;
+ for (int i = 0; i < model->collapsedRowCount(); ++i)
+ state->m_collapsedRows << new QSGNode;
+ }
+
+ if (state->indexFrom < state->indexTo) {
+ if (indexFrom < state->indexFrom) {
+ for (int i = indexFrom; i < state->indexFrom;
+ i+= TimelineItemsGeometry::maxEventsPerNode)
+ updateNodes(i, qMin(i + TimelineItemsGeometry::maxEventsPerNode, state->indexFrom),
+ model, parentState, state);
+ }
+ if (indexTo > state->indexTo) {
+ for (int i = state->indexTo; i < indexTo; i+= TimelineItemsGeometry::maxEventsPerNode)
+ updateNodes(i, qMin(i + TimelineItemsGeometry::maxEventsPerNode, indexTo), model,
+ parentState, state);
+ }
+ } else {
+ for (int i = indexFrom; i < indexTo; i+= TimelineItemsGeometry::maxEventsPerNode)
+ updateNodes(i, qMin(i + TimelineItemsGeometry::maxEventsPerNode, indexTo), model,
+ parentState, state);
+ }
+
+ if (model->expanded()) {
+ for (int row = 0; row < model->expandedRowCount(); ++row) {
+ TimelineExpandedRowNode *rowNode = static_cast<TimelineExpandedRowNode *>(
+ state->m_expandedRows[row]);
+ rowNode->material.setScale(
+ QVector2D(spacing / parentState->scale(),
+ static_cast<qreal>(model->expandedRowHeight(row))) /
+ static_cast<qreal>(TimelineModel::defaultRowHeight()));
+ rowNode->material.setSelectedItem(selectedItem);
+ rowNode->material.setSelectionColor(selectionColor);
+ }
+ }
+
+ state->indexFrom = qMin(state->indexFrom, indexFrom);
+ state->indexTo = qMax(state->indexTo, indexTo);
+ return state;
+}
+
+TimelineItemsRenderPass::TimelineItemsRenderPass()
+{
+}
+
+class TimelineItemsMaterialShader : public QSGMaterialShader
+{
+public:
+ TimelineItemsMaterialShader();
+
+ virtual void updateState(const RenderState &state, QSGMaterial *newEffect,
+ QSGMaterial *oldEffect);
+ virtual char const *const *attributeNames() const;
+
+private:
+ virtual void initialize();
+
+ int m_matrix_id;
+ int m_scale_id;
+ int m_selection_color_id;
+ int m_selected_item_id;
+ int m_z_range_id;
+};
+
+TimelineItemsMaterialShader::TimelineItemsMaterialShader()
+ : QSGMaterialShader()
+{
+ setShaderSourceFile(QOpenGLShader::Vertex, QStringLiteral(":/timeline/timelineitems.vert"));
+ setShaderSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/timeline/timelineitems.frag"));
+}
+
+void TimelineItemsMaterialShader::updateState(const RenderState &state, QSGMaterial *newMaterial,
+ QSGMaterial *)
+{
+ if (state.isMatrixDirty()) {
+ TimelineItemsMaterial *material = static_cast<TimelineItemsMaterial *>(newMaterial);
+ program()->setUniformValue(m_matrix_id, state.combinedMatrix());
+ program()->setUniformValue(m_scale_id, material->scale());
+ program()->setUniformValue(m_selection_color_id, material->selectionColor());
+ program()->setUniformValue(m_selected_item_id, material->selectedItem());
+ program()->setUniformValue(m_z_range_id, GLfloat(1.0));
+ }
+}
+
+char const *const *TimelineItemsMaterialShader::attributeNames() const
+{
+ static const char *const attr[] = {"vertexCoord", "rectSize", "selectionId", "vertexColor", 0};
+ return attr;
+}
+
+void TimelineItemsMaterialShader::initialize()
+{
+ m_matrix_id = program()->uniformLocation("matrix");
+ m_scale_id = program()->uniformLocation("scale");
+ m_selection_color_id = program()->uniformLocation("selectionColor");
+ m_selected_item_id = program()->uniformLocation("selectedItem");
+ m_z_range_id = program()->uniformLocation("_qt_zRange");
+}
+
+
+TimelineItemsMaterial::TimelineItemsMaterial() : m_selectedItem(-1)
+{
+ setFlag(QSGMaterial::Blending, false);
+}
+
+QVector2D TimelineItemsMaterial::scale() const
+{
+ return m_scale;
+}
+
+void TimelineItemsMaterial::setScale(QVector2D scale)
+{
+ m_scale = scale;
+}
+
+float TimelineItemsMaterial::selectedItem() const
+{
+ return m_selectedItem;
+}
+
+void TimelineItemsMaterial::setSelectedItem(float selectedItem)
+{
+ m_selectedItem = selectedItem;
+}
+
+QColor TimelineItemsMaterial::selectionColor() const
+{
+ return m_selectionColor;
+}
+
+void TimelineItemsMaterial::setSelectionColor(QColor selectionColor)
+{
+ m_selectionColor = selectionColor;
+}
+
+QSGMaterialType *TimelineItemsMaterial::type() const
+{
+ static QSGMaterialType type;
+ return &type;
+}
+
+QSGMaterialShader *TimelineItemsMaterial::createShader() const
+{
+ return new TimelineItemsMaterialShader;
+}
+
+void OpaqueColoredPoint2DWithSize::set(float nx, float ny, float nw, float nh, float nid,
+ uchar nr, uchar ng, uchar nb) {
+ x = nx; y = ny; w = nw; h = nh; id = nid;
+ r = nr; g = ng, b = nb; a = 255;
+}
+
+} // namespace Timeline
diff --git a/src/libs/timeline/timelineitemsrenderpass.h b/src/libs/timeline/timelineitemsrenderpass.h
new file mode 100644
index 00000000000..9f7d4a2b8b9
--- /dev/null
+++ b/src/libs/timeline/timelineitemsrenderpass.h
@@ -0,0 +1,53 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEITEMSRENDERPASS_H
+#define TIMELINEITEMSRENDERPASS_H
+
+#include "timelineabstractrenderer.h"
+#include "timelinerenderpass.h"
+#include <QSGMaterial>
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineItemsRenderPass : public TimelineRenderPass
+{
+public:
+ static const TimelineItemsRenderPass *instance();
+ State *update(const TimelineAbstractRenderer *renderer, const TimelineRenderState *parentState,
+ State *state, int firstIndex, int lastIndex, bool stateChanged,
+ qreal spacing) const;
+protected:
+ TimelineItemsRenderPass();
+};
+
+} // namespace Timeline
+
+#endif // TIMELINEITEMSRENDERPASS_H
diff --git a/src/libs/timeline/timelinemodel.cpp b/src/libs/timeline/timelinemodel.cpp
new file mode 100644
index 00000000000..099492114c2
--- /dev/null
+++ b/src/libs/timeline/timelinemodel.cpp
@@ -0,0 +1,664 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinemodel.h"
+#include "timelinemodel_p.h"
+#include "timelineitemsrenderpass.h"
+#include "timelineselectionrenderpass.h"
+#include "timelinenotesrenderpass.h"
+
+#include <utils/qtcassert.h>
+#include <QLinkedList>
+
+namespace Timeline {
+
+/*!
+ \class Timeline::TimelineModel
+ \brief The TimelineModel class provides a sorted model for timeline data.
+
+ The TimelineModel lets you keep range data sorted by both start and end times, so that
+ visible ranges can easily be computed. The only precondition for that to work is that the ranges
+ must be perfectly nested. A "parent" range of a range R is defined as a range for which the
+ start time is earlier than R's start time and the end time is later than R's end time. A set
+ of ranges is perfectly nested if all parent ranges of any given range have a common parent
+ range. Mind that you can always make that happen by defining a range that spans the whole
+ available time span. That, however, will make any code that uses firstIndex() and lastIndex()
+ for selecting subsets of the model always select all of it.
+
+ \note Indices returned from the various methods are only valid until a new range is inserted
+ before them. Inserting a new range before a given index moves the range pointed to by the
+ index by one. Incrementing the index by one will make it point to the item again.
+*/
+
+/*!
+ Compute all ranges' parents.
+ \sa firstIndex()
+*/
+void TimelineModel::computeNesting()
+{
+ Q_D(TimelineModel);
+ QLinkedList<int> parents;
+ for (int range = 0; range != count(); ++range) {
+ TimelineModelPrivate::Range &current = d->ranges[range];
+ for (QLinkedList<int>::iterator parentIt = parents.begin();;) {
+ if (parentIt == parents.end()) {
+ parents.append(range);
+ break;
+ }
+
+ TimelineModelPrivate::Range &parent = d->ranges[*parentIt];
+ qint64 parentEnd = parent.start + parent.duration;
+ if (parentEnd < current.start) {
+ // We've completely passed the parent. Remove it.
+ parentIt = parents.erase(parentIt);
+ } else if (parentEnd >= current.start + current.duration) {
+ // Current range is completely inside the parent range: no need to insert
+ current.parent = (parent.parent == -1 ? *parentIt : parent.parent);
+ break;
+ } else if (parent.start == current.start) {
+ // The parent range starts at the same time but ends before the current range.
+ // We could switch them but that would violate the order requirements. When
+ // searching for ranges between two timestamps we'd skip the ranges between the
+ // current range and the parent range if the start timestamp points into the parent
+ // range. firstIndex() would then return the current range, which has an id greater
+ // than the parent. The parent could not be found then. To deal with this corner
+ // case, we assign the parent the "wrong" way around, so that on firstIndex() we
+ // always end up with the smallest id of any ranges starting at the same time.
+
+ // The other way to deal with this would be fixing up the ordering on insert. In
+ // fact we do that on insertStart().
+ // However, in order to rely on this we would also have to move the start index if
+ // on insertEnd() it turns out that the range just being ended is shorter than a
+ // previous one starting at the same time. We don't want to do that as client code
+ // could not find out about the changes in the IDs for range starts then.
+
+ current.parent = *parentIt;
+ parents.append(range);
+ break;
+ } else {
+ ++parentIt;
+ }
+ }
+ }
+}
+
+int TimelineModel::collapsedRowCount() const
+{
+ Q_D(const TimelineModel);
+ return d->collapsedRowCount;
+}
+
+void TimelineModel::setCollapsedRowCount(int rows)
+{
+ Q_D(TimelineModel);
+ if (d->collapsedRowCount != rows) {
+ d->collapsedRowCount = rows;
+ emit collapsedRowCountChanged();
+ if (!d->expanded)
+ emit rowCountChanged();
+ }
+}
+
+int TimelineModel::expandedRowCount() const
+{
+ Q_D(const TimelineModel);
+ return d->expandedRowCount;
+}
+
+void TimelineModel::setExpandedRowCount(int rows)
+{
+ Q_D(TimelineModel);
+ if (d->expandedRowCount != rows) {
+ d->expandedRowCount = rows;
+ emit expandedRowCountChanged();
+ if (d->expanded)
+ emit rowCountChanged();
+ }
+}
+
+int TimelineModel::row(int index) const
+{
+ return expanded() ? expandedRow(index) : collapsedRow(index);
+}
+
+TimelineModel::TimelineModelPrivate::TimelineModelPrivate(int modelId, const QString &displayName) :
+ modelId(modelId), displayName(displayName), expanded(false), hidden(false),
+ expandedRowCount(1), collapsedRowCount(1), q_ptr(0)
+{
+}
+
+void TimelineModel::TimelineModelPrivate::init(TimelineModel *q)
+{
+ q_ptr = q;
+ connect(q,SIGNAL(expandedChanged()),q,SIGNAL(heightChanged()));
+ connect(q,SIGNAL(hiddenChanged()),q,SIGNAL(heightChanged()));
+ connect(q,SIGNAL(emptyChanged()),q,SIGNAL(heightChanged()));
+}
+
+
+TimelineModel::TimelineModel(TimelineModelPrivate &dd, QObject *parent) :
+ QObject(parent), d_ptr(&dd)
+{
+ d_ptr->init(this);
+}
+
+TimelineModel::TimelineModel(int modelId, const QString &displayName, QObject *parent) :
+ QObject(parent), d_ptr(new TimelineModelPrivate(modelId, displayName))
+{
+ d_ptr->init(this);
+}
+
+TimelineModel::~TimelineModel()
+{
+ Q_D(TimelineModel);
+ delete d;
+}
+
+bool TimelineModel::isEmpty() const
+{
+ return count() == 0;
+}
+
+int TimelineModel::modelId() const
+{
+ Q_D(const TimelineModel);
+ return d->modelId;
+}
+
+int TimelineModel::collapsedRowHeight(int rowNumber) const
+{
+ Q_UNUSED(rowNumber);
+ return TimelineModelPrivate::DefaultRowHeight;
+}
+
+int TimelineModel::collapsedRowOffset(int rowNumber) const
+{
+ return rowNumber * TimelineModelPrivate::DefaultRowHeight;
+}
+
+int TimelineModel::expandedRowHeight(int rowNumber) const
+{
+ Q_D(const TimelineModel);
+ if (d->rowOffsets.size() > rowNumber)
+ return d->rowOffsets[rowNumber] - (rowNumber > 0 ? d->rowOffsets[rowNumber - 1] : 0);
+ return TimelineModelPrivate::DefaultRowHeight;
+}
+
+int TimelineModel::expandedRowOffset(int rowNumber) const
+{
+ Q_D(const TimelineModel);
+ if (rowNumber == 0)
+ return 0;
+
+ if (d->rowOffsets.size() >= rowNumber)
+ return d->rowOffsets[rowNumber - 1];
+ if (!d->rowOffsets.empty())
+ return d->rowOffsets.last() + (rowNumber - d->rowOffsets.size()) *
+ TimelineModelPrivate::DefaultRowHeight;
+ return rowNumber * TimelineModelPrivate::DefaultRowHeight;
+}
+
+void TimelineModel::setExpandedRowHeight(int rowNumber, int height)
+{
+ Q_D(TimelineModel);
+ if (height < TimelineModelPrivate::DefaultRowHeight)
+ height = TimelineModelPrivate::DefaultRowHeight;
+
+ int nextOffset = d->rowOffsets.empty() ? 0 : d->rowOffsets.last();
+ while (d->rowOffsets.size() <= rowNumber)
+ d->rowOffsets << (nextOffset += TimelineModelPrivate::DefaultRowHeight);
+ int difference = height - d->rowOffsets[rowNumber] +
+ (rowNumber > 0 ? d->rowOffsets[rowNumber - 1] : 0);
+ if (difference != 0) {
+ for (int offsetRow = rowNumber; offsetRow < d->rowOffsets.size(); ++offsetRow) {
+ d->rowOffsets[offsetRow] += difference;
+ }
+ emit expandedRowHeightChanged(rowNumber, height);
+ if (d->expanded)
+ emit heightChanged();
+ }
+}
+
+int TimelineModel::rowOffset(int rowNumber) const
+{
+ return expanded() ? expandedRowOffset(rowNumber) : collapsedRowOffset(rowNumber);
+}
+
+int TimelineModel::rowHeight(int rowNumber) const
+{
+ return expanded() ? expandedRowHeight(rowNumber) : collapsedRowHeight(rowNumber);
+}
+
+int TimelineModel::height() const
+{
+ Q_D(const TimelineModel);
+ if (d->hidden || isEmpty())
+ return 0;
+
+ if (!d->expanded)
+ return collapsedRowCount() * TimelineModelPrivate::DefaultRowHeight;
+ if (d->rowOffsets.empty())
+ return expandedRowCount() * TimelineModelPrivate::DefaultRowHeight;
+
+ return d->rowOffsets.last() + (expandedRowCount() - d->rowOffsets.size()) *
+ TimelineModelPrivate::DefaultRowHeight;
+}
+
+/*!
+ Returns the number of ranges in the model.
+*/
+int TimelineModel::count() const
+{
+ Q_D(const TimelineModel);
+ return d->ranges.count();
+}
+
+qint64 TimelineModel::duration(int index) const
+{
+ Q_D(const TimelineModel);
+ return d->ranges[index].duration;
+}
+
+qint64 TimelineModel::startTime(int index) const
+{
+ Q_D(const TimelineModel);
+ return d->ranges[index].start;
+}
+
+qint64 TimelineModel::endTime(int index) const
+{
+ Q_D(const TimelineModel);
+ return d->ranges[index].start + d->ranges[index].duration;
+}
+
+/*!
+ Returns the type ID of the event with event ID \a index. The type ID is a globally valid ID
+ which can be used to communicate meta information about events to other parts of the program. By
+ default it is -1, which means there is no global type information about the event.
+ */
+int TimelineModel::typeId(int index) const
+{
+ Q_UNUSED(index)
+ return -1;
+}
+
+/*!
+ Looks up the first range with an end time later than the given time and
+ returns its parent's index. If no such range is found, it returns -1. If there
+ is no parent, it returns the found range's index. The parent of a range is the
+ range with the earliest start time that completely covers the child range.
+ "Completely covers" means:
+ parent.startTime <= child.startTime && parent.endTime >= child.endTime
+*/
+int TimelineModel::firstIndex(qint64 startTime) const
+{
+ Q_D(const TimelineModel);
+ int index = d->firstIndexNoParents(startTime);
+ if (index == -1)
+ return -1;
+ int parent = d->ranges[index].parent;
+ return parent == -1 ? index : parent;
+}
+
+/*!
+ Of all indexes of ranges starting at the same time as the first range with an end time later
+ than the specified \a startTime returns the lowest one. If no such range is found, it returns
+ -1.
+*/
+int TimelineModel::TimelineModelPrivate::firstIndexNoParents(qint64 startTime) const
+{
+ // in the "endtime" list, find the first event that ends after startTime
+ if (endTimes.isEmpty())
+ return -1;
+ if (endTimes.count() == 1 || endTimes.first().end > startTime)
+ return endTimes.first().startIndex;
+ if (endTimes.last().end <= startTime)
+ return -1;
+
+ return endTimes[lowerBound(endTimes, startTime) + 1].startIndex;
+}
+
+/*!
+ Looks up the last range with a start time earlier than the specified \a endTime and
+ returns its index. If no such range is found, it returns -1.
+*/
+int TimelineModel::lastIndex(qint64 endTime) const
+{
+ Q_D(const TimelineModel);
+ // in the "starttime" list, find the last event that starts before endtime
+ if (d->ranges.isEmpty() || d->ranges.first().start >= endTime)
+ return -1;
+ if (d->ranges.count() == 1)
+ return 0;
+ if (d->ranges.last().start < endTime)
+ return d->ranges.count() - 1;
+
+ return d->lowerBound(d->ranges, endTime);
+}
+
+QVariantMap TimelineModel::location(int index) const
+{
+ Q_UNUSED(index);
+ QVariantMap map;
+ return map;
+}
+
+/*!
+ Returns \c true if this model can contain events of global type ID \a typeIndex. Otherwise
+ returns \c false. The base model does not know anything about type IDs and always returns
+ \c false. You should override this method if you implement \l typeId().
+ */
+bool TimelineModel::handlesTypeId(int typeIndex) const
+{
+ Q_UNUSED(typeIndex);
+ return false;
+}
+
+int TimelineModel::selectionIdForLocation(const QString &filename, int line, int column) const
+{
+ Q_UNUSED(filename);
+ Q_UNUSED(line);
+ Q_UNUSED(column);
+ return -1;
+}
+
+float TimelineModel::relativeHeight(int index) const
+{
+ Q_UNUSED(index);
+ return 1.0f;
+}
+
+int TimelineModel::rowMinValue(int rowNumber) const
+{
+ Q_UNUSED(rowNumber);
+ return 0;
+}
+
+int TimelineModel::rowMaxValue(int rowNumber) const
+{
+ Q_UNUSED(rowNumber);
+ return 0;
+}
+
+int TimelineModel::defaultRowHeight()
+{
+ return TimelineModelPrivate::DefaultRowHeight;
+}
+
+QList<const TimelineRenderPass *> TimelineModel::supportedRenderPasses() const
+{
+ QList<const TimelineRenderPass *> passes;
+ passes << TimelineItemsRenderPass::instance()
+ << TimelineSelectionRenderPass::instance()
+ << TimelineNotesRenderPass::instance();
+ return passes;
+}
+
+QColor TimelineModel::colorBySelectionId(int index) const
+{
+ return colorByHue(selectionId(index) * TimelineModelPrivate::SelectionIdHueMultiplier);
+}
+
+QColor TimelineModel::colorByFraction(double fraction) const
+{
+ return colorByHue(fraction * TimelineModelPrivate::FractionHueMultiplier +
+ TimelineModelPrivate::FractionHueMininimum);
+}
+
+QColor TimelineModel::colorByHue(int hue) const
+{
+ return QColor::fromHsl(hue % 360, TimelineModelPrivate::Saturation,
+ TimelineModelPrivate::Lightness);
+}
+
+/*!
+ Inserts the range defined by \a duration and \a selectionId at the specified \a startTime and
+ returns its index. The \a selectionId determines the selection group the new event belongs to.
+ \sa selectionId()
+*/
+int TimelineModel::insert(qint64 startTime, qint64 duration, int selectionId)
+{
+ Q_D(TimelineModel);
+ /* Doing insert-sort here is preferable as most of the time the times will actually be
+ * presorted in the right way. So usually this will just result in appending. */
+ int index = d->insertStart(TimelineModelPrivate::Range(startTime, duration, selectionId));
+ if (index < d->ranges.size() - 1)
+ d->incrementStartIndices(index);
+ d->insertEnd(TimelineModelPrivate::RangeEnd(index, startTime + duration));
+ return index;
+}
+
+/*!
+ Inserts the specified \a selectionId as range start at the specified \a startTime and returns
+ its index. The range end is not set. The \a selectionId determines the selection group the new
+ event belongs to.
+ \sa selectionId()
+*/
+int TimelineModel::insertStart(qint64 startTime, int selectionId)
+{
+ Q_D(TimelineModel);
+ int index = d->insertStart(TimelineModelPrivate::Range(startTime, 0, selectionId));
+ if (index < d->ranges.size() - 1)
+ d->incrementStartIndices(index);
+ return index;
+}
+
+/*!
+ Adds the range \a duration at the specified start \a index.
+*/
+void TimelineModel::insertEnd(int index, qint64 duration)
+{
+ Q_D(TimelineModel);
+ d->ranges[index].duration = duration;
+ d->insertEnd(TimelineModelPrivate::RangeEnd(index, d->ranges[index].start + duration));
+}
+
+bool TimelineModel::expanded() const
+{
+ Q_D(const TimelineModel);
+ return d->expanded;
+}
+
+void TimelineModel::setExpanded(bool expanded)
+{
+ Q_D(TimelineModel);
+ if (expanded != d->expanded) {
+ d->expanded = expanded;
+ emit expandedChanged();
+ if (d->collapsedRowCount != d->expandedRowCount)
+ emit rowCountChanged();
+ }
+}
+
+bool TimelineModel::hidden() const
+{
+ Q_D(const TimelineModel);
+ return d->hidden;
+}
+
+void TimelineModel::setHidden(bool hidden)
+{
+ Q_D(TimelineModel);
+ if (hidden != d->hidden) {
+ d->hidden = hidden;
+ emit hiddenChanged();
+ }
+}
+
+QString TimelineModel::displayName() const
+{
+ Q_D(const TimelineModel);
+ return d->displayName;
+}
+
+int TimelineModel::rowCount() const
+{
+ Q_D(const TimelineModel);
+ return d->expanded ? d->expandedRowCount : d->collapsedRowCount;
+}
+
+QColor TimelineModel::color(int index) const
+{
+ Q_UNUSED(index);
+ return QColor();
+}
+
+QVariantList TimelineModel::labels() const
+{
+ return QVariantList();
+}
+
+QVariantMap TimelineModel::details(int index) const
+{
+ Q_UNUSED(index);
+ return QVariantMap();
+}
+
+int TimelineModel::expandedRow(int index) const
+{
+ Q_UNUSED(index);
+ return 0;
+}
+
+int TimelineModel::collapsedRow(int index) const
+{
+ Q_UNUSED(index);
+ return 0;
+}
+
+/*!
+ Returns the ID of the selection group the event with event ID \a index belongs to. Selection
+ groups are local to the model and the model can arbitrarily assign events to selection groups
+ when inserting them.
+ If one event from a selection group is selected, all visible other events from the same
+ selection group are highlighted. Rows are expected to correspond to selection IDs when the view
+ is expanded.
+ */
+int TimelineModel::selectionId(int index) const
+{
+ Q_D(const TimelineModel);
+ return d->ranges[index].selectionId;
+}
+
+void TimelineModel::clear()
+{
+ Q_D(TimelineModel);
+ bool hadRowHeights = !d->rowOffsets.empty();
+ bool wasEmpty = isEmpty();
+ setExpandedRowCount(1);
+ setCollapsedRowCount(1);
+ setExpanded(false);
+ setHidden(false);
+ d->rowOffsets.clear();
+ d->ranges.clear();
+ d->endTimes.clear();
+ if (hadRowHeights)
+ emit expandedRowHeightChanged(-1, -1);
+ if (!wasEmpty)
+ emit emptyChanged();
+}
+
+int TimelineModel::nextItemBySelectionId(int selectionId, qint64 time, int currentItem) const
+{
+ Q_D(const TimelineModel);
+ return d->nextItemById(TimelineModelPrivate::SelectionId, selectionId, time, currentItem);
+}
+
+int TimelineModel::nextItemByTypeId(int typeId, qint64 time, int currentItem) const
+{
+ Q_D(const TimelineModel);
+ return d->nextItemById(TimelineModelPrivate::TypeId, typeId, time, currentItem);
+}
+
+int TimelineModel::prevItemBySelectionId(int selectionId, qint64 time, int currentItem) const
+{
+ Q_D(const TimelineModel);
+ return d->prevItemById(TimelineModelPrivate::SelectionId, selectionId, time, currentItem);
+}
+
+int TimelineModel::prevItemByTypeId(int typeId, qint64 time, int currentItem) const
+{
+ Q_D(const TimelineModel);
+ return d->prevItemById(TimelineModelPrivate::TypeId, typeId, time, currentItem);
+}
+
+int TimelineModel::TimelineModelPrivate::nextItemById(IdType idType, int id, qint64 time,
+ int currentItem) const
+{
+ Q_Q(const TimelineModel);
+ if (ranges.empty())
+ return -1;
+
+ int ndx = -1;
+ if (currentItem == -1)
+ ndx = firstIndexNoParents(time);
+ else
+ ndx = currentItem + 1;
+
+ if (ndx < 0 || ndx >= ranges.count())
+ ndx = 0;
+ int startIndex = ndx;
+ do {
+ if ((idType == TypeId && q->typeId(ndx) == id) ||
+ (idType == SelectionId && ranges[ndx].selectionId == id))
+ return ndx;
+ ndx = (ndx + 1) % ranges.count();
+ } while (ndx != startIndex);
+ return -1;
+}
+
+int TimelineModel::TimelineModelPrivate::prevItemById(IdType idType, int id, qint64 time,
+ int currentItem) const
+{
+ Q_Q(const TimelineModel);
+ if (ranges.empty())
+ return -1;
+
+ int ndx = -1;
+ if (currentItem == -1)
+ ndx = firstIndexNoParents(time);
+ else
+ ndx = currentItem - 1;
+ if (ndx < 0)
+ ndx = ranges.count() - 1;
+ int startIndex = ndx;
+ do {
+ if ((idType == TypeId && q->typeId(ndx) == id) ||
+ (idType == SelectionId && ranges[ndx].selectionId == id))
+ return ndx;
+ if (--ndx < 0)
+ ndx = ranges.count()-1;
+ } while (ndx != startIndex);
+ return -1;
+}
+
+} // namespace Timeline
+
+#include "moc_timelinemodel.cpp"
diff --git a/src/libs/timeline/timelinemodel.h b/src/libs/timeline/timelinemodel.h
new file mode 100644
index 00000000000..cc5b56f08d6
--- /dev/null
+++ b/src/libs/timeline/timelinemodel.h
@@ -0,0 +1,156 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEMODEL_H
+#define TIMELINEMODEL_H
+
+#include "timeline_global.h"
+#include "timelinerenderpass.h"
+#include <QVariant>
+#include <QColor>
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineModel : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int modelId READ modelId CONSTANT)
+ Q_PROPERTY(QString displayName READ displayName CONSTANT)
+ Q_PROPERTY(bool empty READ isEmpty NOTIFY emptyChanged)
+ Q_PROPERTY(bool hidden READ hidden WRITE setHidden NOTIFY hiddenChanged)
+ Q_PROPERTY(bool expanded READ expanded WRITE setExpanded NOTIFY expandedChanged)
+ Q_PROPERTY(int height READ height NOTIFY heightChanged)
+ Q_PROPERTY(int expandedRowCount READ expandedRowCount NOTIFY expandedRowCountChanged)
+ Q_PROPERTY(int collapsedRowCount READ collapsedRowCount NOTIFY collapsedRowCountChanged)
+ Q_PROPERTY(int rowCount READ rowCount NOTIFY rowCountChanged)
+ Q_PROPERTY(QVariantList labels READ labels NOTIFY labelsChanged)
+ Q_PROPERTY(int count READ count NOTIFY emptyChanged)
+ Q_PROPERTY(int defaultRowHeight READ defaultRowHeight CONSTANT)
+
+public:
+ class TimelineModelPrivate;
+
+ TimelineModel(int modelId, const QString &displayName, QObject *parent = 0);
+ ~TimelineModel();
+
+ // Methods implemented by the abstract model itself
+ bool isEmpty() const;
+ int modelId() const;
+
+ Q_INVOKABLE int collapsedRowHeight(int rowNumber) const;
+ Q_INVOKABLE int expandedRowHeight(int rowNumber) const;
+ Q_INVOKABLE int rowHeight(int rowNumber) const;
+ Q_INVOKABLE void setExpandedRowHeight(int rowNumber, int height);
+
+ Q_INVOKABLE int collapsedRowOffset(int rowNumber) const;
+ Q_INVOKABLE int expandedRowOffset(int rowNumber) const;
+ Q_INVOKABLE int rowOffset(int rowNumber) const;
+
+ int height() const;
+ int count() const;
+ Q_INVOKABLE qint64 duration(int index) const;
+ Q_INVOKABLE qint64 startTime(int index) const;
+ Q_INVOKABLE qint64 endTime(int index) const;
+ Q_INVOKABLE int selectionId(int index) const;
+
+ int firstIndex(qint64 startTime) const;
+ int lastIndex(qint64 endTime) const;
+
+ bool expanded() const;
+ bool hidden() const;
+ void setExpanded(bool expanded);
+ void setHidden(bool hidden);
+ QString displayName() const;
+ int expandedRowCount() const;
+ int collapsedRowCount() const;
+ int rowCount() const;
+
+ // Methods which can optionally be implemented by child models.
+ Q_INVOKABLE virtual QColor color(int index) const;
+ virtual QVariantList labels() const;
+ Q_INVOKABLE virtual QVariantMap details(int index) const;
+ Q_INVOKABLE virtual int expandedRow(int index) const;
+ Q_INVOKABLE virtual int collapsedRow(int index) const;
+ Q_INVOKABLE int row(int index) const;
+
+ // returned map should contain "file", "line", "column" properties, or be empty
+ Q_INVOKABLE virtual QVariantMap location(int index) const;
+ Q_INVOKABLE virtual int typeId(int index) const;
+ Q_INVOKABLE virtual bool handlesTypeId(int typeId) const;
+ Q_INVOKABLE virtual int selectionIdForLocation(const QString &filename, int line,
+ int column) const;
+ Q_INVOKABLE virtual float relativeHeight(int index) const;
+ Q_INVOKABLE virtual int rowMinValue(int rowNumber) const;
+ Q_INVOKABLE virtual int rowMaxValue(int rowNumber) const;
+
+ Q_INVOKABLE int nextItemBySelectionId(int selectionId, qint64 time, int currentItem) const;
+ Q_INVOKABLE int nextItemByTypeId(int typeId, qint64 time, int currentItem) const;
+ Q_INVOKABLE int prevItemBySelectionId(int selectionId, qint64 time, int currentItem) const;
+ Q_INVOKABLE int prevItemByTypeId(int typeId, qint64 time, int currentItem) const;
+
+ static int defaultRowHeight();
+ virtual QList<const TimelineRenderPass *> supportedRenderPasses() const;
+
+signals:
+ void expandedChanged();
+ void hiddenChanged();
+ void expandedRowHeightChanged(int row, int height);
+ void emptyChanged();
+ void heightChanged();
+ void expandedRowCountChanged();
+ void collapsedRowCountChanged();
+ void rowCountChanged();
+ void labelsChanged();
+
+protected:
+ QColor colorBySelectionId(int index) const;
+ QColor colorByFraction(double fraction) const;
+ QColor colorByHue(int hue) const;
+
+ int insert(qint64 startTime, qint64 duration, int selectionId);
+ int insertStart(qint64 startTime, int selectionId);
+ void insertEnd(int index, qint64 duration);
+ void computeNesting();
+
+ void setCollapsedRowCount(int rows);
+ void setExpandedRowCount(int rows);
+
+ virtual void clear();
+
+ explicit TimelineModel(TimelineModelPrivate &dd, QObject *parent);
+ TimelineModelPrivate *d_ptr;
+
+private:
+ Q_DECLARE_PRIVATE(TimelineModel)
+};
+
+} // namespace Timeline
+
+#endif // TIMELINEMODEL_H
diff --git a/src/libs/timeline/timelinemodel_p.h b/src/libs/timeline/timelinemodel_p.h
new file mode 100644
index 00000000000..fb8e9a7aeea
--- /dev/null
+++ b/src/libs/timeline/timelinemodel_p.h
@@ -0,0 +1,155 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEMODEL_P_H
+#define TIMELINEMODEL_P_H
+
+#include "timelinemodel.h"
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineModel::TimelineModelPrivate {
+public:
+ static const int DefaultRowHeight = 30;
+
+ enum IdType { SelectionId, TypeId };
+
+ enum BoxColorProperties {
+ SelectionIdHueMultiplier = 25,
+ FractionHueMultiplier = 96,
+ FractionHueMininimum = 10,
+ Saturation = 150,
+ Lightness = 166
+ };
+
+ struct Range {
+ Range() : start(-1), duration(-1), selectionId(-1), parent(-1) {}
+ Range(qint64 start, qint64 duration, int selectionId) :
+ start(start), duration(duration), selectionId(selectionId), parent(-1) {}
+ qint64 start;
+ qint64 duration;
+ int selectionId;
+ int parent;
+ inline qint64 timestamp() const {return start;}
+ };
+
+ struct RangeEnd {
+ RangeEnd() : startIndex(-1), end(-1) {}
+ RangeEnd(int startIndex, qint64 end) :
+ startIndex(startIndex), end(end) {}
+ int startIndex;
+ qint64 end;
+ inline qint64 timestamp() const {return end;}
+ };
+
+ TimelineModelPrivate(int modelId, const QString &displayName);
+ void init(TimelineModel *q);
+
+ int firstIndexNoParents(qint64 startTime) const;
+
+ void incrementStartIndices(int index)
+ {
+ for (int i = 0; i < endTimes.size(); ++i) {
+ if (endTimes[i].startIndex >= index)
+ endTimes[i].startIndex++;
+ }
+ }
+
+ inline int insertStart(const Range &start)
+ {
+ for (int i = ranges.count();;) {
+ if (i == 0) {
+ ranges.prepend(start);
+ return 0;
+ }
+ const Range &range = ranges[--i];
+ if (range.start < start.start || (range.start == start.start &&
+ range.duration >= start.duration)) {
+ ranges.insert(++i, start);
+ return i;
+ }
+ }
+ }
+
+ inline int insertEnd(const RangeEnd &end)
+ {
+ for (int i = endTimes.count();;) {
+ if (i == 0) {
+ endTimes.prepend(end);
+ return 0;
+ }
+ if (endTimes[--i].end <= end.end) {
+ endTimes.insert(++i, end);
+ return i;
+ }
+ }
+ }
+
+ template<typename RangeDelimiter>
+ static inline int lowerBound(const QVector<RangeDelimiter> &container, qint64 time)
+ {
+ int fromIndex = 0;
+ int toIndex = container.count() - 1;
+ while (toIndex - fromIndex > 1) {
+ int midIndex = (fromIndex + toIndex)/2;
+ if (container[midIndex].timestamp() < time)
+ fromIndex = midIndex;
+ else
+ toIndex = midIndex;
+ }
+
+ return fromIndex;
+ }
+
+ int prevItemById(IdType idType, int id, qint64 time, int currentSelected) const;
+ int nextItemById(IdType idType, int id, qint64 time, int currentSelected) const;
+
+ QVector<Range> ranges;
+ QVector<RangeEnd> endTimes;
+
+ QVector<int> rowOffsets;
+ const int modelId;
+ const QString displayName;
+
+ bool expanded;
+ bool hidden;
+ int expandedRowCount;
+ int collapsedRowCount;
+
+protected:
+ TimelineModel *q_ptr;
+
+private:
+ Q_DECLARE_PUBLIC(TimelineModel)
+};
+
+} // namespace Timeline
+
+#endif // TIMELINEMODEL_P_H
diff --git a/src/libs/timeline/timelinemodelaggregator.cpp b/src/libs/timeline/timelinemodelaggregator.cpp
new file mode 100644
index 00000000000..a01b70e3f69
--- /dev/null
+++ b/src/libs/timeline/timelinemodelaggregator.cpp
@@ -0,0 +1,230 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinemodel.h"
+#include "timelinenotesmodel.h"
+
+#include <QStringList>
+#include <QVariant>
+
+namespace Timeline {
+
+class TimelineModelAggregator::TimelineModelAggregatorPrivate {
+public:
+ TimelineModelAggregatorPrivate(TimelineModelAggregator *qq):q(qq) {}
+ ~TimelineModelAggregatorPrivate() {}
+
+ TimelineModelAggregator *q;
+
+ QList <TimelineModel *> modelList;
+ TimelineNotesModel *notesModel;
+};
+
+TimelineModelAggregator::TimelineModelAggregator(TimelineNotesModel *notes, QObject *parent)
+ : QObject(parent), d(new TimelineModelAggregatorPrivate(this))
+{
+ d->notesModel = notes;
+ connect(this, &TimelineModelAggregator::modelsChanged,
+ this, &TimelineModelAggregator::heightChanged);
+ connect(this, &TimelineModelAggregator::stateChanged,
+ this, &TimelineModelAggregator::heightChanged);
+}
+
+TimelineModelAggregator::~TimelineModelAggregator()
+{
+ delete d;
+}
+
+int TimelineModelAggregator::height() const
+{
+ return modelOffset(d->modelList.length());
+}
+
+void TimelineModelAggregator::addModel(TimelineModel *m)
+{
+ d->modelList << m;
+ connect(m,SIGNAL(heightChanged()),this,SIGNAL(heightChanged()));
+ if (d->notesModel)
+ d->notesModel->addTimelineModel(m);
+ emit modelsChanged();
+}
+
+const TimelineModel *TimelineModelAggregator::model(int modelIndex) const
+{
+ return d->modelList[modelIndex];
+}
+
+QVariantList TimelineModelAggregator::models() const
+{
+ QVariantList ret;
+ foreach (TimelineModel *model, d->modelList)
+ ret << QVariant::fromValue(model);
+ return ret;
+}
+
+TimelineNotesModel *TimelineModelAggregator::notes() const
+{
+ return d->notesModel;
+}
+
+void TimelineModelAggregator::clear()
+{
+ qDeleteAll(d->modelList);
+ d->modelList.clear();
+ if (d->notesModel)
+ d->notesModel->clear();
+ emit modelsChanged();
+}
+
+int TimelineModelAggregator::modelOffset(int modelIndex) const
+{
+ int ret = 0;
+ for (int i = 0; i < modelIndex; ++i)
+ ret += d->modelList[i]->height();
+ return ret;
+}
+
+int TimelineModelAggregator::modelCount() const
+{
+ return d->modelList.count();
+}
+
+QVariantMap TimelineModelAggregator::nextItem(int selectedModel, int selectedItem,
+ qint64 time) const
+{
+ if (selectedItem != -1)
+ time = model(selectedModel)->startTime(selectedItem);
+
+ QVarLengthArray<int> itemIndexes(modelCount());
+ for (int i = 0; i < modelCount(); i++) {
+ const TimelineModel *currentModel = model(i);
+ if (currentModel->count() > 0) {
+ if (selectedModel == i) {
+ itemIndexes[i] = (selectedItem + 1) % currentModel->count();
+ } else {
+ if (currentModel->startTime(0) > time)
+ itemIndexes[i] = 0;
+ else
+ itemIndexes[i] = (currentModel->lastIndex(time) + 1) % currentModel->count();
+ }
+ } else {
+ itemIndexes[i] = -1;
+ }
+ }
+
+ int candidateModelIndex = -1;
+ qint64 candidateStartTime = std::numeric_limits<qint64>::max();
+ for (int i = 0; i < modelCount(); i++) {
+ if (itemIndexes[i] == -1)
+ continue;
+ qint64 newStartTime = model(i)->startTime(itemIndexes[i]);
+ if (newStartTime > time && newStartTime < candidateStartTime) {
+ candidateStartTime = newStartTime;
+ candidateModelIndex = i;
+ }
+ }
+
+ int itemIndex;
+ if (candidateModelIndex != -1) {
+ itemIndex = itemIndexes[candidateModelIndex];
+ } else {
+ itemIndex = -1;
+ candidateStartTime = std::numeric_limits<qint64>::max();
+ for (int i = 0; i < modelCount(); i++) {
+ const TimelineModel *currentModel = model(i);
+ if (currentModel->count() > 0 && currentModel->startTime(0) < candidateStartTime) {
+ candidateModelIndex = i;
+ itemIndex = 0;
+ candidateStartTime = currentModel->startTime(0);
+ }
+ }
+ }
+
+ QVariantMap ret;
+ ret.insert(QLatin1String("model"), candidateModelIndex);
+ ret.insert(QLatin1String("item"), itemIndex);
+ return ret;
+}
+
+QVariantMap TimelineModelAggregator::prevItem(int selectedModel, int selectedItem,
+ qint64 time) const
+{
+ if (selectedItem != -1)
+ time = model(selectedModel)->startTime(selectedItem);
+
+ QVarLengthArray<int> itemIndexes(modelCount());
+ for (int i = 0; i < modelCount(); i++) {
+ if (selectedModel == i) {
+ itemIndexes[i] = selectedItem - 1;
+ if (itemIndexes[i] < 0)
+ itemIndexes[i] = model(selectedModel)->count() -1;
+ }
+ else
+ itemIndexes[i] = model(i)->lastIndex(time);
+ }
+
+ int candidateModelIndex = -1;
+ qint64 candidateStartTime = std::numeric_limits<qint64>::min();
+ for (int i = 0; i < modelCount(); i++) {
+ const TimelineModel *currentModel = model(i);
+ if (itemIndexes[i] == -1 || itemIndexes[i] >= currentModel->count())
+ continue;
+ qint64 newStartTime = currentModel->startTime(itemIndexes[i]);
+ if (newStartTime < time && newStartTime > candidateStartTime) {
+ candidateStartTime = newStartTime;
+ candidateModelIndex = i;
+ }
+ }
+
+ int itemIndex = -1;
+ if (candidateModelIndex != -1) {
+ itemIndex = itemIndexes[candidateModelIndex];
+ } else {
+ candidateStartTime = std::numeric_limits<qint64>::min();
+ for (int i = 0; i < modelCount(); i++) {
+ const TimelineModel *currentModel = model(i);
+ if (currentModel->count() > 0 &&
+ currentModel->startTime(currentModel->count() - 1) > candidateStartTime) {
+ candidateModelIndex = i;
+ itemIndex = currentModel->count() - 1;
+ candidateStartTime = currentModel->startTime(itemIndex);
+ }
+ }
+ }
+
+ QVariantMap ret;
+ ret.insert(QLatin1String("model"), candidateModelIndex);
+ ret.insert(QLatin1String("item"), itemIndex);
+ return ret;
+}
+
+} // namespace Timeline
diff --git a/src/libs/timeline/timelinemodelaggregator.h b/src/libs/timeline/timelinemodelaggregator.h
new file mode 100644
index 00000000000..c7cd12aedc2
--- /dev/null
+++ b/src/libs/timeline/timelinemodelaggregator.h
@@ -0,0 +1,77 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinemodel.h"
+#include "timelinenotesmodel.h"
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineModelAggregator : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int height READ height NOTIFY heightChanged)
+ Q_PROPERTY(QVariantList models READ models NOTIFY modelsChanged)
+ Q_PROPERTY(Timeline::TimelineNotesModel *notes READ notes CONSTANT)
+public:
+ TimelineModelAggregator(TimelineNotesModel *notes, QObject *parent = 0);
+ ~TimelineModelAggregator();
+
+ int height() const;
+
+ void addModel(TimelineModel *m);
+ const TimelineModel *model(int modelIndex) const;
+ QVariantList models() const;
+
+ TimelineNotesModel *notes() const;
+ void clear();
+ int modelCount() const;
+
+ Q_INVOKABLE int modelOffset(int modelIndex) const;
+
+ Q_INVOKABLE QVariantMap nextItem(int selectedModel, int selectedItem, qint64 time) const;
+ Q_INVOKABLE QVariantMap prevItem(int selectedModel, int selectedItem, qint64 time) const;
+
+signals:
+ void dataAvailable();
+ void stateChanged();
+ void modelsChanged();
+ void heightChanged();
+
+private:
+ class TimelineModelAggregatorPrivate;
+ TimelineModelAggregatorPrivate *d;
+};
+
+} // namespace Timeline
+
+#endif // TIMELINEMODELAGGREGATOR_H
diff --git a/src/libs/timeline/timelinenotesmodel.cpp b/src/libs/timeline/timelinenotesmodel.cpp
new file mode 100644
index 00000000000..6fbd727410d
--- /dev/null
+++ b/src/libs/timeline/timelinenotesmodel.cpp
@@ -0,0 +1,225 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinenotesmodel_p.h"
+
+namespace Timeline {
+
+TimelineNotesModel::TimelineNotesModelPrivate::TimelineNotesModelPrivate(TimelineNotesModel *q) :
+ modified(false), q_ptr(q)
+{
+}
+
+TimelineNotesModel::TimelineNotesModel(QObject *parent) : QObject(parent),
+ d_ptr(new TimelineNotesModelPrivate(this))
+{
+}
+
+TimelineNotesModel::~TimelineNotesModel()
+{
+ Q_D(TimelineNotesModel);
+ delete d;
+}
+
+int TimelineNotesModel::count() const
+{
+ Q_D(const TimelineNotesModel);
+ return d->data.count();
+}
+
+void TimelineNotesModel::addTimelineModel(const TimelineModel *timelineModel)
+{
+ Q_D(TimelineNotesModel);
+ connect(timelineModel, SIGNAL(destroyed(QObject*)),
+ this, SLOT(_q_removeTimelineModel(QObject*)));
+ d->timelineModels.insert(timelineModel->modelId(), timelineModel);
+}
+
+const TimelineModel *TimelineNotesModel::timelineModelByModelId(int timelineModel) const
+{
+ Q_D(const TimelineNotesModel);
+ auto it = d->timelineModels.find(timelineModel);
+ return it == d->timelineModels.end() ? 0 : it.value();
+}
+
+QList<const TimelineModel *> TimelineNotesModel::timelineModels() const
+{
+ Q_D(const TimelineNotesModel);
+ return d->timelineModels.values();
+}
+
+int TimelineNotesModel::typeId(int index) const
+{
+ Q_D(const TimelineNotesModel);
+ const TimelineNotesModelPrivate::Note &note = d->data[index];
+ const TimelineModel *model = timelineModelByModelId(note.timelineModel);
+ if (!model)
+ return -1; // This can happen if one of the timeline models has been removed
+ return model->typeId(note.timelineIndex);
+}
+
+QString TimelineNotesModel::text(int index) const
+{
+ Q_D(const TimelineNotesModel);
+ return d->data[index].text;
+}
+
+int TimelineNotesModel::timelineModel(int index) const
+{
+ Q_D(const TimelineNotesModel);
+ return d->data[index].timelineModel;
+}
+
+int TimelineNotesModel::timelineIndex(int index) const
+{
+ Q_D(const TimelineNotesModel);
+ return d->data[index].timelineIndex;
+}
+
+QVariantList TimelineNotesModel::byTypeId(int selectedType) const
+{
+ QVariantList ret;
+ for (int noteId = 0; noteId < count(); ++noteId) {
+ if (selectedType == typeId(noteId))
+ ret << noteId;
+ }
+ return ret;
+}
+
+QVariantList TimelineNotesModel::byTimelineModel(int timelineModel) const
+{
+ Q_D(const TimelineNotesModel);
+ QVariantList ret;
+ for (int noteId = 0; noteId < count(); ++noteId) {
+ if (d->data[noteId].timelineModel == timelineModel)
+ ret << noteId;
+ }
+ return ret;
+}
+
+int TimelineNotesModel::get(int timelineModel, int timelineIndex) const
+{
+ Q_D(const TimelineNotesModel);
+ for (int noteId = 0; noteId < count(); ++noteId) {
+ const TimelineNotesModelPrivate::Note &note = d->data[noteId];
+ if (note.timelineModel == timelineModel && note.timelineIndex == timelineIndex)
+ return noteId;
+ }
+
+ return -1;
+}
+
+int TimelineNotesModel::add(int timelineModel, int timelineIndex, const QString &text)
+{
+ Q_D(TimelineNotesModel);
+ const TimelineModel *model = d->timelineModels[timelineModel];
+ int typeId = model->typeId(timelineIndex);
+ TimelineNotesModelPrivate::Note note = { text, timelineModel, timelineIndex };
+ d->data << note;
+ d->modified = true;
+ emit changed(typeId, timelineModel, timelineIndex);
+ return d->data.count() - 1;
+}
+
+void TimelineNotesModel::update(int index, const QString &text)
+{
+ Q_D(TimelineNotesModel);
+ TimelineNotesModelPrivate::Note &note = d->data[index];
+ if (text != note.text) {
+ note.text = text;
+ d->modified = true;
+ emit changed(typeId(index), note.timelineModel, note.timelineIndex);
+ }
+}
+
+void TimelineNotesModel::remove(int index)
+{
+ Q_D(TimelineNotesModel);
+ TimelineNotesModelPrivate::Note &note = d->data[index];
+ int noteType = typeId(index);
+ int timelineModel = note.timelineModel;
+ int timelineIndex = note.timelineIndex;
+ d->data.removeAt(index);
+ d->modified = true;
+ emit changed(noteType, timelineModel, timelineIndex);
+}
+
+bool TimelineNotesModel::isModified() const
+{
+ Q_D(const TimelineNotesModel);
+ return d->modified;
+}
+
+void TimelineNotesModel::resetModified()
+{
+ Q_D(TimelineNotesModel);
+ d->modified = false;
+}
+
+void TimelineNotesModel::TimelineNotesModelPrivate::_q_removeTimelineModel(QObject *timelineModel)
+{
+ for (auto i = timelineModels.begin(); i != timelineModels.end();) {
+ if (i.value() == timelineModel)
+ i = timelineModels.erase(i);
+ else
+ ++i;
+ }
+}
+
+void TimelineNotesModel::setText(int noteId, const QString &text)
+{
+ if (text.length() > 0)
+ update(noteId, text);
+ else
+ remove(noteId);
+}
+
+void TimelineNotesModel::setText(int modelIndex, int index, const QString &text)
+{
+ int noteId = get(modelIndex, index);
+ if (noteId == -1) {
+ if (text.length() > 0)
+ add(modelIndex, index, text);
+ } else {
+ setText(noteId, text);
+ }
+}
+
+void TimelineNotesModel::clear()
+{
+ Q_D(TimelineNotesModel);
+ d->data.clear();
+ d->modified = false;
+ emit changed(-1, -1, -1);
+}
+
+} // namespace Timeline
+
+#include "moc_timelinenotesmodel.cpp"
diff --git a/src/libs/timeline/timelinenotesmodel.h b/src/libs/timeline/timelinenotesmodel.h
new file mode 100644
index 00000000000..4a220927ecc
--- /dev/null
+++ b/src/libs/timeline/timelinenotesmodel.h
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINENOTESMODEL_H
+#define TIMELINENOTESMODEL_H
+
+#include "timelinemodel.h"
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineNotesModel : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int count READ count NOTIFY changed)
+public:
+ TimelineNotesModel(QObject *parent = 0);
+ ~TimelineNotesModel();
+
+ int count() const;
+ void addTimelineModel(const TimelineModel *timelineModel);
+ const TimelineModel *timelineModelByModelId(int timelineModel) const;
+ QList<const TimelineModel *> timelineModels() const;
+
+ Q_INVOKABLE int typeId(int index) const;
+ Q_INVOKABLE QString text(int index) const;
+ Q_INVOKABLE int timelineModel(int index) const;
+ Q_INVOKABLE int timelineIndex(int index) const;
+
+ Q_INVOKABLE QVariantList byTypeId(int typeId) const;
+ Q_INVOKABLE QVariantList byTimelineModel(int timelineModel) const;
+
+ Q_INVOKABLE int get(int timelineModel, int timelineIndex) const;
+ Q_INVOKABLE int add(int timelineModel, int timelineIndex, const QString &text);
+ Q_INVOKABLE void update(int index, const QString &text);
+ Q_INVOKABLE void remove(int index);
+
+ Q_INVOKABLE void setText(int noteId, const QString &text);
+ Q_INVOKABLE void setText(int modelIndex, int index, const QString &text);
+
+ bool isModified() const;
+ void resetModified();
+
+ void clear();
+
+signals:
+ void changed(int typeId, int timelineModel, int timelineIndex);
+
+private:
+ class TimelineNotesModelPrivate;
+ TimelineNotesModelPrivate *d_ptr;
+
+ Q_DECLARE_PRIVATE(TimelineNotesModel)
+ Q_PRIVATE_SLOT(d_ptr, void _q_removeTimelineModel(QObject *timelineModel))
+};
+
+} // namespace Timeline
+
+#endif // TIMELINENOTESMODEL_H
diff --git a/src/libs/timeline/timelinenotesmodel_p.h b/src/libs/timeline/timelinenotesmodel_p.h
new file mode 100644
index 00000000000..9a33a628b69
--- /dev/null
+++ b/src/libs/timeline/timelinenotesmodel_p.h
@@ -0,0 +1,65 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINENOTESMODEL_P_H
+#define TIMELINENOTESMODEL_P_H
+
+#include "timelinenotesmodel.h"
+
+namespace Timeline {
+
+class TimelineNotesModel::TimelineNotesModelPrivate {
+public:
+ TimelineNotesModelPrivate(TimelineNotesModel *q);
+
+ struct Note {
+ // Saved properties
+ QString text;
+
+ // Cache, created on loading
+ int timelineModel;
+ int timelineIndex;
+ };
+
+ QList<Note> data;
+ QHash<int, const TimelineModel *> timelineModels;
+ bool modified;
+
+ void _q_removeTimelineModel(QObject *model);
+
+private:
+ TimelineNotesModel *q_ptr;
+ Q_DECLARE_PUBLIC(TimelineNotesModel)
+};
+
+} // namespace Timeline
+
+#endif // TIMELINENOTESMODEL_P_H
+
diff --git a/src/libs/timeline/timelinenotesrenderpass.cpp b/src/libs/timeline/timelinenotesrenderpass.cpp
new file mode 100644
index 00000000000..ec748923887
--- /dev/null
+++ b/src/libs/timeline/timelinenotesrenderpass.cpp
@@ -0,0 +1,265 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinenotesrenderpass.h"
+#include "timelinerenderstate.h"
+#include "timelinenotesmodel.h"
+
+namespace Timeline {
+
+struct Point2DWithDistanceFromTop {
+ float x, y, d;
+ void set(float nx, float ny, float nd);
+};
+
+class NotesMaterial : public QSGMaterial
+{
+public:
+ QSGMaterialType *type() const;
+ QSGMaterialShader *createShader() const;
+};
+
+struct NotesGeometry
+{
+ static const int maxNotes;
+ static const QSGGeometry::AttributeSet &point2DWithDistanceFromTop();
+
+ static QSGGeometry *createGeometry(QVector<int> &ids, const TimelineModel *model,
+ const TimelineRenderState *parentState, bool collapsed);
+};
+
+const int NotesGeometry::maxNotes = 0xffff / 2;
+
+struct TimelineNotesRenderPassState : public TimelineRenderPass::State
+{
+ TimelineNotesRenderPassState(int expandedRows);
+
+ QSGGeometryNode *createNode();
+
+ NotesMaterial material;
+ QSGGeometry nullGeometry;
+ QSGGeometryNode *m_collapsedOverlay;
+ QVector<QSGNode *> m_expandedRows;
+
+ QSGNode *collapsedOverlay() const { return m_collapsedOverlay; }
+ const QVector<QSGNode *> &expandedRows() const { return m_expandedRows; }
+};
+
+const QSGGeometry::AttributeSet &NotesGeometry::point2DWithDistanceFromTop()
+{
+ static QSGGeometry::Attribute data[] = {
+ QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true),
+ QSGGeometry::Attribute::create(1, 1, GL_FLOAT),
+ };
+ static QSGGeometry::AttributeSet attrs = {
+ 2,
+ sizeof(Point2DWithDistanceFromTop),
+ data
+ };
+ return attrs;
+}
+
+const TimelineNotesRenderPass *TimelineNotesRenderPass::instance()
+{
+ static const TimelineNotesRenderPass pass;
+ return &pass;
+}
+
+TimelineNotesRenderPass::TimelineNotesRenderPass()
+{
+}
+
+TimelineRenderPass::State *TimelineNotesRenderPass::update(const TimelineAbstractRenderer *renderer,
+ const TimelineRenderState *parentState,
+ State *oldState, int firstIndex,
+ int lastIndex, bool stateChanged,
+ qreal spacing) const
+{
+ Q_UNUSED(firstIndex);
+ Q_UNUSED(lastIndex);
+ Q_UNUSED(spacing);
+
+ const TimelineNotesModel *notes = renderer->notes();
+ const TimelineModel *model = renderer->model();
+
+ if (!model || !notes)
+ return oldState;
+
+ TimelineNotesRenderPassState *state;
+ if (oldState == 0) {
+ state = new TimelineNotesRenderPassState(model->expandedRowCount());
+ } else {
+ if (!stateChanged && !renderer->notesDirty())
+ return oldState;
+ state = static_cast<TimelineNotesRenderPassState *>(oldState);
+ }
+
+ QVector<QVector<int> > expanded(model->expandedRowCount());
+ QVector<int> collapsed;
+
+ for (int i = 0; i < qMin(notes->count(), NotesGeometry::maxNotes); ++i) {
+ if (notes->timelineModel(i) != model->modelId())
+ continue;
+ int timelineIndex = notes->timelineIndex(i);
+ if (model->startTime(timelineIndex) > parentState->end() ||
+ model->endTime(timelineIndex) < parentState->start())
+ continue;
+ expanded[model->expandedRow(timelineIndex)] << timelineIndex;
+ collapsed << timelineIndex;
+ }
+
+ QSGGeometryNode *collapsedNode = state->m_collapsedOverlay;
+
+ if (collapsed.count() > 0) {
+ collapsedNode->setGeometry(NotesGeometry::createGeometry(collapsed, model, parentState,
+ true));
+ collapsedNode->setFlag(QSGGeometryNode::OwnsGeometry, true);
+ } else {
+ collapsedNode->setGeometry(&state->nullGeometry);
+ collapsedNode->setFlag(QSGGeometryNode::OwnsGeometry, false);
+ }
+
+ for (int row = 0; row < model->expandedRowCount(); ++row) {
+ QSGGeometryNode *rowNode = static_cast<QSGGeometryNode *>(state->m_expandedRows[row]);
+ if (expanded[row].isEmpty()) {
+ rowNode->setGeometry(&state->nullGeometry);
+ rowNode->setFlag(QSGGeometryNode::OwnsGeometry, false);
+ } else {
+ rowNode->setGeometry(NotesGeometry::createGeometry(expanded[row], model, parentState,
+ false));
+ collapsedNode->setFlag(QSGGeometryNode::OwnsGeometry, true);
+ }
+ }
+
+ return state;
+}
+
+TimelineNotesRenderPassState::TimelineNotesRenderPassState(int numExpandedRows) :
+ nullGeometry(NotesGeometry::point2DWithDistanceFromTop(), 0)
+{
+ material.setFlag(QSGMaterial::Blending, true);
+ m_expandedRows.reserve(numExpandedRows);
+ for (int i = 0; i < numExpandedRows; ++i)
+ m_expandedRows << createNode();
+ m_collapsedOverlay = createNode();
+}
+
+QSGGeometryNode *TimelineNotesRenderPassState::createNode()
+{
+ QSGGeometryNode *node = new QSGGeometryNode;
+ node->setGeometry(&nullGeometry);
+ node->setMaterial(&material);
+ return node;
+}
+
+QSGGeometry *NotesGeometry::createGeometry(QVector<int> &ids, const TimelineModel *model,
+ const TimelineRenderState *parentState, bool collapsed)
+{
+ float rowHeight = TimelineModel::defaultRowHeight();
+ QSGGeometry *geometry = new QSGGeometry(point2DWithDistanceFromTop(),
+ ids.count() * 2);
+ geometry->setDrawingMode(GL_LINES);
+ geometry->setLineWidth(3);
+ Point2DWithDistanceFromTop *v =
+ static_cast<Point2DWithDistanceFromTop *>(geometry->vertexData());
+ for (int i = 0; i < ids.count(); ++i) {
+ int timelineIndex = ids[i];
+ float horizontalCenter = ((model->startTime(timelineIndex) +
+ model->endTime(timelineIndex)) / (qint64)2 -
+ parentState->start()) * parentState->scale();
+ float verticalStart = (collapsed ? (model->collapsedRow(timelineIndex) + 0.1) : 0.1) *
+ rowHeight;
+ float verticalEnd = verticalStart + 0.8 * rowHeight;
+ v[i * 2].set(horizontalCenter, verticalStart, 0);
+ v[i * 2 + 1].set(horizontalCenter, verticalEnd, 1);
+ }
+ return geometry;
+}
+
+class NotesMaterialShader : public QSGMaterialShader
+{
+public:
+ NotesMaterialShader();
+
+ virtual void updateState(const RenderState &state, QSGMaterial *newEffect,
+ QSGMaterial *oldEffect);
+ virtual char const *const *attributeNames() const;
+
+private:
+ virtual void initialize();
+
+ int m_matrix_id;
+ int m_z_range_id;
+};
+
+NotesMaterialShader::NotesMaterialShader()
+ : QSGMaterialShader()
+{
+ setShaderSourceFile(QOpenGLShader::Vertex, QStringLiteral(":/timeline/notes.vert"));
+ setShaderSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/timeline/notes.frag"));
+}
+
+void NotesMaterialShader::updateState(const RenderState &state, QSGMaterial *, QSGMaterial *)
+{
+ if (state.isMatrixDirty()) {
+ program()->setUniformValue(m_matrix_id, state.combinedMatrix());
+ program()->setUniformValue(m_z_range_id, GLfloat(1.0));
+ }
+}
+
+char const *const *NotesMaterialShader::attributeNames() const
+{
+ static const char *const attr[] = {"vertexCoord", "distanceFromTop", 0};
+ return attr;
+}
+
+void NotesMaterialShader::initialize()
+{
+ m_matrix_id = program()->uniformLocation("matrix");
+ m_z_range_id = program()->uniformLocation("_qt_zRange");
+}
+
+QSGMaterialType *NotesMaterial::type() const
+{
+ static QSGMaterialType type;
+ return &type;
+}
+
+QSGMaterialShader *NotesMaterial::createShader() const
+{
+ return new NotesMaterialShader;
+}
+
+void Point2DWithDistanceFromTop::set(float nx, float ny, float nd)
+{
+ x = nx; y = ny; d = nd;
+}
+
+} // namespace Timeline
diff --git a/src/plugins/qmlprofiler/abstracttimelinemodel_p.h b/src/libs/timeline/timelinenotesrenderpass.h
index 99bcf04cf4a..74beb3569ad 100644
--- a/src/plugins/qmlprofiler/abstracttimelinemodel_p.h
+++ b/src/libs/timeline/timelinenotesrenderpass.h
@@ -28,32 +28,28 @@
**
****************************************************************************/
-#ifndef ABSTRACTTIMELINEMODEL_P_H
-#define ABSTRACTTIMELINEMODEL_P_H
+#ifndef TIMELINENOTESRENDERPASS_H
+#define TIMELINENOTESRENDERPASS_H
-#include "abstracttimelinemodel.h"
+#include "timelineabstractrenderer.h"
+#include <QSGMaterial>
-namespace QmlProfiler {
+namespace Timeline {
-class QMLPROFILER_EXPORT AbstractTimelineModel::AbstractTimelineModelPrivate {
+class TIMELINE_EXPORT TimelineNotesRenderPass : public TimelineRenderPass
+{
public:
- QVector<int> rowOffsets;
- QmlProfilerModelManager *modelManager;
- int modelId;
- bool expanded;
- bool hidden;
- int expandedRowCount;
- int collapsedRowCount;
- QString displayName;
- QmlDebug::Message message;
- QmlDebug::RangeType rangeType;
-
-protected:
- AbstractTimelineModel *q_ptr;
+ static const TimelineNotesRenderPass *instance();
+
+ State *update(const TimelineAbstractRenderer *renderer, const TimelineRenderState *parentState,
+ State *oldState, int firstIndex, int lastIndex, bool stateChanged,
+ qreal spacing) const;
private:
- Q_DECLARE_PUBLIC(AbstractTimelineModel)
+ TimelineNotesRenderPass();
};
-}
-#endif // ABSTRACTTIMELINEMODEL_P_H
+} // namespace Timeline
+
+#endif // TIMELINENOTESRENDERPASS_H
+
diff --git a/src/libs/timeline/timelineoverviewrenderer.cpp b/src/libs/timeline/timelineoverviewrenderer.cpp
new file mode 100644
index 00000000000..7e43848e979
--- /dev/null
+++ b/src/libs/timeline/timelineoverviewrenderer.cpp
@@ -0,0 +1,91 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelineoverviewrenderer_p.h"
+#include "timelinerenderstate.h"
+
+namespace Timeline {
+
+TimelineOverviewRenderer::TimelineOverviewRenderer(QQuickItem *parent) :
+ TimelineAbstractRenderer(*(new TimelineOverviewRendererPrivate), parent)
+{
+ Q_D(TimelineOverviewRenderer);
+ setFlag(QQuickItem::ItemHasContents);
+ d->renderState = 0;
+}
+
+TimelineOverviewRenderer::~TimelineOverviewRenderer()
+{
+ Q_D(TimelineOverviewRenderer);
+ delete d->renderState;
+ delete d;
+}
+
+QSGNode *TimelineOverviewRenderer::updatePaintNode(QSGNode *oldNode,
+ UpdatePaintNodeData *updatePaintNodeData)
+{
+ Q_D(TimelineOverviewRenderer);
+ Q_UNUSED(updatePaintNodeData)
+
+ if (d->modelDirty) {
+ delete d->renderState;
+ d->renderState = 0;
+ d->modelDirty = false;
+ }
+
+ if (d->renderState == 0) {
+ d->renderState = new TimelineRenderState(d->zoomer->traceStart(), d->zoomer->traceEnd(),
+ 1.0, d->renderPasses.size());
+ }
+
+ qreal xSpacing = width() / d->zoomer->traceDuration();
+ qreal ySpacing = height() / (d->model->collapsedRowCount() * TimelineModel::defaultRowHeight());
+
+ for (int i = 0; i < d->renderPasses.length(); ++i) {
+ d->renderState->setPassState(i, d->renderPasses[i]->update(this, d->renderState,
+ d->renderState->passState(i),
+ 0, d->model->count(), true,
+ xSpacing));
+ }
+
+ if (d->renderState->isEmpty())
+ d->renderState->assembleNodeTree(d->model, d->model->height(), 0);
+
+ d->modelDirty = false;
+ d->notesDirty = false;
+ d->rowHeightsDirty = false;
+
+ QMatrix4x4 matrix;
+ matrix.scale(xSpacing, ySpacing, 1);
+ return d->renderState->finalize(oldNode, false, matrix);
+}
+
+}
+
diff --git a/src/libs/timeline/timelineoverviewrenderer.h b/src/libs/timeline/timelineoverviewrenderer.h
new file mode 100644
index 00000000000..1c4710734b6
--- /dev/null
+++ b/src/libs/timeline/timelineoverviewrenderer.h
@@ -0,0 +1,55 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEOVERVIEWRENDERER_H
+#define TIMELINEOVERVIEWRENDERER_H
+
+#include "timelineabstractrenderer.h"
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineOverviewRenderer : public TimelineAbstractRenderer
+{
+public:
+ TimelineOverviewRenderer(QQuickItem *parent = 0);
+ ~TimelineOverviewRenderer();
+
+protected:
+ virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData);
+
+ class TimelineOverviewRendererPrivate;
+ Q_DECLARE_PRIVATE(TimelineOverviewRenderer)
+};
+
+} // namespace Timeline
+
+QML_DECLARE_TYPE(Timeline::TimelineOverviewRenderer)
+
+#endif // TIMELINEOVERVIEWRENDERER_H
diff --git a/src/libs/timeline/timelineoverviewrenderer_p.h b/src/libs/timeline/timelineoverviewrenderer_p.h
new file mode 100644
index 00000000000..afeac5d6a2c
--- /dev/null
+++ b/src/libs/timeline/timelineoverviewrenderer_p.h
@@ -0,0 +1,49 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEOVERVIEWRENDERER_P_H
+#define TIMELINEOVERVIEWRENDERER_P_H
+
+#include "timelineoverviewrenderer.h"
+#include "timelineabstractrenderer_p.h"
+
+namespace Timeline {
+
+class TimelineOverviewRenderer::TimelineOverviewRendererPrivate :
+ public TimelineAbstractRenderer::TimelineAbstractRendererPrivate
+{
+public:
+ TimelineRenderState *renderState;
+};
+
+} // namespace Timeline
+
+#endif // TIMELINEOVERVIEWRENDERER_P_H
+
diff --git a/src/libs/timeline/timelinerenderer.cpp b/src/libs/timeline/timelinerenderer.cpp
new file mode 100644
index 00000000000..98fc95bc189
--- /dev/null
+++ b/src/libs/timeline/timelinerenderer.cpp
@@ -0,0 +1,305 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinerenderer_p.h"
+#include "timelinerenderpass.h"
+#include "timelinenotesmodel.h"
+#include "timelineitemsrenderpass.h"
+#include "timelineselectionrenderpass.h"
+#include "timelinenotesrenderpass.h"
+
+#include <QElapsedTimer>
+#include <QQmlContext>
+#include <QQmlProperty>
+#include <QTimer>
+#include <QPixmap>
+#include <QVarLengthArray>
+#include <QSGTransformNode>
+#include <QSGSimpleRectNode>
+
+#include <math.h>
+
+namespace Timeline {
+
+TimelineRenderer::TimelineRendererPrivate::TimelineRendererPrivate(TimelineRenderer *q) :
+ lastState(0), q_ptr(q)
+{
+ resetCurrentSelection();
+}
+
+TimelineRenderer::TimelineRenderer(QQuickItem *parent) :
+ TimelineAbstractRenderer(*(new TimelineRendererPrivate(this)), parent)
+{
+ setFlag(QQuickItem::ItemHasContents);
+ setAcceptedMouseButtons(Qt::LeftButton);
+ setAcceptHoverEvents(true);
+}
+
+void TimelineRenderer::TimelineRendererPrivate::resetCurrentSelection()
+{
+ currentSelection.startTime = -1;
+ currentSelection.endTime = -1;
+ currentSelection.row = -1;
+ currentSelection.eventIndex = -1;
+}
+
+TimelineRenderState *TimelineRenderer::TimelineRendererPrivate::findRenderState()
+{
+ int newLevel = 0;
+ int newOffset = 0;
+ int level;
+ int offset;
+
+ qint64 newStart = zoomer->traceStart();
+ qint64 newEnd = zoomer->traceEnd();
+ qint64 start;
+ qint64 end;
+ do {
+ level = newLevel;
+ offset = newOffset;
+ start = newStart;
+ end = newEnd;
+
+ newLevel = level + 1;
+ qint64 range = zoomer->traceDuration() >> newLevel;
+ newOffset = (zoomer->windowStart() - zoomer->traceStart() + range / 2) / range;
+ newStart = zoomer->traceStart() + newOffset * range - range / 2;
+ newEnd = newStart + range;
+ } while (newStart < zoomer->windowStart() && newEnd > zoomer->windowEnd());
+
+
+ if (renderStates.length() <= level)
+ renderStates.resize(level + 1);
+ if (renderStates[level].length() <= offset)
+ renderStates[level].resize(offset + 1);
+ TimelineRenderState *state = renderStates[level][offset];
+ if (state == 0) {
+ state = new TimelineRenderState(start, end, 1.0 / static_cast<qreal>(SafeFloatMax),
+ renderPasses.size());
+ renderStates[level][offset] = state;
+ }
+ return state;
+}
+
+QSGNode *TimelineRenderer::updatePaintNode(QSGNode *node, UpdatePaintNodeData *updatePaintNodeData)
+{
+ Q_D(TimelineRenderer);
+ Q_UNUSED(updatePaintNodeData)
+
+ if (!d->model || d->model->hidden() || d->model->isEmpty() ||
+ d->zoomer->windowDuration() <= 0) {
+ delete node;
+ return 0;
+ }
+
+ qreal spacing = width() / d->zoomer->windowDuration();
+
+ if (d->modelDirty) {
+ if (node)
+ node->removeAllChildNodes();
+ foreach (QVector<TimelineRenderState *> stateVector, d->renderStates)
+ qDeleteAll(stateVector);
+ d->renderStates.clear();
+ d->lastState = 0;
+ }
+
+ TimelineRenderState *state = d->findRenderState();
+
+ int lastIndex = d->model->lastIndex(d->zoomer->windowEnd());
+ int firstIndex = d->model->firstIndex(d->zoomer->windowStart());
+
+ for (int i = 0; i < d->renderPasses.length(); ++i)
+ state->setPassState(i, d->renderPasses[i]->update(this, state, state->passState(i),
+ firstIndex, lastIndex + 1,
+ state != d->lastState, spacing));
+
+ if (state->isEmpty()) { // new state
+ state->assembleNodeTree(d->model, TimelineModel::defaultRowHeight(),
+ TimelineModel::defaultRowHeight());
+ } else if (d->rowHeightsDirty || state != d->lastState) {
+ state->updateExpandedRowHeights(d->model, TimelineModel::defaultRowHeight(),
+ TimelineModel::defaultRowHeight());
+ }
+
+ d->modelDirty = false;
+ d->notesDirty = false;
+ d->rowHeightsDirty = false;
+ d->lastState = state;
+
+ QMatrix4x4 matrix;
+ matrix.translate((state->start() - d->zoomer->windowStart()) * spacing, 0, 0);
+ matrix.scale(spacing / state->scale(), 1, 1);
+
+ return state->finalize(node, d->model->expanded(), matrix);
+}
+
+void TimelineRenderer::mousePressEvent(QMouseEvent *event)
+{
+ Q_UNUSED(event);
+}
+
+int TimelineRenderer::TimelineRendererPrivate::rowFromPosition(int y) const
+{
+ if (!model->expanded())
+ return y / TimelineModel::defaultRowHeight();
+
+ int ret = 0;
+ for (int row = 0; row < model->expandedRowCount(); ++row) {
+ y -= model->expandedRowHeight(row);
+ if (y <= 0) return ret;
+ ++ret;
+ }
+
+ return ret;
+}
+
+void TimelineRenderer::mouseReleaseEvent(QMouseEvent *event)
+{
+ Q_D(TimelineRenderer);
+ Q_UNUSED(event);
+ if (!d->model->isEmpty())
+ d->manageClicked();
+}
+
+void TimelineRenderer::mouseMoveEvent(QMouseEvent *event)
+{
+ event->setAccepted(false);
+}
+
+void TimelineRenderer::hoverMoveEvent(QHoverEvent *event)
+{
+ Q_D(TimelineRenderer);
+ Q_UNUSED(event);
+ d->manageHovered(event->pos().x(), event->pos().y());
+ if (d->currentSelection.eventIndex == -1)
+ event->setAccepted(false);
+}
+
+void TimelineRenderer::TimelineRendererPrivate::manageClicked()
+{
+ Q_Q(TimelineRenderer);
+ if (currentSelection.eventIndex != -1) {
+ if (currentSelection.eventIndex == selectedItem)
+ q->setSelectionLocked(!selectionLocked);
+ else
+ q->setSelectionLocked(true);
+
+ // itemPressed() will trigger an update of the events and JavaScript views. Make sure the
+ // correct event is already selected when that happens, to prevent confusion.
+ q->setSelectedItem(currentSelection.eventIndex);
+ emit q->itemPressed(currentSelection.eventIndex);
+ } else {
+ q->setSelectionLocked(false);
+ q->setSelectedItem(-1);
+ emit q->itemPressed(-1);
+ }
+}
+
+void TimelineRenderer::TimelineRendererPrivate::manageHovered(int mouseX, int mouseY)
+{
+ Q_Q(TimelineRenderer);
+ qint64 duration = zoomer->windowDuration();
+ if (duration <= 0)
+ return;
+
+ // Make the "selected" area 3 pixels wide by adding/subtracting 1 to catch very narrow events.
+ qint64 startTime = (mouseX - 1) * duration / q->width() + zoomer->windowStart();
+ qint64 endTime = (mouseX + 1) * duration / q->width() + zoomer->windowStart();
+ qint64 exactTime = (startTime + endTime) / 2;
+ int row = rowFromPosition(mouseY);
+
+ // already covered? Only recheck selectionLocked and make sure d->selectedItem is correct.
+ if (currentSelection.eventIndex != -1 &&
+ exactTime >= currentSelection.startTime &&
+ exactTime < currentSelection.endTime &&
+ row == currentSelection.row) {
+ if (!selectionLocked)
+ q->setSelectedItem(currentSelection.eventIndex);
+ return;
+ }
+
+ // find if there's items in the time range
+ int eventFrom = model->firstIndex(startTime);
+ int eventTo = model->lastIndex(endTime);
+
+ currentSelection.eventIndex = -1;
+ if (eventFrom == -1 || eventTo < eventFrom || eventTo >= model->count())
+ return;
+
+ // find if we are in the right column
+ qint64 bestOffset = std::numeric_limits<qint64>::max();
+ for (int i=eventTo; i>=eventFrom; --i) {
+ if (model->row(i) == row) {
+ // There can be small events that don't reach the cursor position after large events
+ // that do but are in a different row.
+ qint64 itemEnd = model->endTime(i);
+ if (itemEnd < startTime)
+ continue;
+
+ qint64 itemStart = model->startTime(i);
+
+ qint64 offset = qAbs(itemEnd - exactTime) + qAbs(itemStart - exactTime);
+ if (offset < bestOffset) {
+ // match
+ currentSelection.eventIndex = i;
+ currentSelection.startTime = itemStart;
+ currentSelection.endTime = itemEnd;
+ currentSelection.row = row;
+ bestOffset = offset;
+ }
+ }
+ }
+ if (!selectionLocked && currentSelection.eventIndex != -1)
+ q->setSelectedItem(currentSelection.eventIndex);
+}
+
+void TimelineRenderer::clearData()
+{
+ Q_D(TimelineRenderer);
+ d->resetCurrentSelection();
+ setSelectedItem(-1);
+ setSelectionLocked(true);
+}
+
+void TimelineRenderer::selectNextFromSelectionId(int selectionId)
+{
+ Q_D(TimelineRenderer);
+ setSelectedItem(d->model->nextItemBySelectionId(selectionId, d->zoomer->rangeStart(),
+ d->selectedItem));
+}
+
+void TimelineRenderer::selectPrevFromSelectionId(int selectionId)
+{
+ Q_D(TimelineRenderer);
+ setSelectedItem(d->model->prevItemBySelectionId(selectionId, d->zoomer->rangeStart(),
+ d->selectedItem));
+}
+
+} // namespace Timeline
diff --git a/src/libs/timeline/timelinerenderer.h b/src/libs/timeline/timelinerenderer.h
new file mode 100644
index 00000000000..baed35f4774
--- /dev/null
+++ b/src/libs/timeline/timelinerenderer.h
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINERENDERER_H
+#define TIMELINERENDERER_H
+
+#include "timelinezoomcontrol.h"
+#include "timelinemodel.h"
+#include "timelinenotesmodel.h"
+#include "timelineabstractrenderer.h"
+
+#include <QSGTransformNode>
+#include <QQuickItem>
+
+namespace Timeline {
+
+class TimelineRenderPass;
+class TimelineRenderState;
+
+class TIMELINE_EXPORT TimelineRenderer : public TimelineAbstractRenderer
+{
+ Q_OBJECT
+
+public:
+ explicit TimelineRenderer(QQuickItem *parent = 0);
+
+ Q_INVOKABLE void selectNextFromSelectionId(int selectionId);
+ Q_INVOKABLE void selectPrevFromSelectionId(int selectionId);
+
+ // TODO: We could add some Q_INVOKABLE functions to enable or disable render passes when the the
+ // need arises.
+
+signals:
+ void itemPressed(int pressedItem);
+
+public slots:
+ void clearData();
+
+protected:
+ virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData);
+ virtual void mousePressEvent(QMouseEvent *event);
+ virtual void mouseReleaseEvent(QMouseEvent *event);
+ virtual void mouseMoveEvent(QMouseEvent *event);
+ virtual void hoverMoveEvent(QHoverEvent *event);
+
+private:
+ class TimelineRendererPrivate;
+ Q_DECLARE_PRIVATE(TimelineRenderer)
+};
+
+} // namespace Timeline
+
+QML_DECLARE_TYPE(Timeline::TimelineRenderer)
+
+#endif // TIMELINERENDERER_H
diff --git a/src/libs/timeline/timelinerenderer_p.h b/src/libs/timeline/timelinerenderer_p.h
new file mode 100644
index 00000000000..3d4a2678aa0
--- /dev/null
+++ b/src/libs/timeline/timelinerenderer_p.h
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINERENDERER_P_H
+#define TIMELINERENDERER_P_H
+
+#include "timelinerenderer.h"
+#include "timelineabstractrenderer_p.h"
+
+namespace Timeline {
+
+class TimelineRenderer::TimelineRendererPrivate :
+ TimelineAbstractRenderer::TimelineAbstractRendererPrivate {
+public:
+ TimelineRendererPrivate(TimelineRenderer *q);
+
+ int rowFromPosition(int y) const;
+
+ void manageClicked();
+ void manageHovered(int mouseX, int mouseY);
+
+ static const int SafeFloatMax = 1 << 12;
+
+ void resetCurrentSelection();
+
+ TimelineRenderState *findRenderState();
+
+ struct {
+ qint64 startTime;
+ qint64 endTime;
+ int row;
+ int eventIndex;
+ } currentSelection;
+
+ QVector<QVector<TimelineRenderState *> > renderStates;
+ TimelineRenderState *lastState;
+
+private:
+ TimelineRenderer *q_ptr;
+ Q_DECLARE_PUBLIC(TimelineRenderer)
+};
+
+} // namespace Timeline
+
+#endif // TIMELINERENDERER_P_H
+
diff --git a/src/libs/timeline/timelinerenderpass.cpp b/src/libs/timeline/timelinerenderpass.cpp
new file mode 100644
index 00000000000..a6a9251ba57
--- /dev/null
+++ b/src/libs/timeline/timelinerenderpass.cpp
@@ -0,0 +1,63 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinerenderpass.h"
+
+namespace Timeline {
+
+const QVector<QSGNode *> &TimelineRenderPass::State::expandedRows() const
+{
+ static const QVector<QSGNode *> empty;
+ return empty;
+}
+
+const QVector<QSGNode *> &TimelineRenderPass::State::collapsedRows() const
+{
+ static const QVector<QSGNode *> empty;
+ return empty;
+}
+
+QSGNode *TimelineRenderPass::State::expandedOverlay() const
+{
+ return 0;
+}
+
+QSGNode *TimelineRenderPass::State::collapsedOverlay() const
+{
+ return 0;
+}
+
+TimelineRenderPass::State::~State()
+{
+}
+
+TimelineRenderPass::~TimelineRenderPass() {}
+
+} // namespace Timeline
diff --git a/src/libs/timeline/timelinerenderpass.h b/src/libs/timeline/timelinerenderpass.h
new file mode 100644
index 00000000000..6efb67ec7b5
--- /dev/null
+++ b/src/libs/timeline/timelinerenderpass.h
@@ -0,0 +1,63 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINERENDERPASS_H
+#define TIMELINERENDERPASS_H
+
+#include "timeline_global.h"
+#include <QVector>
+
+QT_FORWARD_DECLARE_CLASS(QSGNode)
+namespace Timeline {
+
+class TimelineAbstractRenderer;
+class TimelineRenderState;
+
+class TIMELINE_EXPORT TimelineRenderPass {
+public:
+ class TIMELINE_EXPORT State {
+ public:
+ virtual const QVector<QSGNode *> &expandedRows() const;
+ virtual const QVector<QSGNode *> &collapsedRows() const;
+ virtual QSGNode *expandedOverlay() const;
+ virtual QSGNode *collapsedOverlay() const;
+ virtual ~State();
+ };
+
+ virtual ~TimelineRenderPass();
+ virtual State *update(const TimelineAbstractRenderer *renderer,
+ const TimelineRenderState *parentState,
+ State *state, int indexFrom, int indexTo, bool stateChanged,
+ qreal spacing) const = 0;
+};
+
+} // namespace Timeline
+
+#endif // TIMELINERENDERPASS_H
diff --git a/src/libs/timeline/timelinerenderstate.cpp b/src/libs/timeline/timelinerenderstate.cpp
new file mode 100644
index 00000000000..75238660729
--- /dev/null
+++ b/src/libs/timeline/timelinerenderstate.cpp
@@ -0,0 +1,248 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinerenderstate_p.h"
+
+namespace Timeline {
+
+TimelineRenderState::TimelineRenderState(qint64 start, qint64 end, qreal scale, int numPasses) :
+ d_ptr(new TimelineRenderStatePrivate)
+{
+ Q_D(TimelineRenderState);
+ d->expandedRowRoot = new QSGNode;
+ d->collapsedRowRoot = new QSGNode;
+ d->expandedOverlayRoot = new QSGNode;
+ d->collapsedOverlayRoot = new QSGNode;
+ d->start = start;
+ d->end = end;
+ d->scale = scale;
+ d->passes.resize(numPasses);
+
+ d->expandedRowRoot->setFlag(QSGNode::OwnedByParent, false);
+ d->collapsedRowRoot->setFlag(QSGNode::OwnedByParent, false);
+ d->expandedOverlayRoot->setFlag(QSGNode::OwnedByParent, false);
+ d->collapsedOverlayRoot->setFlag(QSGNode::OwnedByParent, false);
+}
+
+TimelineRenderState::~TimelineRenderState()
+{
+ Q_D(TimelineRenderState);
+ delete d->expandedRowRoot;
+ delete d->collapsedRowRoot;
+ delete d->expandedOverlayRoot;
+ delete d->collapsedOverlayRoot;
+ qDeleteAll(d->passes);
+ delete d;
+}
+
+qint64 TimelineRenderState::start() const
+{
+ Q_D(const TimelineRenderState);
+ return d->start;
+}
+
+qint64 TimelineRenderState::end() const
+{
+ Q_D(const TimelineRenderState);
+ return d->end;
+}
+
+qreal TimelineRenderState::scale() const
+{
+ Q_D(const TimelineRenderState);
+ return d->scale;
+}
+
+const QSGNode *TimelineRenderState::expandedRowRoot() const
+{
+ Q_D(const TimelineRenderState);
+ return d->expandedRowRoot;
+}
+
+const QSGNode *TimelineRenderState::collapsedRowRoot() const
+{
+ Q_D(const TimelineRenderState);
+ return d->collapsedRowRoot;
+}
+
+const QSGNode *TimelineRenderState::expandedOverlayRoot() const
+{
+ Q_D(const TimelineRenderState);
+ return d->expandedOverlayRoot;
+}
+
+const QSGNode *TimelineRenderState::collapsedOverlayRoot() const
+{
+ Q_D(const TimelineRenderState);
+ return d->collapsedOverlayRoot;
+}
+
+QSGNode *TimelineRenderState::expandedRowRoot()
+{
+ Q_D(TimelineRenderState);
+ return d->expandedRowRoot;
+}
+
+QSGNode *TimelineRenderState::collapsedRowRoot()
+{
+ Q_D(TimelineRenderState);
+ return d->collapsedRowRoot;
+}
+
+QSGNode *TimelineRenderState::expandedOverlayRoot()
+{
+ Q_D(TimelineRenderState);
+ return d->expandedOverlayRoot;
+}
+
+QSGNode *TimelineRenderState::collapsedOverlayRoot()
+{
+ Q_D(TimelineRenderState);
+ return d->collapsedOverlayRoot;
+}
+
+bool TimelineRenderState::isEmpty() const
+{
+ Q_D(const TimelineRenderState);
+ return d->collapsedRowRoot->childCount() == 0 && d->expandedRowRoot->childCount() == 0 &&
+ d->collapsedOverlayRoot->childCount() == 0 && d->expandedOverlayRoot->childCount() == 0;
+}
+
+void TimelineRenderState::assembleNodeTree(const TimelineModel *model, int defaultRowHeight,
+ int defaultRowOffset)
+{
+ Q_D(TimelineRenderState);
+ for (int pass = 0; pass < d->passes.length(); ++pass) {
+ const TimelineRenderPass::State *passState = d->passes[pass];
+ if (!passState)
+ continue;
+ if (passState->expandedOverlay())
+ d->expandedOverlayRoot->appendChildNode(passState->expandedOverlay());
+ if (passState->collapsedOverlay())
+ d->collapsedOverlayRoot->appendChildNode(passState->collapsedOverlay());
+ }
+
+ int row = 0;
+ for (int i = 0; i < model->expandedRowCount(); ++i) {
+ QSGTransformNode *rowNode = new QSGTransformNode;
+ for (int pass = 0; pass < d->passes.length(); ++pass) {
+ const TimelineRenderPass::State *passState = d->passes[pass];
+ if (!passState)
+ continue;
+ const QVector<QSGNode *> &rows = passState->expandedRows();
+ if (rows.length() > row) {
+ QSGNode *rowChildNode = rows[row];
+ if (rowChildNode)
+ rowNode->appendChildNode(rowChildNode);
+ }
+ }
+ d->expandedRowRoot->appendChildNode(rowNode);
+ ++row;
+ }
+
+ for (int row = 0; row < model->collapsedRowCount(); ++row) {
+ QSGTransformNode *rowNode = new QSGTransformNode;
+ QMatrix4x4 matrix;
+ matrix.translate(0, row * defaultRowOffset, 0);
+ matrix.scale(1.0, static_cast<float>(defaultRowHeight) /
+ static_cast<float>(TimelineModel::defaultRowHeight()), 1.0);
+ rowNode->setMatrix(matrix);
+ for (int pass = 0; pass < d->passes.length(); ++pass) {
+ const TimelineRenderPass::State *passState = d->passes[pass];
+ if (!passState)
+ continue;
+ const QVector<QSGNode *> &rows = passState->collapsedRows();
+ if (rows.length() > row) {
+ QSGNode *rowChildNode = rows[row];
+ if (rowChildNode)
+ rowNode->appendChildNode(rowChildNode);
+ }
+ }
+ d->collapsedRowRoot->appendChildNode(rowNode);
+ }
+
+ updateExpandedRowHeights(model, defaultRowHeight, defaultRowOffset);
+}
+
+void TimelineRenderState::updateExpandedRowHeights(const TimelineModel *model, int defaultRowHeight,
+ int defaultRowOffset)
+{
+ Q_D(TimelineRenderState);
+ int row = 0;
+ qreal offset = 0;
+ for (QSGNode *rowNode = d->expandedRowRoot->firstChild(); rowNode != 0;
+ rowNode = rowNode->nextSibling()) {
+ qreal rowHeight = model->expandedRowHeight(row++);
+ QMatrix4x4 matrix;
+ matrix.translate(0, offset, 0);
+ matrix.scale(1, rowHeight / defaultRowHeight, 1);
+ offset += defaultRowOffset * rowHeight / defaultRowHeight;
+ static_cast<QSGTransformNode *>(rowNode)->setMatrix(matrix);
+ }
+}
+
+QSGTransformNode *TimelineRenderState::finalize(QSGNode *oldNode, bool expanded,
+ const QMatrix4x4 &transform)
+{
+ Q_D(TimelineRenderState);
+ QSGNode *rowNode = expanded ? d->expandedRowRoot : d->collapsedRowRoot;
+ QSGNode *overlayNode = expanded ?d->expandedOverlayRoot : d->collapsedOverlayRoot;
+
+ QSGTransformNode *node = oldNode ? static_cast<QSGTransformNode *>(oldNode) :
+ new QSGTransformNode;
+ node->setMatrix(transform);
+
+ if (node->firstChild() != rowNode || node->lastChild() != overlayNode) {
+ node->removeAllChildNodes();
+ node->appendChildNode(rowNode);
+ node->appendChildNode(overlayNode);
+ }
+ return node;
+}
+
+TimelineRenderPass::State *TimelineRenderState::passState(int i)
+{
+ Q_D(TimelineRenderState);
+ return d->passes[i];
+}
+
+const TimelineRenderPass::State *TimelineRenderState::passState(int i) const
+{
+ Q_D(const TimelineRenderState);
+ return d->passes[i];
+}
+
+void TimelineRenderState::setPassState(int i, TimelineRenderPass::State *state)
+{
+ Q_D(TimelineRenderState);
+ d->passes[i] = state;
+}
+
+} // namespace Timeline
diff --git a/src/libs/timeline/timelinerenderstate.h b/src/libs/timeline/timelinerenderstate.h
new file mode 100644
index 00000000000..29b205cb997
--- /dev/null
+++ b/src/libs/timeline/timelinerenderstate.h
@@ -0,0 +1,77 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINERENDERSTATE_H
+#define TIMELINERENDERSTATE_H
+
+#include <QSGNode>
+#include "timelinerenderpass.h"
+#include "timelinemodel.h"
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineRenderState {
+public:
+ TimelineRenderState(qint64 start, qint64 end, qreal scale, int numPasses);
+ ~TimelineRenderState();
+
+ qint64 start() const;
+ qint64 end() const;
+ qreal scale() const;
+
+ TimelineRenderPass::State *passState(int i);
+ const TimelineRenderPass::State *passState(int i) const;
+ void setPassState(int i, TimelineRenderPass::State *state);
+
+ const QSGNode *expandedRowRoot() const;
+ const QSGNode *collapsedRowRoot() const;
+ const QSGNode *expandedOverlayRoot() const;
+ const QSGNode *collapsedOverlayRoot() const;
+
+ QSGNode *expandedRowRoot();
+ QSGNode *collapsedRowRoot();
+ QSGNode *expandedOverlayRoot();
+ QSGNode *collapsedOverlayRoot();
+
+ bool isEmpty() const;
+ void assembleNodeTree(const TimelineModel *model, int defaultRowHeight, int defaultRowOffset);
+ void updateExpandedRowHeights(const TimelineModel *model, int defaultRowHeight,
+ int defaultRowOffset);
+ QSGTransformNode *finalize(QSGNode *oldNode, bool expanded, const QMatrix4x4 &transform);
+
+private:
+ class TimelineRenderStatePrivate;
+ TimelineRenderStatePrivate *d_ptr;
+ Q_DECLARE_PRIVATE(TimelineRenderState)
+};
+
+} // namespace Timeline
+
+#endif // TIMELINERENDERSTATE_H
diff --git a/src/libs/timeline/timelinerenderstate_p.h b/src/libs/timeline/timelinerenderstate_p.h
new file mode 100644
index 00000000000..47b9912fbb8
--- /dev/null
+++ b/src/libs/timeline/timelinerenderstate_p.h
@@ -0,0 +1,56 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef TIMELINERENDERSTATE_P_H
+#define TIMELINERENDERSTATE_P_H
+
+#include "timelinerenderstate.h"
+
+namespace Timeline {
+
+class TimelineRenderState::TimelineRenderStatePrivate {
+public:
+ QSGNode *expandedRowRoot;
+ QSGNode *collapsedRowRoot;
+ QSGNode *expandedOverlayRoot;
+ QSGNode *collapsedOverlayRoot;
+
+ qint64 start;
+ qint64 end;
+
+ qreal scale; // "native" scale, this stays the same through the life time of a state
+
+ QVector<TimelineRenderPass::State *> passes;
+};
+
+} // namespace Timeline
+
+#endif // TIMELINERENDERSTATE_P_H
+
diff --git a/src/libs/timeline/timelineselectionrenderpass.cpp b/src/libs/timeline/timelineselectionrenderpass.cpp
new file mode 100644
index 00000000000..6fbe69d3012
--- /dev/null
+++ b/src/libs/timeline/timelineselectionrenderpass.cpp
@@ -0,0 +1,150 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelineselectionrenderpass.h"
+#include <QtMath>
+#include <QSGSimpleRectNode>
+
+namespace Timeline {
+
+QSGSimpleRectNode *createSelectionNode()
+{
+ QSGSimpleRectNode *selectionNode = new QSGSimpleRectNode;
+ selectionNode->material()->setFlag(QSGMaterial::Blending, false);
+ selectionNode->setRect(0, 0, 0, 0);
+ QSGSimpleRectNode *selectionChild = new QSGSimpleRectNode;
+ selectionChild->material()->setFlag(QSGMaterial::Blending, false);
+ selectionChild->setRect(0, 0, 0, 0);
+ selectionNode->appendChildNode(selectionChild);
+ return selectionNode;
+}
+
+struct TimelineSelectionRenderPassState : public TimelineRenderPass::State {
+ QSGSimpleRectNode *m_expandedOverlay;
+ QSGSimpleRectNode *m_collapsedOverlay;
+
+ QSGNode *expandedOverlay() const { return m_expandedOverlay; }
+ QSGNode *collapsedOverlay() const { return m_collapsedOverlay; }
+};
+
+TimelineRenderPass::State *TimelineSelectionRenderPass::update(
+ const TimelineAbstractRenderer *renderer, const TimelineRenderState *parentState,
+ State *oldState, int firstIndex, int lastIndex, bool stateChanged, qreal spacing) const
+{
+ Q_UNUSED(stateChanged);
+
+ const TimelineModel *model = renderer->model();
+ if (!model)
+ return oldState;
+
+ TimelineSelectionRenderPassState *state;
+
+ if (oldState == 0) {
+ state = new TimelineSelectionRenderPassState;
+ state->m_expandedOverlay = createSelectionNode();
+ state->m_collapsedOverlay = createSelectionNode();
+ } else {
+ state = static_cast<TimelineSelectionRenderPassState *>(oldState);
+ }
+
+ QSGSimpleRectNode *selectionNode = static_cast<QSGSimpleRectNode *>(model->expanded() ?
+ state->m_expandedOverlay :
+ state->m_collapsedOverlay);
+
+ QSGSimpleRectNode *child = static_cast<QSGSimpleRectNode *>(selectionNode->firstChild());
+ int selectedItem = renderer->selectedItem();
+ if (selectedItem != -1 && selectedItem >= firstIndex && selectedItem < lastIndex) {
+ qreal top = 0;
+ qreal height = 0;
+ if (model->expanded()) {
+ int row = model->expandedRow(selectedItem);
+ int rowHeight = model->expandedRowHeight(row);
+ height = rowHeight * model->relativeHeight(selectedItem);
+ top = model->expandedRowOffset(row) - height + rowHeight;
+ } else {
+ int row = model->collapsedRow(selectedItem);
+ height = TimelineModel::defaultRowHeight() * model->relativeHeight(selectedItem);
+ top = TimelineModel::defaultRowHeight() * (row + 1) - height;
+ }
+
+ qreal left = qMax(model->startTime(selectedItem) - parentState->start(), (qint64)0);
+ qreal right = qMin(parentState->end() - parentState->start(),
+ model->endTime(selectedItem) - parentState->start());
+
+ // Construct from upper left and lower right for better precision. When constructing from
+ // left and width the error on the left border is inherited by the right border. Like this
+ // they're independent.
+
+ QRectF outer(QPointF(qFloor(left * parentState->scale()), top),
+ QPointF(qCeil(right * parentState->scale()), top + height));
+
+ float scaleConversion = parentState->scale() / spacing;
+ float missing = 3.0 - outer.width() / scaleConversion;
+ if (missing > 0.0) {
+ outer.setLeft(outer.left() - missing * scaleConversion / 2.0);
+ outer.setRight(outer.right() + missing * scaleConversion / 2.0);
+ }
+ missing = 3.0 - outer.height();
+ if (missing > 0.0)
+ outer.setTop(outer.top() - missing);
+
+ selectionNode->setRect(outer);
+ selectionNode->setColor(renderer->selectionLocked() ? QColor(96,0,255) : Qt::blue);
+
+ float childWidthThreshold = 6.0 * scaleConversion;
+ if (outer.width() > childWidthThreshold && outer.height() > 6.0) {
+ // Construct from upper left and lower right for better precision
+ child->setRect(QRectF(QPointF(outer.left() + childWidthThreshold / 2.0,
+ outer.top() + 3.0),
+ QPointF(outer.right() - childWidthThreshold / 2.0,
+ outer.bottom() - 3.0)));
+ child->setColor(model->color(selectedItem));
+ } else {
+ child->setRect(0, 0, 0, 0);
+ }
+ } else {
+ selectionNode->setRect(0, 0, 0, 0);
+ child->setRect(0, 0, 0, 0);
+ }
+ return state;
+}
+
+const TimelineSelectionRenderPass *TimelineSelectionRenderPass::instance()
+{
+ static const TimelineSelectionRenderPass pass;
+ return &pass;
+}
+
+TimelineSelectionRenderPass::TimelineSelectionRenderPass()
+{
+}
+
+} // namespace Timeline
diff --git a/src/libs/timeline/timelineselectionrenderpass.h b/src/libs/timeline/timelineselectionrenderpass.h
new file mode 100644
index 00000000000..fc6ee7dff6b
--- /dev/null
+++ b/src/libs/timeline/timelineselectionrenderpass.h
@@ -0,0 +1,56 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINESELECTIONRENDERPASS_H
+#define TIMELINESELECTIONRENDERPASS_H
+
+#include "timelineabstractrenderer.h"
+#include "timelinerenderpass.h"
+#include "timelinerenderstate.h"
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineSelectionRenderPass : public TimelineRenderPass
+{
+public:
+ static const TimelineSelectionRenderPass *instance();
+
+ State *update(const TimelineAbstractRenderer *renderer, const TimelineRenderState *parentState,
+ State *state, int firstIndex, int lastIndex, bool stateChanged,
+ qreal spacing) const;
+
+protected:
+ TimelineSelectionRenderPass();
+};
+
+} // namespace Timeline
+
+#endif // TIMELINESELECTIONRENDERPASS_H
+
diff --git a/src/libs/timeline/timelinezoomcontrol.cpp b/src/libs/timeline/timelinezoomcontrol.cpp
new file mode 100644
index 00000000000..c31539af789
--- /dev/null
+++ b/src/libs/timeline/timelinezoomcontrol.cpp
@@ -0,0 +1,173 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "timelinezoomcontrol.h"
+
+namespace Timeline {
+
+TimelineZoomControl::TimelineZoomControl(QObject *parent) : QObject(parent), m_traceStart(-1), m_traceEnd(-1),
+ m_windowStart(-1), m_windowEnd(-1), m_rangeStart(-1), m_rangeEnd(-1), m_windowLocked(false)
+{
+ connect(&m_timer, &QTimer::timeout, this, &TimelineZoomControl::moveWindow);
+}
+
+void TimelineZoomControl::clear()
+{
+ m_timer.stop();
+ setWindowLocked(false);
+ setRange(-1, -1);
+ setTrace(-1, -1);
+}
+
+void TimelineZoomControl::setTraceStart(qint64 start)
+{
+ if (start != m_traceStart) {
+ if (m_traceEnd < start)
+ m_traceEnd = start;
+ m_traceStart = start;
+ emit traceChanged(start, m_traceEnd);
+ rebuildWindow();
+ }
+}
+
+void TimelineZoomControl::setTraceEnd(qint64 end)
+{
+ if (end != m_traceEnd) {
+ if (m_traceStart > end)
+ m_traceStart = end;
+ m_traceEnd = end;
+ emit traceChanged(m_traceStart, end);
+ rebuildWindow();
+ }
+}
+
+void TimelineZoomControl::setTrace(qint64 start, qint64 end)
+{
+ Q_ASSERT(start <= end);
+ if (start != m_traceStart || end != m_traceEnd) {
+ m_traceStart = start;
+ m_traceEnd = end;
+ emit traceChanged(start, end);
+ rebuildWindow();
+ }
+}
+
+void TimelineZoomControl::setRange(qint64 start, qint64 end)
+{
+ Q_ASSERT(start <= end);
+ if (m_rangeStart != start || m_rangeEnd != end) {
+ m_timer.stop();
+ m_rangeStart = start;
+ m_rangeEnd = end;
+ rebuildWindow();
+ emit rangeChanged(start, end);
+ }
+}
+
+void TimelineZoomControl::setWindowLocked(bool windowLocked)
+{
+ if (windowLocked != m_windowLocked) {
+ m_windowLocked = windowLocked;
+ emit windowLockedChanged(windowLocked);
+ }
+}
+
+void TimelineZoomControl::rebuildWindow()
+{
+ qint64 minDuration = 1; // qMax needs equal data types, so literal 1 won't do
+ qint64 shownDuration = qMax(rangeDuration(), minDuration);
+
+ qint64 oldWindowStart = m_windowStart;
+ qint64 oldWindowEnd = m_windowEnd;
+ if (traceDuration() / shownDuration < MAX_ZOOM_FACTOR) {
+ m_windowStart = m_traceStart;
+ m_windowEnd = m_traceEnd;
+ } else if (windowDuration() / shownDuration > MAX_ZOOM_FACTOR ||
+ windowDuration() / shownDuration * 2 < MAX_ZOOM_FACTOR) {
+ qint64 keep = shownDuration * MAX_ZOOM_FACTOR / 2 - shownDuration;
+ m_windowStart = m_rangeStart - keep;
+ if (m_windowStart < m_traceStart) {
+ keep += m_traceStart - m_windowStart;
+ m_windowStart = m_traceStart;
+ }
+
+ m_windowEnd = m_rangeEnd + keep;
+ if (m_windowEnd > m_traceEnd) {
+ m_windowStart = qMax(m_traceStart, m_windowStart - m_windowEnd - m_traceEnd);
+ m_windowEnd = m_traceEnd;
+ }
+ } else {
+ m_timer.start(500);
+ }
+ if (oldWindowStart != m_windowStart || oldWindowEnd != m_windowEnd) {
+ clampRangeToWindow();
+ emit windowChanged(m_windowStart, m_windowEnd);
+ }
+}
+
+void TimelineZoomControl::moveWindow()
+{
+ if (m_windowLocked)
+ return;
+ m_timer.stop();
+
+ qint64 offset = (m_rangeEnd - m_windowEnd + m_rangeStart - m_windowStart) / 2;
+ if (offset == 0 || (offset < 0 && m_windowStart == m_traceStart) ||
+ (offset > 0 && m_windowEnd == m_traceEnd)) {
+ return;
+ } else if (offset > rangeDuration()) {
+ offset = (offset + rangeDuration()) / 2;
+ } else if (offset < -rangeDuration()) {
+ offset = (offset - rangeDuration()) / 2;
+ }
+ m_windowStart += offset;
+ if (m_windowStart < m_traceStart) {
+ m_windowEnd += m_traceStart - m_windowStart;
+ m_windowStart = m_traceStart;
+ }
+ m_windowEnd += offset;
+ if (m_windowEnd > m_traceEnd) {
+ m_windowStart -= m_windowEnd - m_traceEnd;
+ m_windowEnd = m_traceEnd;
+ }
+
+ clampRangeToWindow();
+ emit windowChanged(m_windowStart, m_windowEnd);
+ m_timer.start(100);
+}
+
+void TimelineZoomControl::clampRangeToWindow()
+{
+ qint64 rangeStart = qMin(qMax(m_rangeStart, m_windowStart), m_windowEnd);
+ qint64 rangeEnd = qMin(qMax(rangeStart, m_rangeEnd), m_windowEnd);
+ if (rangeStart != m_rangeStart || rangeEnd != m_rangeEnd)
+ setRange(rangeStart, rangeEnd);
+}
+
+} // namespace Timeline
diff --git a/src/libs/timeline/timelinezoomcontrol.h b/src/libs/timeline/timelinezoomcontrol.h
new file mode 100644
index 00000000000..6b7dcc144e0
--- /dev/null
+++ b/src/libs/timeline/timelinezoomcontrol.h
@@ -0,0 +1,108 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 TIMELINEZOOMCONTROL_H
+#define TIMELINEZOOMCONTROL_H
+
+#include "timeline_global.h"
+#include <QTimer>
+
+namespace Timeline {
+
+class TIMELINE_EXPORT TimelineZoomControl : public QObject {
+ Q_OBJECT
+
+ Q_PROPERTY(qint64 traceStart READ traceStart WRITE setTraceStart NOTIFY traceChanged)
+ Q_PROPERTY(qint64 traceEnd READ traceEnd WRITE setTraceEnd NOTIFY traceChanged)
+ Q_PROPERTY(qint64 traceDuration READ traceDuration NOTIFY traceChanged)
+
+ Q_PROPERTY(qint64 windowStart READ windowStart NOTIFY windowChanged)
+ Q_PROPERTY(qint64 windowEnd READ windowEnd NOTIFY windowChanged)
+ Q_PROPERTY(qint64 windowDuration READ windowDuration NOTIFY windowChanged)
+
+ Q_PROPERTY(qint64 rangeStart READ rangeStart NOTIFY rangeChanged)
+ Q_PROPERTY(qint64 rangeEnd READ rangeEnd NOTIFY rangeChanged)
+ Q_PROPERTY(qint64 rangeDuration READ rangeDuration NOTIFY rangeChanged)
+
+ Q_PROPERTY(bool windowLocked READ windowLocked WRITE setWindowLocked NOTIFY windowLockedChanged)
+
+public:
+ static const qint64 MAX_ZOOM_FACTOR = 1 << 10;
+
+ TimelineZoomControl(QObject *parent = 0);
+ qint64 traceStart() const { return m_traceStart; }
+ qint64 traceEnd() const { return m_traceEnd; }
+ qint64 traceDuration() const { return m_traceEnd - m_traceStart; }
+
+ qint64 windowStart() const { return m_windowStart; }
+ qint64 windowEnd() const { return m_windowEnd; }
+ qint64 windowDuration() const { return m_windowEnd - m_windowStart; }
+
+ qint64 rangeStart() const { return m_rangeStart; }
+ qint64 rangeEnd() const { return m_rangeEnd; }
+ qint64 rangeDuration() const { return m_rangeEnd - m_rangeStart; }
+
+ bool windowLocked() const { return m_windowLocked; }
+ virtual void clear();
+
+signals:
+ void traceChanged(qint64 start, qint64 end);
+ void windowChanged(qint64 start, qint64 end);
+ void rangeChanged(qint64 start, qint64 end);
+ void windowLockedChanged(bool windowLocked);
+
+public slots:
+ void setTraceStart(qint64 start);
+ void setTraceEnd(qint64 end);
+ void setTrace(qint64 start, qint64 end);
+ void setRange(qint64 start, qint64 end);
+ void setWindowLocked(bool windowLocked);
+
+protected slots:
+ void moveWindow();
+
+protected:
+ qint64 m_traceStart;
+ qint64 m_traceEnd;
+ qint64 m_windowStart;
+ qint64 m_windowEnd;
+ qint64 m_rangeStart;
+ qint64 m_rangeEnd;
+
+ QTimer m_timer;
+ bool m_windowLocked;
+
+ void rebuildWindow();
+ void clampRangeToWindow();
+};
+
+} // namespace Timeline
+
+#endif // TIMELINEZOOMCONTROL_H
diff --git a/src/libs/utils/algorithm.h b/src/libs/utils/algorithm.h
index 5d79c6f2d47..0fb7a35a418 100644
--- a/src/libs/utils/algorithm.h
+++ b/src/libs/utils/algorithm.h
@@ -324,7 +324,7 @@ template<template<typename> class C, // result container type
typename R,
typename S>
Q_REQUIRED_RESULT
-auto transform(const SC &container, R (S::*p)())
+auto transform(const SC &container, R (S::*p)() const)
-> C<typename RemoveCvAndReference<R>::type>
{
return TransformImpl<
diff --git a/src/libs/utils/basetreeview.cpp b/src/libs/utils/basetreeview.cpp
index a6af74a9e4e..f87a7ba7f02 100644
--- a/src/libs/utils/basetreeview.cpp
+++ b/src/libs/utils/basetreeview.cpp
@@ -30,6 +30,8 @@
#include "basetreeview.h"
+#include "progressindicator.h"
+
#include <utils/qtcassert.h>
#include <QDebug>
@@ -54,7 +56,7 @@ class BaseTreeViewPrivate : public QObject
public:
explicit BaseTreeViewPrivate(BaseTreeView *parent)
- : q(parent), m_settings(0), m_expectUserChanges(false)
+ : q(parent), m_settings(0), m_expectUserChanges(false), m_progressIndicator(0)
{}
bool eventFilter(QObject *, QEvent *event)
@@ -122,7 +124,7 @@ public:
}
}
- Q_SLOT void handleSectionResized(int logicalIndex, int /*oldSize*/, int newSize)
+ void handleSectionResized(int logicalIndex, int /*oldSize*/, int newSize)
{
if (m_expectUserChanges) {
m_userHandled[logicalIndex] = newSize;
@@ -157,7 +159,7 @@ public:
return minimum;
}
- Q_SLOT void resizeColumns()
+ Q_SLOT void resizeColumns() // Needs moc, see BaseTreeView::setModel
{
QHeaderView *h = q->header();
QTC_ASSERT(h, return);
@@ -176,17 +178,7 @@ public:
}
}
- Q_SLOT void rowActivatedHelper(const QModelIndex &index)
- {
- q->rowActivated(index);
- }
-
- Q_SLOT void rowClickedHelper(const QModelIndex &index)
- {
- q->rowClicked(index);
- }
-
- Q_SLOT void toggleColumnWidth(int logicalIndex)
+ void toggleColumnWidth(int logicalIndex)
{
QHeaderView *h = q->header();
const int currentSize = h->sectionSize(logicalIndex);
@@ -211,6 +203,7 @@ public:
QSettings *m_settings;
QString m_settingsKey;
bool m_expectUserChanges;
+ ProgressIndicator *m_progressIndicator;
};
class BaseTreeViewDelegate : public QItemDelegate
@@ -251,14 +244,15 @@ BaseTreeView::BaseTreeView(QWidget *parent)
h->setSectionsClickable(true);
h->viewport()->installEventFilter(d);
- connect(this, SIGNAL(activated(QModelIndex)),
- d, SLOT(rowActivatedHelper(QModelIndex)));
- connect(this, SIGNAL(clicked(QModelIndex)),
- d, SLOT(rowClickedHelper(QModelIndex)));
- connect(h, SIGNAL(sectionClicked(int)),
- d, SLOT(toggleColumnWidth(int)));
- connect(h, SIGNAL(sectionResized(int,int,int)),
- d, SLOT(handleSectionResized(int,int,int)));
+ connect(this, &QAbstractItemView::activated,
+ this, &BaseTreeView::rowActivated);
+ connect(this, &QAbstractItemView::clicked,
+ this, &BaseTreeView::rowClicked);
+
+ connect(h, &QHeaderView::sectionClicked,
+ d, &BaseTreeViewPrivate::toggleColumnWidth);
+ connect(h, &QHeaderView::sectionResized,
+ d, &BaseTreeViewPrivate::handleSectionResized);
}
BaseTreeView::~BaseTreeView()
@@ -268,18 +262,36 @@ BaseTreeView::~BaseTreeView()
void BaseTreeView::setModel(QAbstractItemModel *m)
{
+ struct ExtraConnection {
+ const char *signature;
+ const char *qsignal;
+ QObject *receiver;
+ const char *qslot;
+ };
+#define DESC(sign, receiver, slot) { #sign, SIGNAL(sign), receiver, SLOT(slot) }
+ const ExtraConnection c[] = {
+ DESC(columnAdjustmentRequested(), d, resizeColumns()),
+ DESC(requestExpansion(QModelIndex), this, expand(QModelIndex))
+ };
+#undef DESC
+
QAbstractItemModel *oldModel = model();
- const char *sig = "columnAdjustmentRequested()";
if (oldModel) {
- int index = model()->metaObject()->indexOfSignal(sig);
- if (index != -1)
- disconnect(model(), SIGNAL(columnAdjustmentRequested()), d, SLOT(resizeColumns()));
+ for (unsigned i = 0; i < sizeof(c) / sizeof(c[0]); ++i) {
+ int index = model()->metaObject()->indexOfSignal(c[i].signature);
+ if (index != -1)
+ disconnect(model(), c[i].qsignal, c[i].receiver, c[i].qslot);
+ }
}
+
TreeView::setModel(m);
+
if (m) {
- int index = m->metaObject()->indexOfSignal(sig);
- if (index != -1)
- connect(m, SIGNAL(columnAdjustmentRequested()), d, SLOT(resizeColumns()));
+ for (unsigned i = 0; i < sizeof(c) / sizeof(c[0]); ++i) {
+ int index = m->metaObject()->indexOfSignal(c[i].signature);
+ if (index != -1)
+ connect(model(), c[i].qsignal, c[i].receiver, c[i].qslot);
+ }
d->restoreState();
}
}
@@ -292,6 +304,32 @@ void BaseTreeView::mousePressEvent(QMouseEvent *ev)
d->toggleColumnWidth(columnAt(ev->x()));
}
+/*!
+ Shows a round spinning progress indicator on top of the tree view.
+ Creates a progress indicator widget if necessary.
+ \sa hideProgressIndicator()
+ */
+void BaseTreeView::showProgressIndicator()
+{
+ if (!d->m_progressIndicator) {
+ d->m_progressIndicator = new ProgressIndicator(ProgressIndicator::Large);
+ d->m_progressIndicator->attachToWidget(this);
+ }
+ d->m_progressIndicator->show();
+}
+
+/*!
+ Hides the round spinning progress indicator that was shown with
+ BaseTreeView::showProgressIndicator(). Note that the progress indicator widget is not
+ destroyed.
+ \sa showProgressIndicator()
+ */
+void BaseTreeView::hideProgressIndicator()
+{
+ QTC_ASSERT(d->m_progressIndicator, return);
+ d->m_progressIndicator->hide();
+}
+
void BaseTreeView::setSettings(QSettings *settings, const QByteArray &key)
{
QTC_ASSERT(!d->m_settings, qDebug() << "DUPLICATED setSettings" << key);
diff --git a/src/libs/utils/basetreeview.h b/src/libs/utils/basetreeview.h
index cde60b92889..777f1f51291 100644
--- a/src/libs/utils/basetreeview.h
+++ b/src/libs/utils/basetreeview.h
@@ -59,6 +59,9 @@ public:
virtual void rowClicked(const QModelIndex &) {}
void mousePressEvent(QMouseEvent *ev);
+ void showProgressIndicator();
+ void hideProgressIndicator();
+
public slots:
void setAlternatingRowColorsHelper(bool on) { setAlternatingRowColors(on); }
diff --git a/src/libs/utils/checkablemessagebox.cpp b/src/libs/utils/checkablemessagebox.cpp
index 28e88183941..2a5126c030c 100644
--- a/src/libs/utils/checkablemessagebox.cpp
+++ b/src/libs/utils/checkablemessagebox.cpp
@@ -288,6 +288,49 @@ QMessageBox::StandardButton CheckableMessageBox::dialogButtonBoxToMessageBoxButt
return static_cast<QMessageBox::StandardButton>(int(db));
}
+bool askAgain(QSettings *settings, const QString &settingsSubKey)
+{
+ QTC_CHECK(settings);
+ if (settings) {
+ settings->beginGroup(QLatin1String(kDoNotAskAgainKey));
+ bool shouldNotAsk = settings->value(settingsSubKey, false).toBool();
+ settings->endGroup();
+ if (shouldNotAsk)
+ return false;
+ }
+ return true;
+}
+
+enum DoNotAskAgainType{Question, Information};
+
+void initDoNotAskAgainMessageBox(CheckableMessageBox &messageBox, const QString &title,
+ const QString &text, QDialogButtonBox::StandardButtons buttons,
+ QDialogButtonBox::StandardButton defaultButton,
+ DoNotAskAgainType type)
+{
+ messageBox.setWindowTitle(title);
+ messageBox.setIconPixmap(QMessageBox::standardIcon(type == Information
+ ? QMessageBox::Information
+ : QMessageBox::Question));
+ messageBox.setText(text);
+ messageBox.setCheckBoxVisible(true);
+ messageBox.setCheckBoxText(type == Information ? CheckableMessageBox::msgDoNotShowAgain()
+ : CheckableMessageBox::msgDoNotAskAgain());
+ messageBox.setChecked(false);
+ messageBox.setStandardButtons(buttons);
+ messageBox.setDefaultButton(defaultButton);
+}
+
+void doNotAskAgain(QSettings *settings, const QString &settingsSubKey)
+{
+ if (!settings)
+ return;
+
+ settings->beginGroup(QLatin1String(kDoNotAskAgainKey));
+ settings->setValue(settingsSubKey, true);
+ settings->endGroup();
+}
+
/*!
Shows a message box with given \a title and \a text, and a \gui {Do not ask again} check box.
If the user checks the check box and accepts the dialog with the \a acceptButton,
@@ -306,35 +349,44 @@ CheckableMessageBox::doNotAskAgainQuestion(QWidget *parent, const QString &title
QDialogButtonBox::StandardButton acceptButton)
{
- QTC_CHECK(settings);
- if (settings) {
- settings->beginGroup(QLatin1String(kDoNotAskAgainKey));
- bool shouldNotAsk = settings->value(settingsSubKey, false).toBool();
- settings->endGroup();
- if (shouldNotAsk)
- return acceptButton;
- }
+ if (!askAgain(settings, settingsSubKey))
+ return acceptButton;
- CheckableMessageBox mb(parent);
- mb.setWindowTitle(title);
- mb.setIconPixmap(QMessageBox::standardIcon(QMessageBox::Question));
- mb.setText(text);
- mb.setCheckBoxVisible(true);
- mb.setCheckBoxText(CheckableMessageBox::msgDoNotAskAgain());
- mb.setChecked(false);
- mb.setStandardButtons(buttons);
- mb.setDefaultButton(defaultButton);
- mb.exec();
+ CheckableMessageBox messageBox(parent);
+ initDoNotAskAgainMessageBox(messageBox, title, text, buttons, defaultButton, Question);
+ messageBox.exec();
+ if (messageBox.isChecked() && (messageBox.clickedStandardButton() == acceptButton))
+ doNotAskAgain(settings, settingsSubKey);
- if (settings) {
- settings->beginGroup(QLatin1String(kDoNotAskAgainKey));
- if (mb.isChecked() && (mb.clickedStandardButton() == acceptButton))
- settings->setValue(settingsSubKey, true);
- else // clean up doesn't hurt
- settings->remove(settingsSubKey);
- settings->endGroup();
- }
- return mb.clickedStandardButton();
+ return messageBox.clickedStandardButton();
+}
+
+/*!
+ Shows a message box with given \a title and \a text, and a \gui {Do not show again} check box.
+ If the user checks the check box and quits the dialog, further invocations of this
+ function with the same \a settings and \a settingsSubKey will not show the dialog, but instantly return.
+
+ Returns the clicked button, or QDialogButtonBox::NoButton if the user rejects the dialog
+ with the escape key, or \a defaultButton if the dialog is suppressed.
+*/
+QDialogButtonBox::StandardButton
+CheckableMessageBox::doNotShowAgainInformation(QWidget *parent, const QString &title,
+ const QString &text, QSettings *settings,
+ const QString &settingsSubKey,
+ QDialogButtonBox::StandardButtons buttons,
+ QDialogButtonBox::StandardButton defaultButton)
+
+{
+ if (!askAgain(settings, settingsSubKey))
+ return defaultButton;
+
+ CheckableMessageBox messageBox(parent);
+ initDoNotAskAgainMessageBox(messageBox, title, text, buttons, defaultButton, Information);
+ messageBox.exec();
+ if (messageBox.isChecked())
+ doNotAskAgain(settings, settingsSubKey);
+
+ return messageBox.clickedStandardButton();
}
/*!
@@ -377,4 +429,13 @@ QString CheckableMessageBox::msgDoNotAskAgain()
return QApplication::translate("Utils::CheckableMessageBox", "Do not &ask again");
}
+/*!
+ Returns the standard \gui {Do not show again} check box text.
+ \sa doNotShowAgainInformation()
+*/
+QString CheckableMessageBox::msgDoNotShowAgain()
+{
+ return QApplication::translate("Utils::CheckableMessageBox", "Do not &show again");
+}
+
} // namespace Utils
diff --git a/src/libs/utils/checkablemessagebox.h b/src/libs/utils/checkablemessagebox.h
index 3c0e241659b..894d955a64f 100644
--- a/src/libs/utils/checkablemessagebox.h
+++ b/src/libs/utils/checkablemessagebox.h
@@ -86,6 +86,15 @@ public:
QDialogButtonBox::StandardButton defaultButton = QDialogButtonBox::No,
QDialogButtonBox::StandardButton acceptButton = QDialogButtonBox::Yes);
+ static QDialogButtonBox::StandardButton
+ doNotShowAgainInformation(QWidget *parent,
+ const QString &title,
+ const QString &text,
+ QSettings *settings,
+ const QString &settingsSubKey,
+ QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Ok,
+ QDialogButtonBox::StandardButton defaultButton = QDialogButtonBox::NoButton);
+
QString text() const;
void setText(const QString &);
@@ -119,6 +128,7 @@ public:
static void resetAllDoNotAskAgainQuestions(QSettings *settings);
static bool hasSuppressedQuestions(QSettings *settings);
static QString msgDoNotAskAgain();
+ static QString msgDoNotShowAgain();
private slots:
void slotClicked(QAbstractButton *b);
diff --git a/src/libs/utils/elfreader.cpp b/src/libs/utils/elfreader.cpp
index 29f33d19cfe..bc34ca3622a 100644
--- a/src/libs/utils/elfreader.cpp
+++ b/src/libs/utils/elfreader.cpp
@@ -117,7 +117,7 @@ bool ElfMapper::map()
// Try reading the data into memory instead.
try {
raw = file.readAll();
- } catch (std::bad_alloc &) {
+ } catch (const std::bad_alloc &) {
return false;
}
start = raw.constData();
diff --git a/src/libs/utils/fadingindicator.cpp b/src/libs/utils/fadingindicator.cpp
new file mode 100644
index 00000000000..ee8c2c70b3a
--- /dev/null
+++ b/src/libs/utils/fadingindicator.cpp
@@ -0,0 +1,146 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "fadingindicator.h"
+
+#include "stylehelper.h"
+
+#include <QGraphicsOpacityEffect>
+#include <QHBoxLayout>
+#include <QLabel>
+#include <QPainter>
+#include <QPixmap>
+#include <QPropertyAnimation>
+#include <QTimer>
+
+namespace Utils {
+namespace Internal {
+
+class FadingIndicatorPrivate : public QWidget
+{
+ Q_OBJECT
+
+public:
+ FadingIndicatorPrivate(QWidget *parent = 0)
+ : QWidget(parent)
+ {
+ m_effect = new QGraphicsOpacityEffect(this);
+ setGraphicsEffect(m_effect);
+ m_effect->setOpacity(1.);
+
+ m_label = new QLabel;
+ QFont font = m_label->font();
+ font.setPixelSize(45);
+ m_label->setFont(font);
+ QPalette pal = palette();
+ pal.setColor(QPalette::Foreground, pal.color(QPalette::Background));
+ m_label->setPalette(pal);
+ auto layout = new QHBoxLayout;
+ setLayout(layout);
+ layout->addWidget(m_label);
+ }
+
+ void setText(const QString &text)
+ {
+ m_pixmap = QPixmap();
+ m_label->setText(text);
+ adjustSize();
+ if (QWidget *parent = parentWidget())
+ move(parent->rect().center() - rect().center());
+ }
+
+ void setPixmap(const QString &uri)
+ {
+ m_label->hide();
+ m_pixmap.load(Utils::StyleHelper::dpiSpecificImageFile(uri));
+ resize(m_pixmap.size() / m_pixmap.devicePixelRatio());
+ if (QWidget *parent = parentWidget())
+ move(parent->rect().center() - rect().center());
+ }
+
+ void run(int ms)
+ {
+ show();
+ raise();
+ QTimer::singleShot(ms, this, SLOT(runInternal()));
+ }
+
+protected:
+ void paintEvent(QPaintEvent *)
+ {
+ QPainter p(this);
+ p.setRenderHint(QPainter::Antialiasing);
+ if (!m_pixmap.isNull()) {
+ p.drawPixmap(rect(), m_pixmap);
+ } else {
+ p.setBrush(palette().color(QPalette::Foreground));
+ p.setPen(Qt::NoPen);
+ p.drawRoundedRect(rect(), 15, 15);
+ }
+ }
+
+private slots:
+ void runInternal()
+ {
+ QPropertyAnimation *anim = new QPropertyAnimation(m_effect, "opacity", this);
+ anim->setDuration(200);
+ anim->setEndValue(0.);
+ connect(anim, SIGNAL(finished()), this, SLOT(deleteLater()));
+ anim->start(QAbstractAnimation::DeleteWhenStopped);
+ }
+
+private:
+ QGraphicsOpacityEffect *m_effect;
+ QLabel *m_label;
+ QPixmap m_pixmap;
+};
+
+} // Internal
+
+namespace FadingIndicator {
+
+void showText(QWidget *parent, const QString &text)
+{
+ auto indicator = new Internal::FadingIndicatorPrivate(parent);
+ indicator->setText(text);
+ indicator->run(1000); // deletes itself
+}
+
+void showPixmap(QWidget *parent, const QString &pixmap)
+{
+ auto indicator = new Internal::FadingIndicatorPrivate(parent);
+ indicator->setPixmap(pixmap);
+ indicator->run(300); // deletes itself
+}
+
+} // FadingIndicator
+} // Utils
+
+#include "fadingindicator.moc"
diff --git a/src/libs/utils/fadingindicator.h b/src/libs/utils/fadingindicator.h
new file mode 100644
index 00000000000..7738e751a64
--- /dev/null
+++ b/src/libs/utils/fadingindicator.h
@@ -0,0 +1,50 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+
+#ifndef FADINGINDICATOR_H
+#define FADINGINDICATOR_H
+
+#include "utils_global.h"
+
+#include <QString>
+#include <QWidget>
+
+namespace Utils {
+namespace FadingIndicator {
+
+QTCREATOR_UTILS_EXPORT void showText(QWidget *parent, const QString &text);
+QTCREATOR_UTILS_EXPORT void showPixmap(QWidget *parent, const QString &pixmap);
+
+} // FadingIndicator
+} // Utils
+
+#endif // FADINGINDICATOR_H
+
diff --git a/src/libs/utils/fancymainwindow.cpp b/src/libs/utils/fancymainwindow.cpp
index 3699e3af55f..097771a2c22 100644
--- a/src/libs/utils/fancymainwindow.cpp
+++ b/src/libs/utils/fancymainwindow.cpp
@@ -199,13 +199,6 @@ public:
QWidget::enterEvent(event);
}
- void leaveEvent(QEvent *event)
- {
- if (!q->isFloating())
- setActive(false);
- QWidget::leaveEvent(event);
- }
-
void setActive(bool on)
{
m_active = on;
@@ -311,6 +304,10 @@ void DockWidget::enterEvent(QEvent *event)
void DockWidget::leaveEvent(QEvent *event)
{
+ if (!isFloating()) {
+ m_timer.stop();
+ m_titleBar->setActive(false);
+ }
QApplication::instance()->removeEventFilter(this);
QDockWidget::leaveEvent(event);
}
diff --git a/src/libs/utils/fileinprojectfinder.cpp b/src/libs/utils/fileinprojectfinder.cpp
index 41110fceb2d..e40b33136b7 100644
--- a/src/libs/utils/fileinprojectfinder.cpp
+++ b/src/libs/utils/fileinprojectfinder.cpp
@@ -29,12 +29,15 @@
****************************************************************************/
#include "fileinprojectfinder.h"
-#include <utils/qtcassert.h>
+#include "fileutils.h"
+#include "qtcassert.h"
#include <QDebug>
#include <QFileInfo>
#include <QUrl>
+#include <algorithm>
+
enum { debug = false };
namespace Utils {
@@ -211,20 +214,19 @@ QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const
}
}
- // find (solely by filename) in project files
+ // find best matching file path in project files
if (debug)
qDebug() << "FileInProjectFinder: checking project files ...";
- const QString fileName = QFileInfo(originalPath).fileName();
- foreach (const QString &f, m_projectFiles) {
- if (QFileInfo(f).fileName() == fileName) {
- m_cache.insert(originalPath, f);
- if (success)
- *success = true;
- if (debug)
- qDebug() << "FileInProjectFinder: found" << f << "in project files";
- return f;
- }
+ const QString matchedFilePath
+ = bestMatch(
+ filesWithSameFileName(FileName::fromString(originalPath).fileName()),
+ originalPath);
+ if (!matchedFilePath.isEmpty()) {
+ m_cache.insert(originalPath, matchedFilePath);
+ if (success)
+ *success = true;
+ return matchedFilePath;
}
if (debug)
@@ -251,4 +253,44 @@ QString FileInProjectFinder::findFile(const QUrl &fileUrl, bool *success) const
return originalPath;
}
+QStringList FileInProjectFinder::filesWithSameFileName(const QString &fileName) const
+{
+ QStringList result;
+ foreach (const QString &f, m_projectFiles) {
+ if (FileName::fromString(f).fileName() == fileName)
+ result << f;
+ }
+ return result;
+}
+
+int FileInProjectFinder::rankFilePath(const QString &candidatePath, const QString &filePathToFind)
+{
+ int rank = 0;
+ for (int a = candidatePath.length(), b = filePathToFind.length();
+ --a >= 0 && --b >= 0 && candidatePath.at(a) == filePathToFind.at(b);)
+ rank++;
+ return rank;
+}
+
+QString FileInProjectFinder::bestMatch(const QStringList &filePaths, const QString &filePathToFind)
+{
+ if (filePaths.isEmpty())
+ return QString();
+ if (filePaths.length() == 1) {
+ if (debug)
+ qDebug() << "FileInProjectFinder: found" << filePaths.first() << "in project files";
+ return filePaths.first();
+ }
+ auto it = std::max_element(filePaths.constBegin(), filePaths.constEnd(),
+ [&filePathToFind] (const QString &a, const QString &b) -> bool {
+ return rankFilePath(a, filePathToFind) < rankFilePath(b, filePathToFind);
+ });
+ if (it != filePaths.cend()) {
+ if (debug)
+ qDebug() << "FileInProjectFinder: found best match" << *it << "in project files";
+ return *it;
+ }
+ return QString();
+}
+
} // namespace Utils
diff --git a/src/libs/utils/fileinprojectfinder.h b/src/libs/utils/fileinprojectfinder.h
index 253c747da58..c208ba2ecfd 100644
--- a/src/libs/utils/fileinprojectfinder.h
+++ b/src/libs/utils/fileinprojectfinder.h
@@ -54,6 +54,10 @@ public:
QString findFile(const QUrl &fileUrl, bool *success = 0) const;
private:
+ QStringList filesWithSameFileName(const QString &fileName) const;
+ static int rankFilePath(const QString &candidatePath, const QString &filePathToFind);
+ static QString bestMatch(const QStringList &filePaths, const QString &filePathToFind);
+
QString m_projectDir;
QString m_sysroot;
QStringList m_projectFiles;
diff --git a/src/libs/utils/fileutils.cpp b/src/libs/utils/fileutils.cpp
index 78c8809a282..2c8baf56249 100644
--- a/src/libs/utils/fileutils.cpp
+++ b/src/libs/utils/fileutils.cpp
@@ -156,7 +156,7 @@ bool FileUtils::copyRecursively(const FileName &srcFilePath, const FileName &tgt
if (!tgtFilePath.exists()) {
QDir targetDir(tgtFilePath.toString());
targetDir.cdUp();
- if (!targetDir.mkdir(tgtFilePath.toFileInfo().fileName())) {
+ if (!targetDir.mkdir(tgtFilePath.fileName())) {
if (error) {
*error = QCoreApplication::translate("Utils::FileUtils", "Failed to create directory \"%1\".")
.arg(tgtFilePath.toUserOutput());
@@ -560,6 +560,30 @@ QString FileName::toUserOutput() const
return QDir::toNativeSeparators(toString());
}
+QString FileName::fileName(int pathComponents) const
+{
+ if (pathComponents < 0)
+ return *this;
+ const QChar slash = QLatin1Char('/');
+ QTC_CHECK(!endsWith(slash));
+ int i = lastIndexOf(slash);
+ if (pathComponents == 0 || i == -1)
+ return mid(i + 1);
+ int component = i + 1;
+ // skip adjacent slashes
+ while (i > 0 && at(--i) == slash);
+ while (i >= 0 && --pathComponents >= 0) {
+ i = lastIndexOf(slash, i);
+ component = i + 1;
+ while (i > 0 && at(--i) == slash);
+ }
+
+ // If there are no more slashes before the found one, return the entire string
+ if (i > 0 && lastIndexOf(slash, i) != -1)
+ return mid(component);
+ return *this;
+}
+
/// \returns a bool indicating whether a file with this
/// FileName exists.
bool FileName::exists() const
@@ -633,6 +657,13 @@ FileName FileName::fromUserInput(const QString &filename)
return FileName(clean);
}
+/// Constructs a FileName from \a fileName, which is encoded as UTF-8.
+/// \a fileName is not checked for validity.
+FileName FileName::fromUtf8(const char *filename, int filenameSize)
+{
+ return FileName(QString::fromUtf8(filename, filenameSize));
+}
+
FileName::FileName(const QString &string)
: QString(string)
{
@@ -730,6 +761,30 @@ FileName &FileName::appendString(QChar str)
return *this;
}
+QTextStream &operator<<(QTextStream &s, const FileName &fn)
+{
+ return s << fn.toString();
+}
+
+int FileNameList::removeDuplicates()
+{
+ QSet<FileName> seen;
+ int removed = 0;
+
+ for (int i = 0; i < size(); ) {
+ const FileName &fn = at(i);
+ if (seen.contains(fn)) {
+ removeAt(i);
+ ++removed;
+ } else {
+ seen.insert(fn);
+ ++i;
+ }
+ }
+
+ return removed;
+}
+
static bool isFileDrop(const QMimeData *d, QList<FileDropSupport::FileSpec> *files = 0)
{
// internal drop
diff --git a/src/libs/utils/fileutils.h b/src/libs/utils/fileutils.h
index 3ddad1697e6..1ffea746a70 100644
--- a/src/libs/utils/fileutils.h
+++ b/src/libs/utils/fileutils.h
@@ -70,8 +70,10 @@ public:
static FileName fromString(const QString &filename, const QString &defaultExtension);
static FileName fromLatin1(const QByteArray &filename);
static FileName fromUserInput(const QString &filename);
+ static FileName fromUtf8(const char *filename, int filenameSize = -1);
QString toString() const;
QString toUserOutput() const;
+ QString fileName(int pathComponents = 0) const;
bool exists() const;
FileName parentDir() const;
@@ -102,6 +104,18 @@ private:
FileName(const QString &string);
};
+QTCREATOR_UTILS_EXPORT QTextStream &operator<<(QTextStream &s, const FileName &fn);
+
+class QTCREATOR_UTILS_EXPORT FileNameList : public QList<FileName>
+{
+public:
+ inline FileNameList() { }
+ inline explicit FileNameList(const FileName &i) { append(i); }
+ inline FileNameList(const FileNameList &l) : QList<FileName>(l) { }
+ inline FileNameList(const QList<FileName> &l) : QList<FileName>(l) { }
+
+ int removeDuplicates();
+};
class QTCREATOR_UTILS_EXPORT FileUtils {
public:
diff --git a/src/libs/utils/images/progressindicator_big.png b/src/libs/utils/images/progressindicator_big.png
new file mode 100644
index 00000000000..ac854f1e25e
--- /dev/null
+++ b/src/libs/utils/images/progressindicator_big.png
Binary files differ
diff --git a/src/libs/utils/images/progressindicator_big@2x.png b/src/libs/utils/images/progressindicator_big@2x.png
new file mode 100644
index 00000000000..23b488f23ab
--- /dev/null
+++ b/src/libs/utils/images/progressindicator_big@2x.png
Binary files differ
diff --git a/src/libs/utils/images/progressindicator_medium.png b/src/libs/utils/images/progressindicator_medium.png
new file mode 100644
index 00000000000..496f6880f2e
--- /dev/null
+++ b/src/libs/utils/images/progressindicator_medium.png
Binary files differ
diff --git a/src/libs/utils/images/progressindicator_medium@2x.png b/src/libs/utils/images/progressindicator_medium@2x.png
new file mode 100644
index 00000000000..c396d400128
--- /dev/null
+++ b/src/libs/utils/images/progressindicator_medium@2x.png
Binary files differ
diff --git a/src/libs/utils/images/progressindicator_small.png b/src/libs/utils/images/progressindicator_small.png
new file mode 100644
index 00000000000..8ba536403d8
--- /dev/null
+++ b/src/libs/utils/images/progressindicator_small.png
Binary files differ
diff --git a/src/libs/utils/images/progressindicator_small@2x.png b/src/libs/utils/images/progressindicator_small@2x.png
new file mode 100644
index 00000000000..e6dc7cc62d1
--- /dev/null
+++ b/src/libs/utils/images/progressindicator_small@2x.png
Binary files differ
diff --git a/src/libs/utils/macroexpander.cpp b/src/libs/utils/macroexpander.cpp
index ee3294f9ec3..4047929f101 100644
--- a/src/libs/utils/macroexpander.cpp
+++ b/src/libs/utils/macroexpander.cpp
@@ -372,7 +372,7 @@ void MacroExpander::registerFileVariables(const QByteArray &prefix,
registerVariable(prefix + kFileNamePostfix,
tr("%1: File name without path.").arg(heading),
- [base]() -> QString { QString tmp = base(); return tmp.isEmpty() ? QString() : QFileInfo(tmp).fileName(); },
+ [base]() -> QString { QString tmp = base(); return tmp.isEmpty() ? QString() : Utils::FileName::fromString(tmp).fileName(); },
visibleInChooser);
registerVariable(prefix + kFileBaseNamePostfix,
diff --git a/src/libs/utils/outputformatter.cpp b/src/libs/utils/outputformatter.cpp
index ef27e3b3803..2235802bab3 100644
--- a/src/libs/utils/outputformatter.cpp
+++ b/src/libs/utils/outputformatter.cpp
@@ -73,8 +73,7 @@ void OutputFormatter::appendMessage(const QString &text, const QTextCharFormat &
QTextCursor cursor(m_plainTextEdit->document());
cursor.movePosition(QTextCursor::End);
- foreach (const FormattedText &output,
- m_escapeCodeHandler->parseText(FormattedText(text, format))) {
+ foreach (const FormattedText &output, parseAnsi(text, format)) {
int startPos = 0;
int crPos = -1;
while ((crPos = output.text.indexOf(QLatin1Char('\r'), startPos)) >= 0) {
@@ -92,6 +91,11 @@ QTextCharFormat OutputFormatter::charFormat(OutputFormat format) const
return m_formats[format];
}
+QList<FormattedText> OutputFormatter::parseAnsi(const QString &text, const QTextCharFormat &format)
+{
+ return m_escapeCodeHandler->parseText(FormattedText(text, format));
+}
+
void OutputFormatter::append(QTextCursor &cursor, const QString &text,
const QTextCharFormat &format)
{
@@ -163,6 +167,5 @@ void OutputFormatter::setFont(const QFont &font)
void OutputFormatter::flush()
{
- if (m_escapeCodeHandler)
- m_escapeCodeHandler->endFormatScope();
+ m_escapeCodeHandler->endFormatScope();
}
diff --git a/src/libs/utils/outputformatter.h b/src/libs/utils/outputformatter.h
index 7280d3e09ef..503e73ab73a 100644
--- a/src/libs/utils/outputformatter.h
+++ b/src/libs/utils/outputformatter.h
@@ -47,6 +47,7 @@ QT_END_NAMESPACE
namespace Utils {
class AnsiEscapeCodeHandler;
+class FormattedText;
class QTCREATOR_UTILS_EXPORT OutputFormatter : public QObject
{
@@ -71,6 +72,7 @@ protected:
void initFormats();
virtual void clearLastLine();
QTextCharFormat charFormat(OutputFormat format) const;
+ QList<Utils::FormattedText> parseAnsi(const QString &text, const QTextCharFormat &format);
void append(QTextCursor &cursor, const QString &text, const QTextCharFormat &format);
private:
diff --git a/src/libs/utils/persistentsettings.cpp b/src/libs/utils/persistentsettings.cpp
index b5493ee5d81..1a69acfc3e2 100644
--- a/src/libs/utils/persistentsettings.cpp
+++ b/src/libs/utils/persistentsettings.cpp
@@ -339,11 +339,11 @@ PersistentSettingsReader::PersistentSettingsReader()
{
}
-QVariant PersistentSettingsReader::restoreValue(const QString &variable) const
+QVariant PersistentSettingsReader::restoreValue(const QString &variable, const QVariant &defaultValue) const
{
if (m_valueMap.contains(variable))
return m_valueMap.value(variable);
- return QVariant();
+ return defaultValue;
}
QVariantMap PersistentSettingsReader::restoreValues() const
diff --git a/src/libs/utils/persistentsettings.h b/src/libs/utils/persistentsettings.h
index c092da9eee1..f8187412d75 100644
--- a/src/libs/utils/persistentsettings.h
+++ b/src/libs/utils/persistentsettings.h
@@ -45,7 +45,7 @@ class QTCREATOR_UTILS_EXPORT PersistentSettingsReader
{
public:
PersistentSettingsReader();
- QVariant restoreValue(const QString &variable) const;
+ QVariant restoreValue(const QString &variable, const QVariant &defaultValue = QVariant()) const;
QVariantMap restoreValues() const;
bool load(const FileName &fileName);
diff --git a/src/libs/utils/portlist.cpp b/src/libs/utils/portlist.cpp
index cdad1958815..5bf0e098fc2 100644
--- a/src/libs/utils/portlist.cpp
+++ b/src/libs/utils/portlist.cpp
@@ -63,7 +63,7 @@ public:
try {
if (!atEnd())
parseElemList();
- } catch (ParseException &e) {
+ } catch (const ParseException &e) {
qWarning("Malformed ports specification: %s", e.error);
}
return m_portList;
diff --git a/src/libs/utils/progressindicator.cpp b/src/libs/utils/progressindicator.cpp
new file mode 100644
index 00000000000..85ce2f1d88a
--- /dev/null
+++ b/src/libs/utils/progressindicator.cpp
@@ -0,0 +1,140 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "progressindicator.h"
+
+#include "qtcassert.h"
+#include "stylehelper.h"
+
+#include <QEvent>
+#include <QPainter>
+#include <QPixmap>
+
+using namespace Utils;
+
+ProgressIndicator::ProgressIndicator(IndicatorSize size, QWidget *parent)
+ : QWidget(parent),
+ m_rotation(0)
+{
+ setAttribute(Qt::WA_TransparentForMouseEvents);
+ m_timer.setSingleShot(false);
+ connect(&m_timer, &QTimer::timeout, this, &ProgressIndicator::step);
+ setIndicatorSize(size);
+}
+
+static QString imageFileNameForIndicatorSize(ProgressIndicator::IndicatorSize size)
+{
+ switch (size) {
+ case ProgressIndicator::Large:
+ return QLatin1String(":/utils/images/progressindicator_big.png");
+ case ProgressIndicator::Medium:
+ return QLatin1String(":/utils/images/progressindicator_medium.png");
+ case ProgressIndicator::Small:
+ default:
+ return QLatin1String(":/utils/images/progressindicator_small.png");
+ }
+}
+
+void ProgressIndicator::setIndicatorSize(ProgressIndicator::IndicatorSize size)
+{
+ m_size = size;
+ m_rotationStep = size == Small ? 45 : 30;
+ m_timer.setInterval(size == Small ? 100 : 80);
+ m_pixmap.load(StyleHelper::dpiSpecificImageFile(
+ imageFileNameForIndicatorSize(size)));
+ updateGeometry();
+}
+
+ProgressIndicator::IndicatorSize ProgressIndicator::indicatorSize() const
+{
+ return m_size;
+}
+
+QSize ProgressIndicator::sizeHint() const
+{
+ return m_pixmap.size() / m_pixmap.devicePixelRatio();
+}
+
+void ProgressIndicator::attachToWidget(QWidget *parent)
+{
+ if (parentWidget())
+ parentWidget()->removeEventFilter(this);
+ setParent(parent);
+ parent->installEventFilter(this);
+ resizeToParent();
+ raise();
+}
+
+void ProgressIndicator::paintEvent(QPaintEvent *)
+{
+ QPainter p(this);
+ p.setRenderHint(QPainter::SmoothPixmapTransform);
+ QPoint translate(rect().width() / 2, rect().height() / 2);
+ QTransform t;
+ t.translate(translate.x(), translate.y());
+ t.rotate(m_rotation);
+ t.translate(-translate.x(), -translate.y());
+ p.setTransform(t);
+ QSize pixmapUserSize(m_pixmap.size() / m_pixmap.devicePixelRatio());
+ p.drawPixmap(QPoint((rect().width() - pixmapUserSize.width()) / 2,
+ (rect().height() - pixmapUserSize.height()) / 2),
+ m_pixmap);
+}
+
+void ProgressIndicator::showEvent(QShowEvent *)
+{
+ m_timer.start();
+}
+
+void ProgressIndicator::hideEvent(QHideEvent *)
+{
+ m_timer.stop();
+}
+
+bool ProgressIndicator::eventFilter(QObject *obj, QEvent *ev)
+{
+ if (obj == parent() && ev->type() == QEvent::Resize) {
+ resizeToParent();
+ }
+ return QWidget::eventFilter(obj, ev);
+}
+
+void ProgressIndicator::step()
+{
+ m_rotation = (m_rotation + m_rotationStep + 360) % 360;
+ update();
+}
+
+void ProgressIndicator::resizeToParent()
+{
+ QTC_ASSERT(parentWidget(), return);
+ setGeometry(QRect(QPoint(0, 0), parentWidget()->size()));
+}
+
diff --git a/src/libs/utils/progressindicator.h b/src/libs/utils/progressindicator.h
new file mode 100644
index 00000000000..30561e2afc8
--- /dev/null
+++ b/src/libs/utils/progressindicator.h
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 PROGRESSINDICATOR_H
+#define PROGRESSINDICATOR_H
+
+#include "utils_global.h"
+
+#include <QTimer>
+#include <QWidget>
+
+namespace Utils {
+
+namespace Internal { class ProgressIndicatorPrivate; }
+
+class QTCREATOR_UTILS_EXPORT ProgressIndicator : public QWidget
+{
+ Q_OBJECT
+public:
+ enum IndicatorSize {
+ Small,
+ Medium,
+ Large
+ };
+
+ explicit ProgressIndicator(IndicatorSize size, QWidget *parent = 0);
+
+ void setIndicatorSize(IndicatorSize size);
+ IndicatorSize indicatorSize() const;
+
+ QSize sizeHint() const;
+
+ void attachToWidget(QWidget *parent);
+
+protected:
+ void paintEvent(QPaintEvent *);
+ void showEvent(QShowEvent *);
+ void hideEvent(QHideEvent *);
+ bool eventFilter(QObject *obj, QEvent *ev);
+
+private:
+ void step();
+ void resizeToParent();
+
+ ProgressIndicator::IndicatorSize m_size;
+ int m_rotationStep;
+ int m_rotation;
+ QTimer m_timer;
+ QPixmap m_pixmap;
+};
+
+} // Utils
+
+#endif // PROGRESSINDICATOR_H
diff --git a/src/libs/utils/projectintropage.cpp b/src/libs/utils/projectintropage.cpp
index 6e5dc7777ca..5769afe7636 100644
--- a/src/libs/utils/projectintropage.cpp
+++ b/src/libs/utils/projectintropage.cpp
@@ -179,10 +179,8 @@ bool ProjectIntroPage::validate()
}
// Check existence of the directory
- QString projectDir = path();
- projectDir += QDir::separator();
- projectDir += d->m_ui.nameLineEdit->text();
- const QFileInfo projectDirFile(projectDir);
+ const QFileInfo projectDirFile(path() + QLatin1Char('/')
+ + QDir::fromNativeSeparators(d->m_ui.nameLineEdit->text()));
if (!projectDirFile.exists()) { // All happy
hideStatusLabel();
return nameValid;
diff --git a/src/libs/utils/reloadpromptutils.cpp b/src/libs/utils/reloadpromptutils.cpp
index 73ae4dabdaf..d20aa0e1aae 100644
--- a/src/libs/utils/reloadpromptutils.cpp
+++ b/src/libs/utils/reloadpromptutils.cpp
@@ -28,6 +28,7 @@
**
****************************************************************************/
+#include "fileutils.h"
#include "reloadpromptutils.h"
#include <QCoreApplication>
@@ -37,7 +38,7 @@
namespace Utils {
-QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &fileName,
+QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const FileName &fileName,
bool modified,
QWidget *parent)
{
@@ -53,8 +54,8 @@ QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &fileName,
msg = QCoreApplication::translate("Utils::reloadPrompt",
"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);
+ msg = msg.arg(fileName.fileName());
+ return reloadPrompt(title, msg, fileName.toUserOutput(), parent);
}
QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &title,
diff --git a/src/libs/utils/reloadpromptutils.h b/src/libs/utils/reloadpromptutils.h
index c3a53c9021c..65e564b438a 100644
--- a/src/libs/utils/reloadpromptutils.h
+++ b/src/libs/utils/reloadpromptutils.h
@@ -39,6 +39,7 @@ class QWidget;
QT_END_NAMESPACE
namespace Utils {
+class FileName;
enum ReloadPromptAnswer {
ReloadCurrent,
@@ -48,7 +49,7 @@ enum ReloadPromptAnswer {
CloseCurrent
};
-QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &fileName,
+QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const FileName &fileName,
bool modified,
QWidget *parent);
QTCREATOR_UTILS_EXPORT ReloadPromptAnswer reloadPrompt(const QString &title,
diff --git a/src/libs/utils/synchronousprocess.cpp b/src/libs/utils/synchronousprocess.cpp
index 0666740641f..6bcc01a8887 100644
--- a/src/libs/utils/synchronousprocess.cpp
+++ b/src/libs/utils/synchronousprocess.cpp
@@ -385,7 +385,7 @@ static bool isGuiThread()
}
SynchronousProcessResponse SynchronousProcess::run(const QString &binary,
- const QStringList &args)
+ const QStringList &args)
{
if (debug)
qDebug() << '>' << Q_FUNC_INFO << binary << args;
diff --git a/src/libs/utils/theme/theme.cpp b/src/libs/utils/theme/theme.cpp
index 3fd18c77c69..97a433e9554 100644
--- a/src/libs/utils/theme/theme.cpp
+++ b/src/libs/utils/theme/theme.cpp
@@ -116,7 +116,7 @@ QPair<QColor, QString> Theme::readNamedColor(const QString &color) const
bool ok = true;
const QRgb rgba = color.toLongLong(&ok, 16);
if (!ok) {
- qWarning("Color '%s' is neither a named color nor a valid color", qPrintable(color));
+ qWarning("Color \"%s\" is neither a named color nor a valid color", qPrintable(color));
return qMakePair(Qt::black, QString());
}
return qMakePair(QColor::fromRgba(rgba), QString());
diff --git a/src/libs/utils/tooltip/tipcontents.cpp b/src/libs/utils/tooltip/tipcontents.cpp
deleted file mode 100644
index e28c3713199..00000000000
--- a/src/libs/utils/tooltip/tipcontents.cpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "tipcontents.h"
-#include "tooltip.h"
-#include "tips.h"
-
-#include <utils/qtcassert.h>
-
-#include <QtGlobal>
-
-namespace Utils {
-
-TipContent::TipContent()
-{}
-
-TipContent::~TipContent()
-{}
-
-ColorContent::ColorContent(const QColor &color) : m_color(color)
-{}
-
-ColorContent::~ColorContent()
-{}
-
-TipContent *ColorContent::clone() const
-{
- return new ColorContent(*this);
-}
-
-int ColorContent::typeId() const
-{
- return COLOR_CONTENT_ID;
-}
-
-bool ColorContent::isValid() const
-{
- return m_color.isValid();
-}
-
-bool ColorContent::isInteractive() const
-{
- return false;
-}
-
-int ColorContent::showTime() const
-{
- return 4000;
-}
-
-bool ColorContent::equals(const TipContent &tipContent) const
-{
- if (typeId() == tipContent.typeId()) {
- if (m_color == static_cast<const ColorContent &>(tipContent).m_color)
- return true;
- }
- return false;
-}
-
-const QColor &ColorContent::color() const
-{
- return m_color;
-}
-
-TextContent::TextContent(const QString &text) : m_text(text)
-{}
-
-TextContent::~TextContent()
-{}
-
-TipContent *TextContent::clone() const
-{
- return new TextContent(*this);
-}
-
-int TextContent::typeId() const
-{
- return TEXT_CONTENT_ID;
-}
-
-bool TextContent::isValid() const
-{
- return !m_text.isEmpty();
-}
-
-bool TextContent::isInteractive() const
-{
- return false;
-}
-
-int TextContent::showTime() const
-{
- return 10000 + 40 * qMax(0, m_text.length() - 100);
-}
-
-bool TextContent::equals(const TipContent &tipContent) const
-{
- if (typeId() == tipContent.typeId()) {
- if (m_text == static_cast<const TextContent &>(tipContent).m_text)
- return true;
- }
- return false;
-}
-
-const QString &TextContent::text() const
-{
- return m_text;
-}
-
-WidgetContent::WidgetContent(QWidget *w, bool interactive) :
- m_widget(w), m_interactive(interactive)
-{
-}
-
-TipContent *WidgetContent::clone() const
-{
- return new WidgetContent(m_widget, m_interactive);
-}
-
-int WidgetContent::typeId() const
-{
- return WIDGET_CONTENT_ID;
-}
-
-bool WidgetContent::isValid() const
-{
- return m_widget;
-}
-
-bool WidgetContent::isInteractive() const
-{
- return m_interactive;
-}
-
-void WidgetContent::setInteractive(bool i)
-{
- m_interactive = i;
-}
-
-int WidgetContent::showTime() const
-{
- return 30000;
-}
-
-bool WidgetContent::equals(const TipContent &tipContent) const
-{
- if (typeId() == tipContent.typeId()) {
- if (m_widget == static_cast<const WidgetContent &>(tipContent).m_widget)
- return true;
- }
- return false;
-}
-
-bool WidgetContent::pinToolTip(QWidget *w, QWidget *parent)
-{
- QTC_ASSERT(w, return false);
- // Find the parent WidgetTip, tell it to pin/release the
- // widget and close.
- for (QWidget *p = w->parentWidget(); p ; p = p->parentWidget()) {
- if (Internal::WidgetTip *wt = qobject_cast<Internal::WidgetTip *>(p)) {
- wt->pinToolTipWidget(parent);
- ToolTip::hide();
- return true;
- }
- }
- return false;
-}
-
-} // namespace Utils
diff --git a/src/libs/utils/tooltip/tipcontents.h b/src/libs/utils/tooltip/tipcontents.h
deleted file mode 100644
index 7d2c91c1b0c..00000000000
--- a/src/libs/utils/tooltip/tipcontents.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef TIPCONTENTS_H
-#define TIPCONTENTS_H
-
-#include "../utils_global.h"
-
-#include <QString>
-#include <QColor>
-#include <QWidget>
-
-namespace Utils {
-
-class QTCREATOR_UTILS_EXPORT TipContent
-{
-protected:
- TipContent();
-
-public:
- virtual ~TipContent();
-
- virtual TipContent *clone() const = 0;
- virtual int typeId() const = 0;
- virtual bool isValid() const = 0;
- virtual bool isInteractive() const = 0;
- virtual int showTime() const = 0;
- virtual bool equals(const TipContent &tipContent) const = 0;
-};
-
-class QTCREATOR_UTILS_EXPORT ColorContent : public TipContent
-{
-public:
- ColorContent(const QColor &color);
- virtual ~ColorContent();
-
- virtual TipContent *clone() const;
- virtual int typeId() const;
- virtual bool isValid() const;
- virtual bool isInteractive() const;
- virtual int showTime() const;
- virtual bool equals(const TipContent &tipContent) const;
-
- const QColor &color() const;
-
- static const int COLOR_CONTENT_ID = 0;
-
-private:
- QColor m_color;
-};
-
-class QTCREATOR_UTILS_EXPORT TextContent : public TipContent
-{
-public:
- TextContent(const QString &text);
- virtual ~TextContent();
-
- virtual TipContent *clone() const;
- virtual int typeId() const;
- virtual bool isValid() const;
- virtual bool isInteractive() const;
- virtual int showTime() const;
- virtual bool equals(const TipContent &tipContent) const;
-
- const QString &text() const;
-
- static const int TEXT_CONTENT_ID = 1;
-
-private:
- QString m_text;
-};
-
-// A content for displaying any widget (with a layout).
-class QTCREATOR_UTILS_EXPORT WidgetContent : public TipContent
-{
-public:
- explicit WidgetContent(QWidget *w, bool interactive = false);
-
- virtual TipContent *clone() const;
- virtual int typeId() const;
- virtual bool isValid() const;
- virtual int showTime() const;
- virtual bool isInteractive() const;
- void setInteractive(bool i);
-
- virtual bool equals(const TipContent &tipContent) const;
-
- // Helper to 'pin' (show as real window) a tooltip shown
- // using WidgetContent
- static bool pinToolTip(QWidget *w, QWidget *parent);
-
- static const int WIDGET_CONTENT_ID = 42;
-
- QWidget *widget() const { return m_widget; }
-
-private:
- QWidget *m_widget;
- bool m_interactive;
-};
-
-} // namespace Utils
-
-#endif // TIPCONTENTS_H
diff --git a/src/libs/utils/tooltip/tips.cpp b/src/libs/utils/tooltip/tips.cpp
index 159eeb9abf8..9fd0121a682 100644
--- a/src/libs/utils/tooltip/tips.cpp
+++ b/src/libs/utils/tooltip/tips.cpp
@@ -29,7 +29,7 @@
****************************************************************************/
#include "tips.h"
-#include "tipcontents.h"
+#include "tooltip.h"
#include "reuse.h"
#include <utils/qtcassert.h>
@@ -49,59 +49,32 @@
#include <QVBoxLayout>
namespace Utils {
- namespace Internal {
-
-namespace {
- // @todo: Reuse...
- QPixmap tilePixMap(int size)
- {
- const int checkerbordSize= size;
- QPixmap tilePixmap(checkerbordSize * 2, checkerbordSize * 2);
- tilePixmap.fill(Qt::white);
- QPainter tilePainter(&tilePixmap);
- QColor color(220, 220, 220);
- tilePainter.fillRect(0, 0, checkerbordSize, checkerbordSize, color);
- tilePainter.fillRect(checkerbordSize, checkerbordSize, checkerbordSize, checkerbordSize, color);
- return tilePixmap;
- }
-}
+namespace Internal {
QTipLabel::QTipLabel(QWidget *parent) :
- QLabel(parent, Qt::ToolTip | Qt::BypassGraphicsProxyWidget),
- m_tipContent(0)
+ QLabel(parent, Qt::ToolTip | Qt::BypassGraphicsProxyWidget)
{}
-QTipLabel::~QTipLabel()
-{
- TipContent *tmpTipContent = m_tipContent;
- m_tipContent = 0;
- delete tmpTipContent;
-}
-
-bool QTipLabel::isInteractive() const
-{
- return m_tipContent && m_tipContent->isInteractive();
-}
-void QTipLabel::setContent(const TipContent &content)
+ColorTip::ColorTip(QWidget *parent)
+ : QTipLabel(parent)
{
- TipContent *tmpTipContent = m_tipContent;
- m_tipContent = content.clone();
- delete tmpTipContent;
+ resize(40, 40);
}
-const TipContent &QTipLabel::content() const
-{ return *m_tipContent; }
-
-ColorTip::ColorTip(QWidget *parent) : QTipLabel(parent)
+void ColorTip::setContent(const QVariant &content)
{
- resize(QSize(40, 40));
- m_tilePixMap = tilePixMap(10);
+ m_color = content.value<QColor>();
+
+ const int size = 10;
+ m_tilePixmap = QPixmap(size * 2, size * 2);
+ m_tilePixmap.fill(Qt::white);
+ QPainter tilePainter(&m_tilePixmap);
+ QColor col(220, 220, 220);
+ tilePainter.fillRect(0, 0, size, size, col);
+ tilePainter.fillRect(size, size, size, size, col);
}
-ColorTip::~ColorTip()
-{}
-
void ColorTip::configure(const QPoint &pos, QWidget *w)
{
Q_UNUSED(pos)
@@ -110,31 +83,32 @@ void ColorTip::configure(const QPoint &pos, QWidget *w)
update();
}
-bool ColorTip::canHandleContentReplacement(const TipContent &content) const
+bool ColorTip::canHandleContentReplacement(int typeId) const
{
- if (content.typeId() == ColorContent::COLOR_CONTENT_ID)
- return true;
- return false;
+ return typeId == ToolTip::ColorContent;
+}
+
+bool ColorTip::equals(int typeId, const QVariant &other) const
+{
+ return typeId == ToolTip::ColorContent && other == m_color;
}
void ColorTip::paintEvent(QPaintEvent *event)
{
QTipLabel::paintEvent(event);
- const QColor &color = static_cast<const ColorContent &>(content()).color();
-
QPen pen;
pen.setWidth(1);
- if (color.value() > 100)
- pen.setColor(color.darker());
+ if (m_color.value() > 100)
+ pen.setColor(m_color.darker());
else
- pen.setColor(color.lighter());
+ pen.setColor(m_color.lighter());
QPainter painter(this);
painter.setPen(pen);
- painter.setBrush(color);
+ painter.setBrush(m_color);
QRect r(0, 0, rect().width() - 1, rect().height() - 1);
- painter.drawTiledPixmap(r, m_tilePixMap);
+ painter.drawTiledPixmap(r, m_tilePixmap);
painter.drawRect(r);
}
@@ -150,13 +124,14 @@ TextTip::TextTip(QWidget *parent) : QTipLabel(parent)
setWindowOpacity(style()->styleHint(QStyle::SH_ToolTipLabel_Opacity, 0, this) / 255.0);
}
-TextTip::~TextTip()
-{}
+void TextTip::setContent(const QVariant &content)
+{
+ m_text = content.toString();
+}
void TextTip::configure(const QPoint &pos, QWidget *w)
{
- const QString &text = static_cast<const TextContent &>(content()).text();
- setText(text);
+ setText(m_text);
// Make it look good with the default ToolTip font on Mac, which has a small descent.
QFontMetrics fm(font());
@@ -181,11 +156,19 @@ void TextTip::configure(const QPoint &pos, QWidget *w)
resize(tipWidth, heightForWidth(tipWidth) + extraHeight);
}
-bool TextTip::canHandleContentReplacement(const TipContent &content) const
+bool TextTip::canHandleContentReplacement(int typeId) const
{
- if (content.typeId() == TextContent::TEXT_CONTENT_ID)
- return true;
- return false;
+ return typeId == ToolTip::TextContent;
+}
+
+int TextTip::showTime() const
+{
+ return 10000 + 40 * qMax(0, m_text.size() - 100);
+}
+
+bool TextTip::equals(int typeId, const QVariant &other) const
+{
+ return typeId == ToolTip::TextContent && other.toString() == m_text;
}
void TextTip::paintEvent(QPaintEvent *event)
@@ -217,15 +200,17 @@ WidgetTip::WidgetTip(QWidget *parent) :
setLayout(m_layout);
}
-void WidgetTip::configure(const QPoint &pos, QWidget *)
+void WidgetTip::setContent(const QVariant &content)
{
- const WidgetContent &anyContent = static_cast<const WidgetContent &>(content());
- QWidget *widget = anyContent.widget();
+ m_widget = content.value<QWidget *>();
+}
- QTC_ASSERT(widget && m_layout->count() == 0, return);
+void WidgetTip::configure(const QPoint &pos, QWidget *)
+{
+ QTC_ASSERT(m_widget && m_layout->count() == 0, return);
move(pos);
- m_layout->addWidget(widget);
+ m_layout->addWidget(m_widget);
m_layout->setSizeConstraint(QLayout::SetFixedSize);
adjustSize();
}
@@ -253,12 +238,18 @@ void WidgetTip::pinToolTipWidget(QWidget *parent)
widget->setAttribute(Qt::WA_DeleteOnClose);
}
-bool WidgetTip::canHandleContentReplacement(const TipContent & ) const
+bool WidgetTip::canHandleContentReplacement(int typeId) const
{
// Always create a new widget.
+ Q_UNUSED(typeId);
return false;
}
+bool WidgetTip::equals(int typeId, const QVariant &other) const
+{
+ return typeId == ToolTip::WidgetContent && other.value<QWidget *>() == m_widget;
+}
+
// need to include it here to force it to be inside the namespaces
#include "moc_tips.cpp"
diff --git a/src/libs/utils/tooltip/tips.h b/src/libs/utils/tooltip/tips.h
index 0b43a469096..86a9633e5da 100644
--- a/src/libs/utils/tooltip/tips.h
+++ b/src/libs/utils/tooltip/tips.h
@@ -31,13 +31,13 @@
#ifndef TIPS_H
#define TIPS_H
-#include <QSharedPointer>
+#include "../utils_global.h"
+
#include <QLabel>
#include <QPixmap>
-
-QT_FORWARD_DECLARE_CLASS(QVBoxLayout)
-
-namespace Utils { class TipContent; }
+#include <QSharedPointer>
+#include <QVariant>
+#include <QVBoxLayout>
#ifndef Q_MOC_RUN
namespace Utils {
@@ -48,68 +48,68 @@ namespace Internal {
class QTipLabel : public QLabel
{
Q_OBJECT
-protected:
- QTipLabel(QWidget *parent);
-
public:
- virtual ~QTipLabel();
-
- void setContent(const TipContent &content);
- const TipContent &content() const;
+ QTipLabel(QWidget *parent);
+ virtual void setContent(const QVariant &content) = 0;
+ virtual bool isInteractive() const { return false; }
+ virtual int showTime() const = 0;
virtual void configure(const QPoint &pos, QWidget *w) = 0;
- virtual bool canHandleContentReplacement(const TipContent &content) const = 0;
-
- bool isInteractive() const;
-
-private:
- TipContent *m_tipContent;
+ virtual bool canHandleContentReplacement(int typeId) const = 0;
+ virtual bool equals(int typeId, const QVariant &other) const = 0;
};
-class ColorTip : public QTipLabel
+class TextTip : public QTipLabel
{
- Q_OBJECT
public:
- ColorTip(QWidget *parent);
- virtual ~ColorTip();
+ TextTip(QWidget *parent);
+ virtual void setContent(const QVariant &content);
virtual void configure(const QPoint &pos, QWidget *w);
- virtual bool canHandleContentReplacement(const TipContent &content) const;
-
-private:
+ virtual bool canHandleContentReplacement(int typeId) const;
+ virtual int showTime() const;
+ virtual bool equals(int typeId, const QVariant &other) const;
virtual void paintEvent(QPaintEvent *event);
+ virtual void resizeEvent(QResizeEvent *event);
- QPixmap m_tilePixMap;
+private:
+ QString m_text;
};
-class TextTip : public QTipLabel
+class ColorTip : public QTipLabel
{
- Q_OBJECT
public:
- TextTip(QWidget *parent);
- virtual ~TextTip();
+ ColorTip(QWidget *parent);
+ virtual void setContent(const QVariant &content);
virtual void configure(const QPoint &pos, QWidget *w);
- virtual bool canHandleContentReplacement(const TipContent &content) const;
+ virtual bool canHandleContentReplacement(int typeId) const;
+ virtual int showTime() const { return 4000; }
+ virtual bool equals(int typeId, const QVariant &other) const;
+ virtual void paintEvent(QPaintEvent *event);
private:
- virtual void paintEvent(QPaintEvent *event);
- virtual void resizeEvent(QResizeEvent *event);
+ QColor m_color;
+ QPixmap m_tilePixmap;
};
class WidgetTip : public QTipLabel
{
Q_OBJECT
+
public:
explicit WidgetTip(QWidget *parent = 0);
+ void pinToolTipWidget(QWidget *parent);
+ virtual void setContent(const QVariant &content);
virtual void configure(const QPoint &pos, QWidget *w);
- virtual bool canHandleContentReplacement(const TipContent &content) const;
-
-public slots:
- void pinToolTipWidget(QWidget *parent);
+ virtual bool canHandleContentReplacement(int typeId) const;
+ virtual int showTime() const { return 30000; }
+ virtual bool equals(int typeId, const QVariant &other) const;
+ virtual bool isInteractive() const { return true; }
private:
+ QWidget *m_widget;
QVBoxLayout *m_layout;
};
diff --git a/src/libs/utils/tooltip/tooltip.cpp b/src/libs/utils/tooltip/tooltip.cpp
index 5859dd1f2de..08e05ea4a1d 100644
--- a/src/libs/utils/tooltip/tooltip.cpp
+++ b/src/libs/utils/tooltip/tooltip.cpp
@@ -30,11 +30,11 @@
#include "tooltip.h"
#include "tips.h"
-#include "tipcontents.h"
#include "effects.h"
#include "reuse.h"
#include <utils/hostosinfo.h>
+#include <utils/qtcassert.h>
#include <QString>
#include <QColor>
@@ -51,8 +51,8 @@ using namespace Internal;
ToolTip::ToolTip() : m_tip(0), m_widget(0)
{
- connect(&m_showTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
- connect(&m_hideDelayTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
+ connect(&m_showTimer, &QTimer::timeout, this, &ToolTip::hideTipImmediately);
+ connect(&m_hideDelayTimer, &QTimer::timeout, this, &ToolTip::hideTipImmediately);
}
ToolTip::~ToolTip()
@@ -66,9 +66,28 @@ ToolTip *ToolTip::instance()
return &tooltip;
}
-void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
+void ToolTip::show(const QPoint &pos, const QString &content, QWidget *w, const QRect &rect)
{
- instance()->showInternal(pos, content, w, rect);
+ if (content.isEmpty())
+ instance()->hideTipWithDelay();
+ else
+ instance()->showInternal(pos, QVariant(content), TextContent, w, rect);
+}
+
+void ToolTip::show(const QPoint &pos, const QColor &color, QWidget *w, const QRect &rect)
+{
+ if (!color.isValid())
+ instance()->hideTipWithDelay();
+ else
+ instance()->showInternal(pos, QVariant(color), ColorContent, w, rect);
+}
+
+void ToolTip::show(const QPoint &pos, QWidget *content, QWidget *w, const QRect &rect)
+{
+ if (!content)
+ instance()->hideTipWithDelay();
+ else
+ instance()->showInternal(pos, QVariant::fromValue(content), WidgetContent, w, rect);
}
void ToolTip::move(const QPoint &pos, QWidget *w)
@@ -77,27 +96,37 @@ void ToolTip::move(const QPoint &pos, QWidget *w)
instance()->placeTip(pos, w);
}
-void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w)
+bool ToolTip::pinToolTip(QWidget *w, QWidget *parent)
{
- show(pos, content, w, QRect());
+ QTC_ASSERT(w, return false);
+ // Find the parent WidgetTip, tell it to pin/release the
+ // widget and close.
+ for (QWidget *p = w->parentWidget(); p ; p = p->parentWidget()) {
+ if (WidgetTip *wt = qobject_cast<WidgetTip *>(p)) {
+ wt->pinToolTipWidget(parent);
+ ToolTip::hide();
+ return true;
+ }
+ }
+ return false;
}
-bool ToolTip::acceptShow(const TipContent &content,
+bool ToolTip::acceptShow(const QVariant &content,
+ int typeId,
const QPoint &pos,
QWidget *w,
const QRect &rect)
{
- if (!validateContent(content))
- return false;
-
if (isVisible()) {
- if (m_tip->canHandleContentReplacement(content)) {
+ if (m_tip->canHandleContentReplacement(typeId)) {
// Reuse current tip.
QPoint localPos = pos;
if (w)
localPos = w->mapFromGlobal(pos);
- if (tipChanged(localPos, content, w))
- setUp(pos, content, w, rect);
+ if (tipChanged(localPos, content, typeId, w)) {
+ m_tip->setContent(content);
+ setUp(pos, w, rect);
+ }
return false;
}
hideTipImmediately();
@@ -114,19 +143,8 @@ bool ToolTip::acceptShow(const TipContent &content,
return true;
}
-bool ToolTip::validateContent(const TipContent &content)
+void ToolTip::setUp(const QPoint &pos, QWidget *w, const QRect &rect)
{
- if (!content.isValid()) {
- if (isVisible())
- hideTipWithDelay();
- return false;
- }
- return true;
-}
-
-void ToolTip::setUp(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
-{
- m_tip->setContent(content);
m_tip->configure(pos, w);
placeTip(pos, w);
@@ -134,12 +152,12 @@ void ToolTip::setUp(const QPoint &pos, const TipContent &content, QWidget *w, co
if (m_hideDelayTimer.isActive())
m_hideDelayTimer.stop();
- m_showTimer.start(content.showTime());
+ m_showTimer.start(m_tip->showTime());
}
-bool ToolTip::tipChanged(const QPoint &pos, const TipContent &content, QWidget *w) const
+bool ToolTip::tipChanged(const QPoint &pos, const QVariant &content, int typeId, QWidget *w) const
{
- if (!m_tip->content().equals(content) || m_widget != w)
+ if (!m_tip->equals(typeId, content) || m_widget != w)
return true;
if (!m_rect.isNull())
return !m_rect.contains(pos);
@@ -199,27 +217,29 @@ void ToolTip::hideTipImmediately()
qApp->removeEventFilter(this);
}
-void ToolTip::showInternal(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
+void ToolTip::showInternal(const QPoint &pos, const QVariant &content,
+ int typeId, QWidget *w, const QRect &rect)
{
- if (acceptShow(content, pos, w, rect)) {
+ if (acceptShow(content, typeId, pos, w, rect)) {
QWidget *target = 0;
if (HostOsInfo::isWindowsHost())
target = QApplication::desktop()->screen(Internal::screenNumber(pos, w));
else
target = w;
- switch (content.typeId()) {
- case TextContent::TEXT_CONTENT_ID:
- m_tip = new TextTip(target);
- break;
- case ColorContent::COLOR_CONTENT_ID:
+ switch (typeId) {
+ case ColorContent:
m_tip = new ColorTip(target);
break;
- case WidgetContent::WIDGET_CONTENT_ID:
+ case TextContent:
+ m_tip = new TextTip(target);
+ break;
+ case WidgetContent:
m_tip = new WidgetTip(target);
break;
}
- setUp(pos, content, w, rect);
+ m_tip->setContent(content);
+ setUp(pos, w, rect);
qApp->installEventFilter(this);
showTip();
}
diff --git a/src/libs/utils/tooltip/tooltip.h b/src/libs/utils/tooltip/tooltip.h
index dd3e17cb656..b95d3a32060 100644
--- a/src/libs/utils/tooltip/tooltip.h
+++ b/src/libs/utils/tooltip/tooltip.h
@@ -50,14 +50,13 @@
QT_BEGIN_NAMESPACE
class QPoint;
+class QVariant;
class QWidget;
QT_END_NAMESPACE
namespace Utils {
namespace Internal { class QTipLabel; }
-class TipContent;
-
class QTCREATOR_UTILS_EXPORT ToolTip : public QObject
{
Q_OBJECT
@@ -67,27 +66,33 @@ protected:
public:
~ToolTip();
+ enum {
+ ColorContent = 0,
+ TextContent = 1,
+ WidgetContent = 42
+ };
+
bool eventFilter(QObject *o, QEvent *event);
static ToolTip *instance();
- 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 show(const QPoint &pos, const QString &content, QWidget *w = 0, const QRect &rect = QRect());
+ static void show(const QPoint &pos, const QColor &color, QWidget *w = 0, const QRect &rect = QRect());
+ static void show(const QPoint &pos, QWidget *content, QWidget *w = 0, const QRect &rect = QRect());
static void move(const QPoint &pos, QWidget *w);
static void hide();
static bool isVisible();
-protected slots:
- void hideTipImmediately();
-
-protected:
- void showInternal(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect);
+ // Helper to 'pin' (show as real window) a tooltip shown
+ // using WidgetContent
+ static bool pinToolTip(QWidget *w, QWidget *parent);
private:
- 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);
- bool tipChanged(const QPoint &pos, const TipContent &content, QWidget *w) const;
+ void showInternal(const QPoint &pos, const QVariant &content, int typeId, QWidget *w, const QRect &rect);
+ void hideTipImmediately();
+ bool acceptShow(const QVariant &content, int typeId, const QPoint &pos, QWidget *w, const QRect &rect);
+ void setUp(const QPoint &pos, QWidget *w, const QRect &rect);
+ bool tipChanged(const QPoint &pos, const QVariant &content, int typeId, QWidget *w) const;
void setTipRect(QWidget *w, const QRect &rect);
void placeTip(const QPoint &pos, QWidget *w);
void showTip();
diff --git a/src/libs/utils/treemodel.cpp b/src/libs/utils/treemodel.cpp
index 2b93d233e41..c582000bcb0 100644
--- a/src/libs/utils/treemodel.cpp
+++ b/src/libs/utils/treemodel.cpp
@@ -31,12 +31,579 @@
#include "treemodel.h"
#include "qtcassert.h"
+#include <QStack>
+#include <QSize>
+
+#define USE_MODEL_TEST 0
+#define USE_INDEX_CHECKS 0
+
+#if USE_INDEX_CHECKS
+#define CHECK_INDEX(index) \
+ do { \
+ if (index.isValid()) { \
+ QTC_CHECK(index.model() == this); \
+ } else { \
+ QTC_CHECK(index.model() == 0); \
+ } \
+ } while (false)
+#else
+#define CHECK_INDEX(index)
+#endif
+
+#if USE_MODEL_TEST
+
+namespace {
+
+class ModelTest : public QObject
+{
+public:
+ ModelTest(QAbstractItemModel *model, QObject *parent = 0);
+
+private:
+ void nonDestructiveBasicTest();
+ void rowCount();
+ void columnCount();
+ void hasIndex();
+ void index();
+ void parent();
+ void data();
+
+protected:
+ void runAllTests();
+ void layoutAboutToBeChanged();
+ void layoutChanged();
+ void rowsAboutToBeInserted(const QModelIndex &parent, int start, int end);
+ void rowsInserted(const QModelIndex & parent, int start, int end);
+ void rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end);
+ void rowsRemoved(const QModelIndex & parent, int start, int end);
+
+private:
+ void checkChildren(const QModelIndex &parent, int currentDepth = 0);
+
+ QAbstractItemModel *model;
+
+ struct Changing
+ {
+ QModelIndex parent;
+ int oldSize;
+ QVariant last;
+ QVariant next;
+ };
+ QStack<Changing> insert;
+ QStack<Changing> remove;
+
+ bool fetchingMore;
+
+ QList<QPersistentModelIndex> changing;
+};
+
/*!
- \class Utils::TreeModel
+ Connect to all of the models signals. Whenever anything happens
+ recheck everything.
+*/
+ModelTest::ModelTest(QAbstractItemModel *_model, QObject *parent) : QObject(parent), model(_model), fetchingMore(false)
+{
+ Q_ASSERT(model);
- \brief The TreeModel class is a convienience base class for models
- to use in a QTreeView.
+ connect(model, &QAbstractItemModel::columnsAboutToBeInserted,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::columnsAboutToBeRemoved,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::columnsInserted,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::columnsRemoved,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::dataChanged,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::headerDataChanged,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::layoutAboutToBeChanged, this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::layoutChanged, this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::modelReset, this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::rowsAboutToBeInserted,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::rowsInserted,
+ this, &ModelTest::runAllTests);
+ connect(model, &QAbstractItemModel::rowsRemoved,
+ this, &ModelTest::runAllTests);
+
+ // Special checks for inserting/removing
+ connect(model, &QAbstractItemModel::layoutAboutToBeChanged,
+ this, &ModelTest::layoutAboutToBeChanged);
+ connect(model, &QAbstractItemModel::layoutChanged,
+ this, &ModelTest::layoutChanged);
+
+ connect(model, &QAbstractItemModel::rowsAboutToBeInserted,
+ this, &ModelTest::rowsAboutToBeInserted);
+ connect(model, &QAbstractItemModel::rowsAboutToBeRemoved,
+ this, &ModelTest::rowsAboutToBeRemoved);
+ connect(model, &QAbstractItemModel::rowsInserted,
+ this, &ModelTest::rowsInserted);
+ connect(model, &QAbstractItemModel::rowsRemoved,
+ this, &ModelTest::rowsRemoved);
+
+ runAllTests();
+}
+
+void ModelTest::runAllTests()
+{
+ if (fetchingMore)
+ return;
+ nonDestructiveBasicTest();
+ rowCount();
+ columnCount();
+ hasIndex();
+ index();
+ parent();
+ data();
+}
+
+/*!
+ nonDestructiveBasicTest tries to call a number of the basic functions (not all)
+ to make sure the model doesn't outright segfault, testing the functions that makes sense.
*/
+void ModelTest::nonDestructiveBasicTest()
+{
+ Q_ASSERT(model->buddy(QModelIndex()) == QModelIndex());
+ model->canFetchMore(QModelIndex());
+ Q_ASSERT(model->columnCount(QModelIndex()) >= 0);
+ Q_ASSERT(model->data(QModelIndex()) == QVariant());
+ fetchingMore = true;
+ model->fetchMore(QModelIndex());
+ fetchingMore = false;
+ Qt::ItemFlags flags = model->flags(QModelIndex());
+ Q_ASSERT(flags == Qt::ItemIsDropEnabled || flags == 0);
+ model->hasChildren(QModelIndex());
+ model->hasIndex(0, 0);
+ model->headerData(0, Qt::Horizontal);
+ model->index(0, 0);
+ model->itemData(QModelIndex());
+ QVariant cache;
+ model->match(QModelIndex(), -1, cache);
+ model->mimeTypes();
+ QModelIndex m1 = model->parent(QModelIndex());
+ QModelIndex m2 = QModelIndex();
+ Q_ASSERT(m1 == m2);
+ Q_ASSERT(model->parent(QModelIndex()) == QModelIndex());
+ Q_ASSERT(model->rowCount() >= 0);
+ QVariant variant;
+ model->setData(QModelIndex(), variant, -1);
+ model->setHeaderData(-1, Qt::Horizontal, QVariant());
+ model->setHeaderData(999999, Qt::Horizontal, QVariant());
+ QMap<int, QVariant> roles;
+ model->sibling(0, 0, QModelIndex());
+ model->span(QModelIndex());
+ model->supportedDropActions();
+}
+
+/*!
+ Tests model's implementation of QAbstractItemModel::rowCount() and hasChildren()
+
+ Models that are dynamically populated are not as fully tested here.
+ */
+void ModelTest::rowCount()
+{
+ // check top row
+ QModelIndex topIndex = model->index(0, 0, QModelIndex());
+ int rows = model->rowCount(topIndex);
+ Q_ASSERT(rows >= 0);
+ if (rows > 0)
+ Q_ASSERT(model->hasChildren(topIndex) == true);
+
+ QModelIndex secondLevelIndex = model->index(0, 0, topIndex);
+ if (secondLevelIndex.isValid()) { // not the top level
+ // check a row count where parent is valid
+ rows = model->rowCount(secondLevelIndex);
+ Q_ASSERT(rows >= 0);
+ if (rows > 0)
+ Q_ASSERT(model->hasChildren(secondLevelIndex) == true);
+ }
+
+ // The models rowCount() is tested more extensively in checkChildren(),
+ // but this catches the big mistakes
+}
+
+/*!
+ Tests model's implementation of QAbstractItemModel::columnCount() and hasChildren()
+ */
+void ModelTest::columnCount()
+{
+ // check top row
+ QModelIndex topIndex = model->index(0, 0, QModelIndex());
+ Q_ASSERT(model->columnCount(topIndex) >= 0);
+
+ // check a column count where parent is valid
+ QModelIndex childIndex = model->index(0, 0, topIndex);
+ if (childIndex.isValid())
+ Q_ASSERT(model->columnCount(childIndex) >= 0);
+
+ // columnCount() is tested more extensively in checkChildren(),
+ // but this catches the big mistakes
+}
+
+/*!
+ Tests model's implementation of QAbstractItemModel::hasIndex()
+ */
+void ModelTest::hasIndex()
+{
+ // Make sure that invalid values returns an invalid index
+ Q_ASSERT(model->hasIndex(-2, -2) == false);
+ Q_ASSERT(model->hasIndex(-2, 0) == false);
+ Q_ASSERT(model->hasIndex(0, -2) == false);
+
+ int rows = model->rowCount();
+ int columns = model->columnCount();
+
+ // check out of bounds
+ Q_ASSERT(model->hasIndex(rows, columns) == false);
+ Q_ASSERT(model->hasIndex(rows + 1, columns + 1) == false);
+
+ if (rows > 0)
+ Q_ASSERT(model->hasIndex(0, 0) == true);
+
+ // hasIndex() is tested more extensively in checkChildren(),
+ // but this catches the big mistakes
+}
+
+/*!
+ Tests model's implementation of QAbstractItemModel::index()
+ */
+void ModelTest::index()
+{
+ // Make sure that invalid values returns an invalid index
+ Q_ASSERT(model->index(-2, -2) == QModelIndex());
+ Q_ASSERT(model->index(-2, 0) == QModelIndex());
+ Q_ASSERT(model->index(0, -2) == QModelIndex());
+
+ int rows = model->rowCount();
+ int columns = model->columnCount();
+
+ if (rows == 0)
+ return;
+
+ // Catch off by one errors
+ QModelIndex tmp;
+ tmp = model->index(rows, columns);
+ Q_ASSERT(tmp == QModelIndex());
+ tmp = model->index(0, 0);
+ Q_ASSERT(tmp.isValid() == true);
+
+ // Make sure that the same index is *always* returned
+ QModelIndex a = model->index(0, 0);
+ QModelIndex b = model->index(0, 0);
+ Q_ASSERT(a == b);
+
+ // index() is tested more extensively in checkChildren(),
+ // but this catches the big mistakes
+}
+
+/*!
+ Tests model's implementation of QAbstractItemModel::parent()
+ */
+void ModelTest::parent()
+{
+ // Make sure the model wont crash and will return an invalid QModelIndex
+ // when asked for the parent of an invalid index.
+ Q_ASSERT(model->parent(QModelIndex()) == QModelIndex());
+
+ if (model->rowCount() == 0)
+ return;
+
+ QModelIndex tmp;
+
+ // Column 0 | Column 1 |
+ // QModelIndex() | |
+ // \- topIndex | topIndex1 |
+ // \- childIndex | childIndex1 |
+
+ // Common error test #1, make sure that a top level index has a parent
+ // that is a invalid QModelIndex.
+ QModelIndex topIndex = model->index(0, 0, QModelIndex());
+ tmp = model->parent(topIndex);
+ Q_ASSERT(tmp == QModelIndex());
+
+ // Common error test #2, make sure that a second level index has a parent
+ // that is the first level index.
+ if (model->rowCount(topIndex) > 0) {
+ QModelIndex childIndex = model->index(0, 0, topIndex);
+ tmp = model->parent(childIndex);
+ Q_ASSERT(tmp == topIndex);
+ }
+
+ // Common error test #3, the second column should NOT have the same children
+ // as the first column in a row.
+ // Usually the second column shouldn't have children.
+ QModelIndex topIndex1 = model->index(0, 1, QModelIndex());
+ if (model->rowCount(topIndex1) > 0) {
+ QModelIndex childIndex = model->index(0, 0, topIndex);
+ QModelIndex childIndex1 = model->index(0, 0, topIndex1);
+ Q_ASSERT(childIndex != childIndex1);
+ }
+
+ // Full test, walk n levels deep through the model making sure that all
+ // parent's children correctly specify their parent.
+ checkChildren(QModelIndex());
+}
+
+/*!
+ Called from the parent() test.
+
+ A model that returns an index of parent X should also return X when asking
+ for the parent of the index.
+
+ This recursive function does pretty extensive testing on the whole model in an
+ effort to catch edge cases.
+
+ This function assumes that rowCount(), columnCount() and index() already work.
+ If they have a bug it will point it out, but the above tests should have already
+ found the basic bugs because it is easier to figure out the problem in
+ those tests then this one.
+ */
+void ModelTest::checkChildren(const QModelIndex &parent, int currentDepth)
+{
+ QModelIndex tmp;
+
+ // First just try walking back up the tree.
+ QModelIndex p = parent;
+ while (p.isValid())
+ p = p.parent();
+
+ // For models that are dynamically populated
+ if (model->canFetchMore(parent)) {
+ fetchingMore = true;
+ model->fetchMore(parent);
+ fetchingMore = false;
+ }
+
+ int rows = model->rowCount(parent);
+ int columns = model->columnCount(parent);
+
+ if (rows > 0)
+ Q_ASSERT(model->hasChildren(parent));
+
+ // Some further testing against rows(), columns(), and hasChildren()
+ Q_ASSERT(rows >= 0);
+ Q_ASSERT(columns >= 0);
+ if (rows > 0)
+ Q_ASSERT(model->hasChildren(parent) == true);
+
+ //qDebug() << "parent:" << model->data(parent).toString() << "rows:" << rows
+ // << "columns:" << columns << "parent column:" << parent.column();
+
+ Q_ASSERT(model->hasIndex(rows + 1, 0, parent) == false);
+ for (int r = 0; r < rows; ++r) {
+ if (model->canFetchMore(parent)) {
+ fetchingMore = true;
+ model->fetchMore(parent);
+ fetchingMore = false;
+ }
+ Q_ASSERT(model->hasIndex(r, columns + 1, parent) == false);
+ for (int c = 0; c < columns; ++c) {
+ Q_ASSERT(model->hasIndex(r, c, parent) == true);
+ QModelIndex index = model->index(r, c, parent);
+ // rowCount() and columnCount() said that it existed...
+ Q_ASSERT(index.isValid() == true);
+
+ // index() should always return the same index when called twice in a row
+ QModelIndex modifiedIndex = model->index(r, c, parent);
+ Q_ASSERT(index == modifiedIndex);
+
+ // Make sure we get the same index if we request it twice in a row
+ QModelIndex a = model->index(r, c, parent);
+ QModelIndex b = model->index(r, c, parent);
+ Q_ASSERT(a == b);
+
+ // Some basic checking on the index that is returned
+ Q_ASSERT(index.model() == model);
+ Q_ASSERT(index.row() == r);
+ Q_ASSERT(index.column() == c);
+ // While you can technically return a QVariant usually this is a sign
+ // of an bug in data() Disable if this really is ok in your model.
+ //Q_ASSERT(model->data(index, Qt::DisplayRole).isValid() == true);
+
+ // If the next test fails here is some somewhat useful debug you play with.
+ /*
+ if (model->parent(index) != parent) {
+ qDebug() << r << c << currentDepth << model->data(index).toString()
+ << model->data(parent).toString();
+ qDebug() << index << parent << model->parent(index);
+ // And a view that you can even use to show the model.
+ //QTreeView view;
+ //view.setModel(model);
+ //view.show();
+ }*/
+
+ // Check that we can get back our real parent.
+ //qDebug() << "TTT 1: " << model->parent(index);
+ //qDebug() << "TTT 2: " << parent;
+ //qDebug() << "TTT 3: " << index;
+ tmp = model->parent(index);
+ Q_ASSERT(tmp == parent);
+
+ // recursively go down the children
+ if (model->hasChildren(index) && currentDepth < 10 ) {
+ //qDebug() << r << c << "has children" << model->rowCount(index);
+ checkChildren(index, ++currentDepth);
+ }/* else { if (currentDepth >= 10) qDebug() << "checked 10 deep"; };*/
+
+ // make sure that after testing the children that the index doesn't change.
+ QModelIndex newerIndex = model->index(r, c, parent);
+ Q_ASSERT(index == newerIndex);
+ }
+ }
+}
+
+/*!
+ Tests model's implementation of QAbstractItemModel::data()
+ */
+void ModelTest::data()
+{
+ // Invalid index should return an invalid qvariant
+ Q_ASSERT(!model->data(QModelIndex()).isValid());
+
+ if (model->rowCount() == 0)
+ return;
+
+ // A valid index should have a valid QVariant data
+ Q_ASSERT(model->index(0, 0).isValid());
+
+ // shouldn't be able to set data on an invalid index
+ Q_ASSERT(model->setData(QModelIndex(), QLatin1String("foo"), Qt::DisplayRole) == false);
+
+ // General Purpose roles that should return a QString
+ QVariant variant = model->data(model->index(0, 0), Qt::ToolTipRole);
+ if (variant.isValid())
+ Q_ASSERT(variant.canConvert(QVariant::String));
+ variant = model->data(model->index(0, 0), Qt::StatusTipRole);
+ if (variant.isValid())
+ Q_ASSERT(variant.canConvert(QVariant::String));
+ variant = model->data(model->index(0, 0), Qt::WhatsThisRole);
+ if (variant.isValid())
+ Q_ASSERT(variant.canConvert(QVariant::String));
+
+ // General Purpose roles that should return a QSize
+ variant = model->data(model->index(0, 0), Qt::SizeHintRole);
+ if (variant.isValid())
+ Q_ASSERT(variant.canConvert(QVariant::Size));
+
+ // General Purpose roles that should return a QFont
+ QVariant fontVariant = model->data(model->index(0, 0), Qt::FontRole);
+ if (fontVariant.isValid())
+ Q_ASSERT(fontVariant.canConvert(QVariant::Font));
+
+ // Check that the alignment is one we know about
+ QVariant textAlignmentVariant = model->data(model->index(0, 0), Qt::TextAlignmentRole);
+ if (textAlignmentVariant.isValid()) {
+ int alignment = textAlignmentVariant.toInt();
+ Q_ASSERT(alignment == (alignment & (Qt::AlignHorizontal_Mask | Qt::AlignVertical_Mask)));
+ }
+
+ // General Purpose roles that should return a QColor
+ QVariant colorVariant = model->data(model->index(0, 0), Qt::BackgroundColorRole);
+ if (colorVariant.isValid())
+ Q_ASSERT(colorVariant.canConvert(QVariant::Color));
+
+ colorVariant = model->data(model->index(0, 0), Qt::TextColorRole);
+ if (colorVariant.isValid())
+ Q_ASSERT(colorVariant.canConvert(QVariant::Color));
+
+ // Check that the "check state" is one we know about.
+ QVariant checkStateVariant = model->data(model->index(0, 0), Qt::CheckStateRole);
+ if (checkStateVariant.isValid()) {
+ int state = checkStateVariant.toInt();
+ Q_ASSERT(state == Qt::Unchecked ||
+ state == Qt::PartiallyChecked ||
+ state == Qt::Checked);
+ }
+}
+
+/*!
+ Store what is about to be inserted to make sure it actually happens
+
+ \sa rowsInserted()
+ */
+void ModelTest::rowsAboutToBeInserted(const QModelIndex &parent, int start, int end)
+{
+ Q_UNUSED(end);
+ Changing c;
+ c.parent = parent;
+ c.oldSize = model->rowCount(parent);
+ c.last = model->data(model->index(start - 1, 0, parent));
+ c.next = model->data(model->index(start, 0, parent));
+ insert.push(c);
+}
+
+/*!
+ Confirm that what was said was going to happen actually did
+
+ \sa rowsAboutToBeInserted()
+ */
+void ModelTest::rowsInserted(const QModelIndex & parent, int start, int end)
+{
+ Changing c = insert.pop();
+ Q_ASSERT(c.parent == parent);
+ Q_ASSERT(c.oldSize + (end - start + 1) == model->rowCount(parent));
+ Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent)));
+ /*
+ if (c.next != model->data(model->index(end + 1, 0, c.parent))) {
+ qDebug() << start << end;
+ for (int i=0; i < model->rowCount(); ++i)
+ qDebug() << model->index(i, 0).data().toString();
+ qDebug() << c.next << model->data(model->index(end + 1, 0, c.parent));
+ }
+ */
+ Q_ASSERT(c.next == model->data(model->index(end + 1, 0, c.parent)));
+}
+
+void ModelTest::layoutAboutToBeChanged()
+{
+ for (int i = 0; i < qBound(0, model->rowCount(), 100); ++i)
+ changing.append(QPersistentModelIndex(model->index(i, 0)));
+}
+
+void ModelTest::layoutChanged()
+{
+ for (int i = 0; i < changing.count(); ++i) {
+ QPersistentModelIndex p = changing[i];
+ Q_ASSERT(p == model->index(p.row(), p.column(), p.parent()));
+ }
+ changing.clear();
+}
+
+/*!
+ Store what is about to be inserted to make sure it actually happens
+
+ \sa rowsRemoved()
+ */
+void ModelTest::rowsAboutToBeRemoved(const QModelIndex &parent, int start, int end)
+{
+ Changing c;
+ c.parent = parent;
+ c.oldSize = model->rowCount(parent);
+ c.last = model->data(model->index(start - 1, 0, parent));
+ c.next = model->data(model->index(end + 1, 0, parent));
+ remove.push(c);
+}
+
+/*!
+ Confirm that what was said was going to happen actually did
+
+ \sa rowsAboutToBeRemoved()
+ */
+void ModelTest::rowsRemoved(const QModelIndex & parent, int start, int end)
+{
+ Changing c = remove.pop();
+ Q_ASSERT(c.parent == parent);
+ Q_ASSERT(c.oldSize - (end - start + 1) == model->rowCount(parent));
+ Q_ASSERT(c.last == model->data(model->index(start - 1, 0, c.parent)));
+ Q_ASSERT(c.next == model->data(model->index(start, 0, c.parent)));
+}
+
+} // anon namespace
+
+#endif // ModelTest
namespace Utils {
@@ -44,22 +611,28 @@ namespace Utils {
// TreeItem
//
TreeItem::TreeItem()
- : m_parent(0), m_lazy(false), m_populated(false),
+ : m_parent(0), m_model(0), m_displays(0), m_lazy(false), m_populated(false),
m_flags(Qt::ItemIsEnabled|Qt::ItemIsSelectable)
{
}
+TreeItem::TreeItem(const QStringList &displays, int flags)
+ : m_parent(0), m_model(0), m_displays(new QStringList(displays)), m_lazy(false), m_populated(false),
+ m_flags(flags)
+{
+}
+
TreeItem::~TreeItem()
{
clear();
+ delete m_displays;
}
TreeItem *TreeItem::child(int pos) const
{
ensurePopulated();
QTC_ASSERT(pos >= 0, return 0);
- QTC_ASSERT(pos < m_children.size(), return 0);
- return m_children.at(pos);
+ return pos < m_children.size() ? m_children.at(pos) : 0;
}
bool TreeItem::isLazy() const
@@ -67,11 +640,6 @@ bool TreeItem::isLazy() const
return m_lazy;
}
-int TreeItem::columnCount() const
-{
- return 1;
-}
-
int TreeItem::rowCount() const
{
ensurePopulated();
@@ -84,9 +652,17 @@ void TreeItem::populate()
QVariant TreeItem::data(int column, int role) const
{
+ if (role == Qt::DisplayRole && m_displays && column >= 0 && column < m_displays->size())
+ return m_displays->at(column);
+ return QVariant();
+}
+
+bool TreeItem::setData(int column, const QVariant &data, int role)
+{
Q_UNUSED(column);
+ Q_UNUSED(data);
Q_UNUSED(role);
- return QVariant();
+ return false;
}
Qt::ItemFlags TreeItem::flags(int column) const
@@ -95,18 +671,82 @@ Qt::ItemFlags TreeItem::flags(int column) const
return m_flags;
}
+bool TreeItem::hasChildren() const
+{
+ return canFetchMore() || rowCount() > 0;
+}
+
+bool TreeItem::canFetchMore() const
+{
+ return false;
+}
+
void TreeItem::prependChild(TreeItem *item)
{
- QTC_CHECK(!item->parent());
- item->m_parent = this;
- m_children.prepend(item);
+ insertChild(0, item);
}
void TreeItem::appendChild(TreeItem *item)
{
+ insertChild(m_children.size(), item);
+}
+
+void TreeItem::insertChild(int pos, TreeItem *item)
+{
QTC_CHECK(!item->parent());
- item->m_parent = this;
- m_children.append(item);
+ QTC_ASSERT(0 <= pos && pos <= m_children.size(), return); // '<= size' is intentional.
+
+ if (m_model && !m_lazy) {
+ QModelIndex idx = index();
+ m_model->beginInsertRows(idx, pos, pos);
+ item->m_parent = this;
+ item->propagateModel(m_model);
+ m_children.insert(m_children.begin() + pos, item);
+ m_model->endInsertRows();
+ } else {
+ item->m_parent = this;
+ m_children.insert(m_children.begin() + pos, item);
+ }
+}
+
+void TreeItem::removeChildren()
+{
+ if (rowCount() == 0)
+ return;
+ if (m_model) {
+ QModelIndex idx = index();
+ m_model->beginRemoveRows(idx, 0, rowCount() - 1);
+ clear();
+ m_model->endRemoveRows();
+ } else {
+ clear();
+ }
+}
+
+void TreeItem::update()
+{
+ if (m_model) {
+ QModelIndex idx = index();
+ m_model->dataChanged(idx.sibling(idx.row(), 0), idx.sibling(idx.row(), m_model->m_columnCount - 1));
+ }
+}
+
+TreeItem *TreeItem::firstChild() const
+{
+ return m_children.isEmpty() ? 0 : m_children.first();
+}
+
+TreeItem *TreeItem::lastChild() const
+{
+ return m_children.isEmpty() ? 0 : m_children.last();
+}
+
+int TreeItem::level() const
+{
+ int l = 0;
+ for (TreeItem *item = this->parent(); item; item = item->parent())
+ ++l;
+ return l;
}
void TreeItem::setLazy(bool on)
@@ -119,6 +759,40 @@ void TreeItem::setFlags(Qt::ItemFlags flags)
m_flags = flags;
}
+QModelIndex TreeItem::index() const
+{
+ QTC_ASSERT(m_model, return QModelIndex());
+ return m_model->indexFromItem(this);
+}
+
+void TreeItem::setModel(TreeModel *model)
+{
+ if (m_model == model)
+ return;
+ m_model = model;
+ foreach (TreeItem *item, m_children)
+ item->setModel(model);
+}
+
+void TreeItem::walkTree(TreeItemVisitor *visitor)
+{
+ if (visitor->preVisit(this)) {
+ ++visitor->m_level;
+ visitor->visit(this);
+ foreach (TreeItem *item, m_children)
+ item->walkTree(visitor);
+ --visitor->m_level;
+ }
+ visitor->postVisit(this);
+}
+
+void TreeItem::walkTree(std::function<void (TreeItem *)> f)
+{
+ f(this);
+ foreach (TreeItem *item, m_children)
+ item->walkTree(f);
+}
+
void TreeItem::clear()
{
while (m_children.size()) {
@@ -128,6 +802,12 @@ void TreeItem::clear()
}
}
+void TreeItem::expand()
+{
+ QTC_ASSERT(m_model, return);
+ m_model->requestExpansion(index());
+}
+
void TreeItem::ensurePopulated() const
{
if (!m_populated) {
@@ -137,12 +817,41 @@ void TreeItem::ensurePopulated() const
}
}
-//
-// TreeModel
-//
+void TreeItem::propagateModel(TreeModel *m)
+{
+ QTC_ASSERT(m, return);
+ QTC_ASSERT(m_model == 0 || m_model == m, return);
+ if (m && !m_model) {
+ m_model = m;
+ foreach (TreeItem *item, m_children)
+ item->propagateModel(m);
+ }
+}
+
+/*!
+ \class Utils::TreeModel
+
+ \brief The TreeModel class is a convienience base class for models
+ to use in a QTreeView.
+*/
+
TreeModel::TreeModel(QObject *parent)
- : QAbstractItemModel(parent), m_root(new TreeItem)
+ : QAbstractItemModel(parent),
+ m_root(new TreeItem)
{
+ m_columnCount = 1;
+ m_root->m_model = this;
+#if USE_MODEL_TEST
+ new ModelTest(this, this);
+#endif
+}
+
+TreeModel::TreeModel(TreeItem *root, QObject *parent)
+ : QAbstractItemModel(parent),
+ m_root(root)
+{
+ m_columnCount = 1;
+ m_root->propagateModel(this);
}
TreeModel::~TreeModel()
@@ -152,11 +861,12 @@ TreeModel::~TreeModel()
QModelIndex TreeModel::parent(const QModelIndex &idx) const
{
- checkIndex(idx);
+ CHECK_INDEX(idx);
if (!idx.isValid())
return QModelIndex();
const TreeItem *item = itemFromIndex(idx);
+ QTC_ASSERT(item, return QModelIndex());
const TreeItem *parent = item->parent();
if (!parent || parent == m_root)
return QModelIndex();
@@ -174,22 +884,31 @@ QModelIndex TreeModel::parent(const QModelIndex &idx) const
int TreeModel::rowCount(const QModelIndex &idx) const
{
- checkIndex(idx);
+ CHECK_INDEX(idx);
if (!idx.isValid())
return m_root->rowCount();
if (idx.column() > 0)
return 0;
- return itemFromIndex(idx)->rowCount();
+ const TreeItem *item = itemFromIndex(idx);
+ QTC_ASSERT(item, return 0);
+ return item->rowCount();
}
int TreeModel::columnCount(const QModelIndex &idx) const
{
- checkIndex(idx);
- if (!idx.isValid())
- return m_root->columnCount();
+ CHECK_INDEX(idx);
if (idx.column() > 0)
return 0;
- return itemFromIndex(idx)->columnCount();
+ return m_columnCount;
+}
+
+bool TreeModel::setData(const QModelIndex &idx, const QVariant &data, int role)
+{
+ TreeItem *item = itemFromIndex(idx);
+ bool res = item ? item->setData(idx.column(), data, role) : false;
+ if (res)
+ emit dataChanged(idx, idx);
+ return res;
}
QVariant TreeModel::data(const QModelIndex &idx, int role) const
@@ -198,21 +917,72 @@ QVariant TreeModel::data(const QModelIndex &idx, int role) const
return item ? item->data(idx.column(), role) : QVariant();
}
+QVariant TreeModel::headerData(int section, Qt::Orientation orientation,
+ int role) const
+{
+ if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section < m_header.size())
+ return m_header.at(section);
+ return QVariant();
+}
+
+bool TreeModel::hasChildren(const QModelIndex &idx) const
+{
+ TreeItem *item = itemFromIndex(idx);
+ return !item || item->hasChildren();
+}
+
Qt::ItemFlags TreeModel::flags(const QModelIndex &idx) const
{
+ if (!idx.isValid())
+ return 0;
TreeItem *item = itemFromIndex(idx);
return item ? item->flags(idx.column())
: (Qt::ItemIsEnabled|Qt::ItemIsSelectable);
}
+bool TreeModel::canFetchMore(const QModelIndex &idx) const
+{
+ if (!idx.isValid())
+ return false;
+ TreeItem *item = itemFromIndex(idx);
+ return item ? item->canFetchMore() : false;
+}
+
+void TreeModel::fetchMore(const QModelIndex &idx)
+{
+ if (!idx.isValid())
+ return;
+ TreeItem *item = itemFromIndex(idx);
+ if (item)
+ item->fetchMore();
+}
+
TreeItem *TreeModel::rootItem() const
{
return m_root;
}
+void TreeModel::setRootItem(TreeItem *item)
+{
+ delete m_root;
+ m_root = item;
+ item->setModel(this);
+}
+
+void TreeModel::setHeader(const QStringList &displays)
+{
+ m_header = displays;
+ m_columnCount = displays.size();
+}
+
+void TreeModel::setColumnCount(int columnCount)
+{
+ m_columnCount = columnCount;
+}
+
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) const
{
- checkIndex(parent);
+ CHECK_INDEX(parent);
if (!hasIndex(row, column, parent))
return QModelIndex();
@@ -225,42 +995,96 @@ QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent) con
TreeItem *TreeModel::itemFromIndex(const QModelIndex &idx) const
{
- checkIndex(idx);
+ CHECK_INDEX(idx);
TreeItem *item = idx.isValid() ? static_cast<TreeItem*>(idx.internalPointer()) : m_root;
-// CHECK(checkItem(item));
+ QTC_ASSERT(item, return 0);
+ QTC_ASSERT(item->m_model == this, return 0);
return item;
}
QModelIndex TreeModel::indexFromItem(const TreeItem *item) const
{
-// CHECK(checkItem(item));
- return indexFromItemHelper(item, m_root, QModelIndex());
+ QTC_ASSERT(item, return QModelIndex());
+ if (item == m_root)
+ return QModelIndex();
+
+ TreeItem *mitem = const_cast<TreeItem *>(item);
+ int row = item->parent()->m_children.indexOf(mitem);
+ return createIndex(row, 0, mitem);
}
-QModelIndex TreeModel::indexFromItemHelper(const TreeItem *needle,
- TreeItem *parentItem, const QModelIndex &parentIndex) const
+void TreeModel::removeItems()
{
- checkIndex(parentIndex);
- if (needle == parentItem)
- return parentIndex;
- for (int i = parentItem->rowCount(); --i >= 0; ) {
- TreeItem *childItem = parentItem->child(i);
- QModelIndex childIndex = index(i, 0, parentIndex);
- QModelIndex idx = indexFromItemHelper(needle, childItem, childIndex);
- checkIndex(idx);
- if (idx.isValid())
- return idx;
- }
- return QModelIndex();
+ if (m_root)
+ m_root->removeChildren();
}
-void TreeModel::checkIndex(const QModelIndex &index) const
+UntypedTreeLevelItems TreeModel::untypedLevelItems(int level, TreeItem *start) const
{
- if (index.isValid()) {
- QTC_CHECK(index.model() == this);
+ if (start == 0)
+ start = m_root;
+ return UntypedTreeLevelItems(start, level);
+}
+
+UntypedTreeLevelItems TreeModel::untypedLevelItems(TreeItem *start) const
+{
+ return UntypedTreeLevelItems(start, 1);
+}
+
+void TreeModel::removeItem(TreeItem *item)
+{
+#if USE_MODEL_TEST
+ (void) new ModelTest(this, this);
+#endif
+
+ QTC_ASSERT(item, return);
+ TreeItem *parent = item->parent();
+ QTC_ASSERT(parent, return);
+ int pos = parent->m_children.indexOf(item);
+ QTC_ASSERT(pos != -1, return);
+
+ QModelIndex idx = indexFromItem(parent);
+ beginRemoveRows(idx, pos, pos);
+ item->m_parent = 0;
+ parent->m_children.removeAt(pos);
+ endRemoveRows();
+}
+
+//
+// TreeLevelItems
+//
+
+UntypedTreeLevelItems::UntypedTreeLevelItems(TreeItem *item, int level)
+ : m_item(item), m_level(level)
+{}
+
+UntypedTreeLevelItems::const_iterator::const_iterator(TreeItem *base, int level)
+ : m_level(level)
+{
+ QTC_ASSERT(level > 0, return);
+ if (base) {
+ // "begin()"
+ m_depth = 0;
+ // Level x: The item m_item[x] is the m_pos[x]'th child of its
+ // parent, out of m_size[x].
+ m_pos[0] = 0;
+ m_size[0] = 1;
+ m_item[0] = base;
+ goDown();
} else {
- QTC_CHECK(index.model() == 0);
+ // "end()"
+ m_depth = -1;
}
}
+UntypedTreeLevelItems::const_iterator UntypedTreeLevelItems::begin() const
+{
+ return const_iterator(m_item, m_level);
+}
+
+UntypedTreeLevelItems::const_iterator UntypedTreeLevelItems::end() const
+{
+ return const_iterator(0, m_level);
+}
+
} // namespace Utils
diff --git a/src/libs/utils/treemodel.h b/src/libs/utils/treemodel.h
index ffcb0b381df..6e654fdfaab 100644
--- a/src/libs/utils/treemodel.h
+++ b/src/libs/utils/treemodel.h
@@ -33,32 +33,78 @@
#include "utils_global.h"
+#include "algorithm.h"
+#include "qtcassert.h"
+
#include <QAbstractItemModel>
+#include <functional>
+#include <iterator>
+
namespace Utils {
+class TreeItem;
+class TreeModel;
+
+class QTCREATOR_UTILS_EXPORT TreeItemVisitor
+{
+public:
+ TreeItemVisitor() : m_level(0) {}
+ virtual ~TreeItemVisitor() {}
+
+ virtual bool preVisit(TreeItem *) { return true; }
+ virtual void visit(TreeItem *) {}
+ virtual void postVisit(TreeItem *) {}
+
+ int level() const { return m_level; }
+
+private:
+ friend class TreeItem;
+ int m_level;
+};
+
class QTCREATOR_UTILS_EXPORT TreeItem
{
public:
TreeItem();
+ explicit TreeItem(const QStringList &displays, int flags = Qt::ItemIsEnabled);
virtual ~TreeItem();
virtual TreeItem *parent() const { return m_parent; }
virtual TreeItem *child(int pos) const;
virtual bool isLazy() const;
- virtual int columnCount() const;
virtual int rowCount() const;
virtual void populate();
virtual QVariant data(int column, int role) const;
+ virtual bool setData(int column, const QVariant &data, int role);
virtual Qt::ItemFlags flags(int column) const;
+ virtual bool hasChildren() const;
+ virtual bool canFetchMore() const;
+ virtual void fetchMore() {}
+
void prependChild(TreeItem *item);
void appendChild(TreeItem *item);
+ void insertChild(int pos, TreeItem *item);
+ void removeChildren();
+ void update();
+ void expand();
+ TreeItem *firstChild() const;
+ TreeItem *lastChild() const;
+ int level() const;
void setLazy(bool on);
void setPopulated(bool on);
void setFlags(Qt::ItemFlags flags);
+ QVector<TreeItem *> children() const { return m_children; }
+ QModelIndex index() const;
+
+ TreeModel *model() const { return m_model; }
+ void setModel(TreeModel *model);
+
+ void walkTree(TreeItemVisitor *visitor);
+ void walkTree(std::function<void(TreeItem *)> f);
private:
TreeItem(const TreeItem &) Q_DECL_EQ_DELETE;
@@ -66,39 +112,207 @@ private:
void clear();
void ensurePopulated() const;
+ void propagateModel(TreeModel *m);
TreeItem *m_parent; // Not owned.
+ TreeModel *m_model; // Not owned.
QVector<TreeItem *> m_children; // Owned.
+ QStringList *m_displays;
bool m_lazy;
mutable bool m_populated;
Qt::ItemFlags m_flags;
+
+ friend class TreeModel;
+};
+
+class QTCREATOR_UTILS_EXPORT UntypedTreeLevelItems
+{
+public:
+ enum { MaxSearchDepth = 12 }; // FIXME.
+ explicit UntypedTreeLevelItems(TreeItem *item, int level = 1);
+
+ typedef TreeItem *value_type;
+
+ class const_iterator
+ {
+ public:
+ typedef std::forward_iterator_tag iterator_category;
+ typedef TreeItem *value_type;
+ typedef std::ptrdiff_t difference_type;
+ typedef const value_type *pointer;
+ typedef const value_type &reference;
+
+ const_iterator(TreeItem *base, int level);
+
+ TreeItem *operator*() { return m_item[m_depth]; }
+
+ void operator++()
+ {
+ QTC_ASSERT(m_depth == m_level, return);
+
+ int pos = ++m_pos[m_depth];
+ if (pos < m_size[m_depth])
+ m_item[m_depth] = m_item[m_depth - 1]->child(pos);
+ else
+ goUpNextDown();
+ }
+
+ bool operator==(const const_iterator &other) const
+ {
+ if (m_depth != other.m_depth)
+ return false;
+ for (int i = 0; i <= m_depth; ++i)
+ if (m_item[i] != other.m_item[i])
+ return false;
+ return true;
+ }
+
+ bool operator!=(const const_iterator &other) const
+ {
+ return !operator==(other);
+ }
+
+ private:
+ // Result is either an item of the target level, or 'end'.
+ void goDown()
+ {
+ QTC_ASSERT(m_depth != -1, return);
+ QTC_ASSERT(m_depth < m_level, return);
+ do {
+ TreeItem *curr = m_item[m_depth];
+ ++m_depth;
+ int size = curr->rowCount();
+ if (size == 0) {
+ // This is a dead end not reaching to the desired level.
+ goUpNextDown();
+ return;
+ }
+ m_size[m_depth] = size;
+ m_pos[m_depth] = 0;
+ m_item[m_depth] = curr->child(0);
+ } while (m_depth < m_level);
+ // Did not reach the required level? Set to end().
+ if (m_depth != m_level)
+ m_depth = -1;
+ }
+ void goUpNextDown()
+ {
+ // Go up until we can move sidewards.
+ do {
+ --m_depth;
+ if (m_depth < 0)
+ return; // Solid end.
+ } while (++m_pos[m_depth] >= m_size[m_depth]);
+ m_item[m_depth] = m_item[m_depth - 1]->child(m_pos[m_depth]);
+ goDown();
+ }
+
+ int m_level;
+ int m_depth;
+ TreeItem *m_item[MaxSearchDepth];
+ int m_pos[MaxSearchDepth];
+ int m_size[MaxSearchDepth];
+ };
+
+ const_iterator begin() const;
+ const_iterator end() const;
+
+private:
+ TreeItem *m_item;
+ int m_level;
+};
+
+template <class T>
+class TreeLevelItems
+{
+public:
+ typedef T value_type;
+
+ explicit TreeLevelItems(const UntypedTreeLevelItems &items) : m_items(items) {}
+
+ struct const_iterator : public UntypedTreeLevelItems::const_iterator
+ {
+ typedef std::forward_iterator_tag iterator_category;
+ typedef T value_type;
+ typedef std::ptrdiff_t difference_type;
+ typedef const value_type *pointer;
+ typedef const value_type &reference;
+
+ const_iterator(UntypedTreeLevelItems::const_iterator it) : UntypedTreeLevelItems::const_iterator(it) {}
+ T operator*() { return static_cast<T>(UntypedTreeLevelItems::const_iterator::operator*()); }
+ };
+
+ const_iterator begin() const { return const_iterator(m_items.begin()); }
+ const_iterator end() const { return const_iterator(m_items.end()); }
+
+private:
+ UntypedTreeLevelItems m_items;
};
class QTCREATOR_UTILS_EXPORT TreeModel : public QAbstractItemModel
{
+ Q_OBJECT
+
public:
explicit TreeModel(QObject *parent = 0);
+ explicit TreeModel(TreeItem *root, QObject *parent = 0);
virtual ~TreeModel();
int rowCount(const QModelIndex &idx = QModelIndex()) const;
int columnCount(const QModelIndex &idx) const;
+ bool setData(const QModelIndex &idx, const QVariant &data, int role);
QVariant data(const QModelIndex &idx, int role) const;
QModelIndex index(int, int, const QModelIndex &idx) const;
QModelIndex parent(const QModelIndex &idx) const;
Qt::ItemFlags flags(const QModelIndex &idx) const;
+ QVariant headerData(int section, Qt::Orientation orientation, int role) const;
+ bool hasChildren(const QModelIndex &idx) const;
+
+ bool canFetchMore(const QModelIndex &idx) const;
+ void fetchMore(const QModelIndex &idx);
TreeItem *rootItem() const;
+ void setRootItem(TreeItem *item);
TreeItem *itemFromIndex(const QModelIndex &) const;
QModelIndex indexFromItem(const TreeItem *needle) const;
+ void removeItems();
-private:
- QModelIndex indexFromItemHelper(const TreeItem *needle,
- TreeItem *parentItem, const QModelIndex &parentIndex) const;
+ void setHeader(const QStringList &displays);
+ void setColumnCount(int columnCount);
+
+ UntypedTreeLevelItems untypedLevelItems(int level = 0, TreeItem *start = 0) const;
+ UntypedTreeLevelItems untypedLevelItems(TreeItem *start) const;
- void checkIndex(const QModelIndex &index) const;
+ template <class T>
+ TreeLevelItems<T> treeLevelItems(int level, TreeItem *start = 0) const
+ {
+ return TreeLevelItems<T>(untypedLevelItems(level, start));
+ }
+
+ template <class T>
+ TreeLevelItems<T> treeLevelItems(TreeItem *start) const
+ {
+ return TreeLevelItems<T>(untypedLevelItems(start));
+ }
+
+ template <class T>
+ T findItemAtLevel(int level, std::function<bool(T)> f, TreeItem *start = 0) const
+ {
+ return Utils::findOrDefault(treeLevelItems<T>(level, start), f);
+ }
+
+ void removeItem(TreeItem *item); // item is not destroyed.
+
+signals:
+ void requestExpansion(QModelIndex);
+
+private:
+ friend class TreeItem;
TreeItem *m_root; // Owned.
+ QStringList m_header;
+ int m_columnCount;
};
} // namespace Utils
diff --git a/src/libs/utils/unixutils.cpp b/src/libs/utils/unixutils.cpp
index d6d98973817..a93209d463e 100644
--- a/src/libs/utils/unixutils.cpp
+++ b/src/libs/utils/unixutils.cpp
@@ -28,8 +28,9 @@
**
****************************************************************************/
-
#include "unixutils.h"
+#include "fileutils.h"
+
#include <QSettings>
#include <QFileInfo>
#include <QCoreApplication>
@@ -81,7 +82,7 @@ QString UnixUtils::substituteFileBrowserParameters(const QString &pre, const QSt
} else if (c == QLatin1Char('f')) {
s = QLatin1Char('"') + file + QLatin1Char('"');
} else if (c == QLatin1Char('n')) {
- s = QLatin1Char('"') + QFileInfo(file).fileName() + QLatin1Char('"');
+ s = QLatin1Char('"') + FileName::fromString(file).fileName() + QLatin1Char('"');
} else if (c == QLatin1Char('%')) {
s = c;
} else {
diff --git a/src/libs/utils/utils-lib.pri b/src/libs/utils/utils-lib.pri
index f339efdb8a2..34b3549dc8e 100644
--- a/src/libs/utils/utils-lib.pri
+++ b/src/libs/utils/utils-lib.pri
@@ -49,7 +49,6 @@ SOURCES += $$PWD/environment.cpp \
$$PWD/checkablemessagebox.cpp \
$$PWD/styledbar.cpp \
$$PWD/stylehelper.cpp \
- $$PWD/iwelcomepage.cpp \
$$PWD/fancymainwindow.cpp \
$$PWD/detailsbutton.cpp \
$$PWD/detailswidget.cpp \
@@ -82,7 +81,6 @@ SOURCES += $$PWD/environment.cpp \
$$PWD/hostosinfo.cpp \
$$PWD/tooltip/tooltip.cpp \
$$PWD/tooltip/tips.cpp \
- $$PWD/tooltip/tipcontents.cpp \
$$PWD/unixutils.cpp \
$$PWD/ansiescapecodehandler.cpp \
$$PWD/execmenu.cpp \
@@ -93,7 +91,9 @@ SOURCES += $$PWD/environment.cpp \
$$PWD/treeviewcombobox.cpp \
$$PWD/proxycredentialsdialog.cpp \
$$PWD/macroexpander.cpp \
- $$PWD/theme/theme.cpp
+ $$PWD/theme/theme.cpp \
+ $$PWD/progressindicator.cpp \
+ $$PWD/fadingindicator.cpp
win32:SOURCES += $$PWD/consoleprocess_win.cpp
else:SOURCES += $$PWD/consoleprocess_unix.cpp
@@ -139,7 +139,6 @@ HEADERS += \
$$PWD/qtcassert.h \
$$PWD/styledbar.h \
$$PWD/stylehelper.h \
- $$PWD/iwelcomepage.h \
$$PWD/fancymainwindow.h \
$$PWD/detailsbutton.h \
$$PWD/detailswidget.h \
@@ -175,7 +174,6 @@ HEADERS += \
$$PWD/elidinglabel.h \
$$PWD/tooltip/tooltip.h \
$$PWD/tooltip/tips.h \
- $$PWD/tooltip/tipcontents.h \
$$PWD/tooltip/reuse.h \
$$PWD/tooltip/effects.h \
$$PWD/unixutils.h \
@@ -192,7 +190,9 @@ HEADERS += \
$$PWD/proxycredentialsdialog.h \
$$PWD/macroexpander.h \
$$PWD/theme/theme.h \
- $$PWD/theme/theme_p.h
+ $$PWD/theme/theme_p.h \
+ $$PWD/progressindicator.h \
+ $$PWD/fadingindicator.h
FORMS += $$PWD/filewizardpage.ui \
$$PWD/projectintropage.ui \
diff --git a/src/libs/utils/utils.qbs b/src/libs/utils/utils.qbs
index 456dbd7dbc4..603a0e6e49f 100644
--- a/src/libs/utils/utils.qbs
+++ b/src/libs/utils/utils.qbs
@@ -72,6 +72,8 @@ QtcLibrary {
"environmentmodel.h",
"execmenu.cpp",
"execmenu.h",
+ "fadingindicator.cpp",
+ "fadingindicator.h",
"faketooltip.cpp",
"faketooltip.h",
"fancylineedit.cpp",
@@ -101,8 +103,6 @@ QtcLibrary {
"htmldocextractor.h",
"itemviews.cpp",
"itemviews.h",
- "iwelcomepage.cpp",
- "iwelcomepage.h",
"json.cpp",
"json.h",
"linecolumnlabel.cpp",
@@ -132,6 +132,8 @@ QtcLibrary {
"persistentsettings.h",
"portlist.cpp",
"portlist.h",
+ "progressindicator.cpp",
+ "progressindicator.h",
"projectintropage.cpp",
"projectintropage.h",
"projectintropage.ui",
@@ -204,6 +206,10 @@ QtcLibrary {
"images/crumblepath-segment-selected-end.png",
"images/crumblepath-segment-selected.png",
"images/crumblepath-segment.png",
+ "images/progressindicator_big.png",
+ "images/progressindicator_big@2x.png",
+ "images/progressindicator_small.png",
+ "images/progressindicator_small@2x.png",
"images/triangle_vert.png",
]
@@ -223,8 +229,6 @@ QtcLibrary {
files: [
"effects.h",
"reuse.h",
- "tipcontents.cpp",
- "tipcontents.h",
"tips.cpp",
"tips.h",
"tooltip.cpp",
diff --git a/src/libs/utils/utils.qrc b/src/libs/utils/utils.qrc
index 2748bccb6c8..c7be7e8de8e 100644
--- a/src/libs/utils/utils.qrc
+++ b/src/libs/utils/utils.qrc
@@ -7,6 +7,12 @@
<file>images/crumblepath-segment-hover.png</file>
<file>images/crumblepath-segment-selected-end.png</file>
<file>images/crumblepath-segment-selected.png</file>
+ <file>images/progressindicator_big.png</file>
+ <file>images/progressindicator_big@2x.png</file>
+ <file>images/progressindicator_medium.png</file>
+ <file>images/progressindicator_medium@2x.png</file>
+ <file>images/progressindicator_small.png</file>
+ <file>images/progressindicator_small@2x.png</file>
<file>images/triangle_vert.png</file>
</qresource>
</RCC>
diff --git a/src/libs/utils/wizard.cpp b/src/libs/utils/wizard.cpp
index a551825e37d..022ce467826 100644
--- a/src/libs/utils/wizard.cpp
+++ b/src/libs/utils/wizard.cpp
@@ -322,9 +322,9 @@ Wizard::Wizard(QWidget *parent, Qt::WindowFlags flags) :
{
d_ptr->q_ptr = this;
d_ptr->m_wizardProgress = new WizardProgress(this);
- connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(_q_currentPageChanged(int)));
- connect(this, SIGNAL(pageAdded(int)), this, SLOT(_q_pageAdded(int)));
- connect(this, SIGNAL(pageRemoved(int)), this, SLOT(_q_pageRemoved(int)));
+ connect(this, &QWizard::currentIdChanged, this, &Wizard::_q_currentPageChanged);
+ connect(this, &QWizard::pageAdded, this, &Wizard::_q_pageAdded);
+ connect(this, &QWizard::pageRemoved, this, &Wizard::_q_pageRemoved);
setSideWidget(new LinearProgressWidget(d_ptr->m_wizardProgress, this));
setOption(QWizard::NoCancelButton, false);
setOption(QWizard::NoDefaultButton, false);
diff --git a/src/libs/utils/wizardpage.h b/src/libs/utils/wizardpage.h
index 13a9871d302..5ff240339b4 100644
--- a/src/libs/utils/wizardpage.h
+++ b/src/libs/utils/wizardpage.h
@@ -52,6 +52,10 @@ public:
void registerFieldWithName(const QString &name, QWidget *widget,
const char *property = 0, const char *changedSignal = 0);
+signals:
+ // Emitted when there is something that the developer using this page should be aware of.
+ void reportError(const QString &errorMessage);
+
private:
QSet<QString> m_toRegister;
};
diff --git a/src/plugins/analyzerbase/analyzermanager.cpp b/src/plugins/analyzerbase/analyzermanager.cpp
index d68cf1ccef9..80e0397e507 100644
--- a/src/plugins/analyzerbase/analyzermanager.cpp
+++ b/src/plugins/analyzerbase/analyzermanager.cpp
@@ -161,7 +161,7 @@ public slots:
void startTool();
void selectToolboxAction(int);
void selectMenuAction();
- void modeChanged(Core::IMode *mode);
+ void modeChanged(IMode *mode);
void resetLayout();
void updateRunActions();
diff --git a/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp b/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp
index c7c27fceeba..8f2390cfcd9 100644
--- a/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp
+++ b/src/plugins/analyzerbase/analyzerrunconfigwidget.cpp
@@ -58,12 +58,13 @@ AnalyzerRunConfigWidget::AnalyzerRunConfigWidget(ProjectExplorer::IRunConfigurat
<< QApplication::translate("ProjectExplorer::Internal::EditorSettingsPropertiesPage", "Custom")
);
globalSettingLayout->addWidget(m_settingsCombo);
- connect(m_settingsCombo, SIGNAL(activated(int)), this, SLOT(chooseSettings(int)));
+ connect(m_settingsCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
+ this, &AnalyzerRunConfigWidget::chooseSettings);
m_restoreButton = new QPushButton(
QApplication::translate("ProjectExplorer::Internal::EditorSettingsPropertiesPage", "Restore Global"),
globalSetting);
globalSettingLayout->addWidget(m_restoreButton);
- connect(m_restoreButton, SIGNAL(clicked()), this, SLOT(restoreGlobal()));
+ connect(m_restoreButton, &QPushButton::clicked, this, &AnalyzerRunConfigWidget::restoreGlobal);
globalSettingLayout->addStretch(2);
QWidget *innerPane = new QWidget;
diff --git a/src/plugins/analyzerbase/analyzerruncontrol.cpp b/src/plugins/analyzerbase/analyzerruncontrol.cpp
index 9f91c6e2117..7d05b1efdc2 100644
--- a/src/plugins/analyzerbase/analyzerruncontrol.cpp
+++ b/src/plugins/analyzerbase/analyzerruncontrol.cpp
@@ -48,7 +48,7 @@ using namespace ProjectExplorer;
namespace Analyzer {
AnalyzerRunControl::AnalyzerRunControl(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
+ RunConfiguration *runConfiguration)
: RunControl(runConfiguration, sp.runMode)
{
setIcon(QLatin1String(":/images/analyzer_start_small.png"));
@@ -56,7 +56,8 @@ AnalyzerRunControl::AnalyzerRunControl(const AnalyzerStartParameters &sp,
m_runConfig = runConfiguration;
m_sp = sp;
- connect(this, SIGNAL(finished()), SLOT(runControlFinished()));
+ connect(this, &AnalyzerRunControl::finished,
+ this, &AnalyzerRunControl::runControlFinished);
connect(AnalyzerManager::stopAction(), SIGNAL(triggered()), SLOT(stopIt()));
}
diff --git a/src/plugins/analyzerbase/analyzerutils.cpp b/src/plugins/analyzerbase/analyzerutils.cpp
index 736dce16fd0..ed6e9b0c28f 100644
--- a/src/plugins/analyzerbase/analyzerutils.cpp
+++ b/src/plugins/analyzerbase/analyzerutils.cpp
@@ -63,18 +63,18 @@ static void moveCursorToEndOfName(QTextCursor *tc)
// We cannot depend on this since CppEditor plugin code is internal and requires building the implementation files ourselves
CPlusPlus::Symbol *AnalyzerUtils::findSymbolUnderCursor()
{
- TextEditor::BaseTextEditor *editor = TextEditor::BaseTextEditor::currentTextEditor();
- if (!editor)
+ TextEditor::TextEditorWidget *widget = TextEditor::TextEditorWidget::currentTextEditorWidget();
+ if (!widget)
return 0;
- QTextCursor tc = editor->textCursor();
+ QTextCursor tc = widget->textCursor();
int line = 0;
int column = 0;
const int pos = tc.position();
- editor->convertPosition(pos, &line, &column);
+ widget->convertPosition(pos, &line, &column);
const CPlusPlus::Snapshot &snapshot = CppTools::CppModelManager::instance()->snapshot();
- CPlusPlus::Document::Ptr doc = snapshot.document(editor->document()->filePath());
+ CPlusPlus::Document::Ptr doc = snapshot.document(widget->textDocument()->filePath());
QTC_ASSERT(doc, return 0);
// fetch the expression's code
diff --git a/src/plugins/analyzerbase/detailederrorview.cpp b/src/plugins/analyzerbase/detailederrorview.cpp
index 9c5904b1980..bc1dfdbc35a 100644
--- a/src/plugins/analyzerbase/detailederrorview.cpp
+++ b/src/plugins/analyzerbase/detailederrorview.cpp
@@ -30,10 +30,14 @@
#include "detailederrorview.h"
+#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <utils/qtcassert.h>
+#include <QApplication>
+#include <QClipboard>
+#include <QContextMenuEvent>
#include <QFontMetrics>
#include <QPainter>
#include <QScrollBar>
@@ -216,6 +220,11 @@ void DetailedErrorDelegate::openLinkInEditor(const QString &link)
Core::EditorManager::openEditorAt(path, qMax(line, 0), qMax(column, 0));
}
+void DetailedErrorDelegate::copyToClipboard()
+{
+ QApplication::clipboard()->setText(textualRepresentation());
+}
+
DetailedErrorView::DetailedErrorView(QWidget *parent)
: QListView(parent)
{
@@ -232,6 +241,14 @@ void DetailedErrorView::setItemDelegate(QAbstractItemDelegate *delegate)
DetailedErrorDelegate *myDelegate = qobject_cast<DetailedErrorDelegate *>(itemDelegate());
connect(this, &DetailedErrorView::resized, myDelegate, &DetailedErrorDelegate::onViewResized);
+
+ m_copyAction = new QAction(this);
+ m_copyAction->setText(tr("Copy"));
+ m_copyAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
+ m_copyAction->setShortcut(QKeySequence::Copy);
+ m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
+ connect(m_copyAction, &QAction::triggered, myDelegate, &DetailedErrorDelegate::copyToClipboard);
+ addAction(m_copyAction);
}
void DetailedErrorView::setModel(QAbstractItemModel *model)
@@ -253,6 +270,21 @@ void DetailedErrorView::resizeEvent(QResizeEvent *e)
QListView::resizeEvent(e);
}
+void DetailedErrorView::contextMenuEvent(QContextMenuEvent *e)
+{
+ if (selectionModel()->selectedRows().isEmpty())
+ return;
+
+ QMenu menu;
+ menu.addActions(commonActions());
+ const QList<QAction *> custom = customActions();
+ if (!custom.isEmpty()) {
+ menu.addSeparator();
+ menu.addActions(custom);
+ }
+ menu.exec(e->globalPos());
+}
+
void DetailedErrorView::updateGeometries()
{
if (model()) {
@@ -284,6 +316,18 @@ int DetailedErrorView::rowCount() const
return model() ? model()->rowCount() : 0;
}
+QList<QAction *> DetailedErrorView::commonActions() const
+{
+ QList<QAction *> actions;
+ actions << m_copyAction;
+ return actions;
+}
+
+QList<QAction *> DetailedErrorView::customActions() const
+{
+ return QList<QAction *>();
+}
+
int DetailedErrorView::currentRow() const
{
const QModelIndex index = selectionModel()->currentIndex();
diff --git a/src/plugins/analyzerbase/detailederrorview.h b/src/plugins/analyzerbase/detailederrorview.h
index 3e9470dc4e8..7273181376d 100644
--- a/src/plugins/analyzerbase/detailederrorview.h
+++ b/src/plugins/analyzerbase/detailederrorview.h
@@ -55,7 +55,7 @@ public:
explicit DetailedErrorDelegate(QListView *parent);
virtual SummaryLineInfo summaryInfo(const QModelIndex &index) const = 0;
- virtual void copy() = 0;
+ void copyToClipboard();
QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const;
void paint(QPainter *painter, const QStyleOptionViewItem &option,
@@ -77,6 +77,7 @@ private:
// the constness of this function is a necessary lie because it is called from paint() const.
virtual QWidget *createDetailsWidget(const QFont &font, const QModelIndex &errorIndex,
QWidget *parent) const = 0;
+ virtual QString textualRepresentation() const = 0;
static const int s_itemMargin = 2;
mutable QWidget *m_detailsWidget;
@@ -109,10 +110,16 @@ protected:
void resizeEvent(QResizeEvent *e);
private:
+ void contextMenuEvent(QContextMenuEvent *e) Q_DECL_OVERRIDE;
+
int currentRow() const;
void setCurrentRow(int row);
-
int rowCount() const;
+
+ QList<QAction *> commonActions() const;
+ virtual QList<QAction *> customActions() const;
+
+ QAction *m_copyAction;
};
} // namespace Analyzer
diff --git a/src/plugins/analyzerbase/startremotedialog.cpp b/src/plugins/analyzerbase/startremotedialog.cpp
index 03acf481ba0..a7cc9c68d9e 100644
--- a/src/plugins/analyzerbase/startremotedialog.cpp
+++ b/src/plugins/analyzerbase/startremotedialog.cpp
@@ -94,12 +94,12 @@ StartRemoteDialog::StartRemoteDialog(QWidget *parent)
d->arguments->setText(settings->value(QLatin1String("arguments")).toString());
settings->endGroup();
- connect(d->kitChooser, SIGNAL(activated(int)), SLOT(validate()));
- connect(d->executable, SIGNAL(textChanged(QString)), SLOT(validate()));
- connect(d->workingDirectory, SIGNAL(textChanged(QString)), SLOT(validate()));
- connect(d->arguments, SIGNAL(textChanged(QString)), SLOT(validate()));
- connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));
- connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));
+ connect(d->kitChooser, &KitChooser::activated, this, &StartRemoteDialog::validate);
+ connect(d->executable, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
+ connect(d->workingDirectory, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
+ connect(d->arguments, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
+ connect(d->buttonBox, &QDialogButtonBox::accepted, this, &StartRemoteDialog::accept);
+ connect(d->buttonBox, &QDialogButtonBox::rejected, this, &StartRemoteDialog::reject);
validate();
}
diff --git a/src/plugins/android/androidanalyzesupport.cpp b/src/plugins/android/androidanalyzesupport.cpp
index 83736a042cf..7c1fe17a52c 100644
--- a/src/plugins/android/androidanalyzesupport.cpp
+++ b/src/plugins/android/androidanalyzesupport.cpp
@@ -61,7 +61,7 @@ RunControl *AndroidAnalyzeSupport::createAnalyzeRunControl(AndroidRunConfigurati
params.sysroot = SysRootKitInformation::sysRoot(target->kit()).toString();
// TODO: Not sure if these are the right paths.
params.workingDirectory = target->project()->projectDirectory().toString();
- if (runMode == ProjectExplorer::QmlProfilerRunMode) {
+ if (runMode == QmlProfilerRunMode) {
QTcpServer server;
QTC_ASSERT(server.listen(QHostAddress::LocalHost)
|| server.listen(QHostAddress::LocalHostIPv6), return 0);
diff --git a/src/plugins/android/androidbuildapkwidget.ui b/src/plugins/android/androidbuildapkwidget.ui
index 51ba40b30c8..dd084a72c3a 100644
--- a/src/plugins/android/androidbuildapkwidget.ui
+++ b/src/plugins/android/androidbuildapkwidget.ui
@@ -154,7 +154,7 @@
</property>
<property name="text">
<string>Signing an APK that uses &quot;Deploy local Qt libraries&quot; is not allowed.
-Deploying local Qt libraries is incompatible with Android 5</string>
+Deploying local Qt libraries is incompatible with Android 5.</string>
</property>
</widget>
</item>
diff --git a/src/plugins/android/androidconfigurations.cpp b/src/plugins/android/androidconfigurations.cpp
index 206a1f67fa3..a8b77a3ffef 100644
--- a/src/plugins/android/androidconfigurations.cpp
+++ b/src/plugins/android/androidconfigurations.cpp
@@ -135,9 +135,9 @@ namespace {
static bool is32BitUserSpace()
{
// Do the exact same check as android's emulator is doing:
- if (Utils::HostOsInfo::isLinuxHost()) {
+ if (HostOsInfo::isLinuxHost()) {
if (QSysInfo::WordSize == 32 ) {
- Utils::Environment env = Utils::Environment::systemEnvironment();
+ Environment env = Environment::systemEnvironment();
QString executable = env.searchInPath(QLatin1String("file")).toString();
QString shell = env.value(QLatin1String("SHELL"));
if (executable.isEmpty() || shell.isEmpty())
@@ -224,15 +224,13 @@ void AndroidConfig::load(const QSettings &settings)
if (reader.load(FileName::fromString(sdkSettingsFileName()))
&& settings.value(changeTimeStamp).toInt() != QFileInfo(sdkSettingsFileName()).lastModified().toMSecsSinceEpoch() / 1000) {
// persisten settings
- m_sdkLocation = FileName::fromString(reader.restoreValue(SDKLocationKey).toString());
- m_ndkLocation = FileName::fromString(reader.restoreValue(NDKLocationKey).toString());
- m_antLocation = FileName::fromString(reader.restoreValue(AntLocationKey).toString());
- m_openJDKLocation = FileName::fromString(reader.restoreValue(OpenJDKLocationKey).toString());
- m_keystoreLocation = FileName::fromString(reader.restoreValue(KeystoreLocationKey).toString());
- m_toolchainHost = reader.restoreValue(ToolchainHostKey).toString();
- QVariant v = reader.restoreValue(AutomaticKitCreationKey);
- if (v.isValid())
- m_automaticKitCreation = v.toBool();
+ m_sdkLocation = FileName::fromString(reader.restoreValue(SDKLocationKey, m_sdkLocation.toString()).toString());
+ m_ndkLocation = FileName::fromString(reader.restoreValue(NDKLocationKey, m_ndkLocation.toString()).toString());
+ m_antLocation = FileName::fromString(reader.restoreValue(AntLocationKey, m_antLocation.toString()).toString());
+ m_openJDKLocation = FileName::fromString(reader.restoreValue(OpenJDKLocationKey, m_openJDKLocation.toString()).toString());
+ m_keystoreLocation = FileName::fromString(reader.restoreValue(KeystoreLocationKey, m_keystoreLocation.toString()).toString());
+ m_toolchainHost = reader.restoreValue(ToolchainHostKey, m_toolchainHost).toString();
+ m_automaticKitCreation = reader.restoreValue(AutomaticKitCreationKey, m_automaticKitCreation).toBool();
QString extraDirectory = reader.restoreValue(MakeExtraSearchDirectory).toString();
m_makeExtraSearchDirectories.clear();
if (!extraDirectory.isEmpty())
@@ -392,13 +390,13 @@ QList<SdkPlatform> AndroidConfig::sdkTargets(int minApiLevel) const
FileName AndroidConfig::adbToolPath() const
{
- Utils::FileName path = m_sdkLocation;
+ FileName path = m_sdkLocation;
return path.appendPath(QLatin1String("platform-tools/adb" QTC_HOST_EXE_SUFFIX));
}
-Utils::Environment AndroidConfig::androidToolEnvironment() const
+Environment AndroidConfig::androidToolEnvironment() const
{
- Utils::Environment env = Utils::Environment::systemEnvironment();
+ Environment env = Environment::systemEnvironment();
if (!m_openJDKLocation.isEmpty())
env.set(QLatin1String("JAVA_HOME"), m_openJDKLocation.toUserOutput());
return env;
@@ -537,7 +535,7 @@ QFuture<AndroidConfig::CreateAvdInfo> AndroidConfig::createAVD(CreateAvdInfo inf
return QtConcurrent::run(&AndroidConfig::createAVDImpl, info, androidToolPath(), androidToolEnvironment());
}
-AndroidConfig::CreateAvdInfo AndroidConfig::createAVDImpl(CreateAvdInfo info, Utils::FileName androidToolPath, Utils::Environment env)
+AndroidConfig::CreateAvdInfo AndroidConfig::createAVDImpl(CreateAvdInfo info, FileName androidToolPath, Environment env)
{
QProcess proc;
proc.setProcessEnvironment(env.toProcessEnvironment());
@@ -602,12 +600,22 @@ bool AndroidConfig::removeAVD(const QString &name) const
return !proc.exitCode();
}
+QFuture<QVector<AndroidDeviceInfo>> AndroidConfig::androidVirtualDevicesFuture()
+{
+ return QtConcurrent::run(&AndroidConfig::androidVirtualDevicesImpl, androidToolPath(), androidToolEnvironment());
+}
+
QVector<AndroidDeviceInfo> AndroidConfig::androidVirtualDevices() const
{
+ return androidVirtualDevicesImpl(androidToolPath(), androidToolEnvironment());
+}
+
+QVector<AndroidDeviceInfo> AndroidConfig::androidVirtualDevicesImpl(const FileName &androidTool, const Environment &environment)
+{
QVector<AndroidDeviceInfo> devices;
QProcess proc;
- proc.setProcessEnvironment(androidToolEnvironment().toProcessEnvironment());
- proc.start(androidToolPath().toString(),
+ proc.setProcessEnvironment(environment.toProcessEnvironment());
+ proc.start(androidTool.toString(),
QStringList() << QLatin1String("list") << QLatin1String("avd")); // list available AVDs
if (!proc.waitForFinished(5000)) {
proc.terminate();
@@ -1007,7 +1015,7 @@ void AndroidConfigurations::setConfig(const AndroidConfig &devConfigs)
emit m_instance->updated();
}
-AndroidDeviceInfo AndroidConfigurations::showDeviceDialog(ProjectExplorer::Project *project,
+AndroidDeviceInfo AndroidConfigurations::showDeviceDialog(Project *project,
int apiLevel, const QString &abi,
Options options)
{
@@ -1037,13 +1045,13 @@ AndroidDeviceInfo AndroidConfigurations::showDeviceDialog(ProjectExplorer::Proje
return AndroidDeviceInfo();
}
-void AndroidConfigurations::clearDefaultDevices(ProjectExplorer::Project *project)
+void AndroidConfigurations::clearDefaultDevices(Project *project)
{
if (m_instance->m_defaultDeviceForAbi.contains(project))
m_instance->m_defaultDeviceForAbi.remove(project);
}
-void AndroidConfigurations::setDefaultDevice(ProjectExplorer::Project *project, const QString &abi, const QString &serialNumber)
+void AndroidConfigurations::setDefaultDevice(Project *project, const QString &abi, const QString &serialNumber)
{
m_instance->m_defaultDeviceForAbi[project][abi] = serialNumber;
}
@@ -1116,7 +1124,7 @@ void AndroidConfigurations::updateAutomaticKitList()
continue;
// Update code for 3.0 beta, which shipped with a bug for the debugger settings
- ProjectExplorer::ToolChain *tc =ToolChainKitInformation::toolChain(k);
+ ToolChain *tc =ToolChainKitInformation::toolChain(k);
if (tc && Debugger::DebuggerKitInformation::debuggerCommand(k) != tc->suggestedDebugger()) {
Debugger::DebuggerItem debugger;
debugger.setCommand(tc->suggestedDebugger());
@@ -1158,7 +1166,7 @@ void AndroidConfigurations::updateAutomaticKitList()
foreach (QtSupport::BaseQtVersion *qt, qtVersions) {
Kit *newKit = new Kit;
newKit->setAutoDetected(true);
- newKit->setIconPath(Utils::FileName::fromString(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY_ICON)));
+ newKit->setIconPath(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);
@@ -1195,7 +1203,7 @@ void AndroidConfigurations::updateAutomaticKitList()
}
foreach (Kit *k, existingKits) {
- ProjectExplorer::ToolChain *tc = ToolChainKitInformation::toolChain(k);
+ ToolChain *tc = ToolChainKitInformation::toolChain(k);
QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k);
if (tc && tc->type() == QLatin1String(Constants::ANDROID_TOOLCHAIN_TYPE)
&& qtVersion && qtVersion->type() == QLatin1String(Constants::ANDROIDQT)) {
@@ -1311,7 +1319,7 @@ void AndroidConfigurations::load()
} else if (HostOsInfo::isMacHost()) {
QString javaHome = QLatin1String("/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home");
if (QFileInfo::exists(javaHome))
- m_config.setOpenJDKLocation(Utils::FileName::fromString(javaHome));
+ m_config.setOpenJDKLocation(FileName::fromString(javaHome));
} else if (HostOsInfo::isWindowsHost()) {
QSettings settings(QLatin1String("HKEY_LOCAL_MACHINE\\SOFTWARE\\Javasoft\\Java Development Kit"), QSettings::NativeFormat);
QStringList allVersions = settings.childGroups();
@@ -1358,7 +1366,7 @@ void AndroidConfigurations::updateAndroidDevice()
{
DeviceManager * const devMgr = DeviceManager::instance();
if (m_instance->m_config.adbToolPath().exists())
- devMgr->addDevice(IDevice::Ptr(new Internal::AndroidDevice));
+ devMgr->addDevice(IDevice::Ptr(new 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 0faaddc4af0..55152b81e13 100644
--- a/src/plugins/android/androidconfigurations.h
+++ b/src/plugins/android/androidconfigurations.h
@@ -146,7 +146,10 @@ public:
bool removeAVD(const QString &name) const;
QVector<AndroidDeviceInfo> connectedDevices(QString *error = 0) const;
+
+ QFuture<QVector<AndroidDeviceInfo> > androidVirtualDevicesFuture();
QVector<AndroidDeviceInfo> androidVirtualDevices() const;
+
QString startAVD(const QString &name, int apiLevel, QString cpuAbi) const;
bool startAVDAsync(const QString &avdName) const;
QString findAvd(int apiLevel, const QString &cpuAbi) const;
@@ -165,6 +168,7 @@ public:
SdkPlatform highestAndroidSdk() const;
private:
static CreateAvdInfo createAVDImpl(CreateAvdInfo info, Utils::FileName androidToolPath, Utils::Environment env);
+ static QVector<AndroidDeviceInfo> androidVirtualDevicesImpl(const Utils::FileName &androidTool, const Utils::Environment &environment);
Utils::FileName toolPath(ProjectExplorer::Abi::Architecture architecture, const QString &ndkToolChainVersion) const;
Utils::FileName openJDKBinPath() const;
diff --git a/src/plugins/android/androiddebugsupport.cpp b/src/plugins/android/androiddebugsupport.cpp
index fbe5a265d52..5679af60754 100644
--- a/src/plugins/android/androiddebugsupport.cpp
+++ b/src/plugins/android/androiddebugsupport.cpp
@@ -35,7 +35,6 @@
#include "androidmanager.h"
#include "androidqtsupport.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerkitinformation.h>
#include <debugger/debuggerrunconfigurationaspect.h>
#include <debugger/debuggerruncontrol.h>
@@ -90,9 +89,10 @@ RunControl *AndroidDebugSupport::createDebugRunControl(AndroidRunConfiguration *
params.startMode = AttachToRemoteServer;
params.displayName = AndroidManager::packageName(target);
params.remoteSetupNeeded = true;
+ params.runConfiguration = runConfig;
- Debugger::DebuggerRunConfigurationAspect *aspect
- = runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
+ DebuggerRunConfigurationAspect *aspect
+ = runConfig->extraAspect<DebuggerRunConfigurationAspect>();
if (aspect->useCppDebugger()) {
params.languages |= CppLanguage;
Kit *kit = target->kit();
@@ -120,7 +120,7 @@ RunControl *AndroidDebugSupport::createDebugRunControl(AndroidRunConfiguration *
}
DebuggerRunControl * const debuggerRunControl
- = DebuggerRunControlFactory::doCreate(params, runConfig, errorMessage);
+ = DebuggerRunControlFactory::doCreate(params, errorMessage);
new AndroidDebugSupport(runConfig, debuggerRunControl);
return debuggerRunControl;
}
@@ -128,7 +128,6 @@ RunControl *AndroidDebugSupport::createDebugRunControl(AndroidRunConfiguration *
AndroidDebugSupport::AndroidDebugSupport(AndroidRunConfiguration *runConfig,
DebuggerRunControl *runControl)
: QObject(runControl),
- m_engine(0),
m_runControl(runControl),
m_runner(new AndroidRunner(this, runConfig, runControl->runMode()))
{
@@ -137,26 +136,22 @@ AndroidDebugSupport::AndroidDebugSupport(AndroidRunConfiguration *runConfig,
connect(m_runControl, SIGNAL(finished()),
m_runner, SLOT(stop()));
- Debugger::DebuggerRunConfigurationAspect *aspect
- = runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
+ DebuggerRunConfigurationAspect *aspect
+ = runConfig->extraAspect<DebuggerRunConfigurationAspect>();
Q_ASSERT(aspect->useCppDebugger() || aspect->useQmlDebugger());
Q_UNUSED(aspect)
- m_engine = runControl->engine();
+ connect(m_runControl, &DebuggerRunControl::requestRemoteSetup,
+ m_runner, &AndroidRunner::start);
- if (m_engine) {
- connect(m_engine, &DebuggerEngine::requestRemoteSetup,
- m_runner, &AndroidRunner::start);
-
- // FIXME: Move signal to base class and generalize handling.
- connect(m_engine, SIGNAL(aboutToNotifyInferiorSetupOk()),
- m_runner, SLOT(handleRemoteDebuggerRunning()));
- }
+ // FIXME: Move signal to base class and generalize handling.
+ connect(m_runControl, &DebuggerRunControl::aboutToNotifyInferiorSetupOk,
+ m_runner, &AndroidRunner::handleRemoteDebuggerRunning);
connect(m_runner, &AndroidRunner::remoteServerRunning,
[this](const QByteArray &serverChannel, int pid) {
- QTC_ASSERT(m_engine, return);
- m_engine->notifyEngineRemoteServerRunning(serverChannel, pid);
+ QTC_ASSERT(m_runControl, return);
+ m_runControl->notifyEngineRemoteServerRunning(serverChannel, pid);
});
connect(m_runner, &AndroidRunner::remoteProcessStarted,
@@ -166,19 +161,19 @@ AndroidDebugSupport::AndroidDebugSupport(AndroidRunConfiguration *runConfig,
[this](const QString &errorMsg) {
QTC_ASSERT(m_runControl, return);
m_runControl->appendMessage(errorMsg, Utils::DebugFormat);
- QMetaObject::invokeMethod(m_engine, "notifyInferiorExited", Qt::QueuedConnection);
+ QMetaObject::invokeMethod(m_runControl, "notifyInferiorExited", Qt::QueuedConnection);
});
connect(m_runner, &AndroidRunner::remoteErrorOutput,
[this](const QByteArray &output) {
- QTC_ASSERT(m_engine, return);
- m_engine->showMessage(QString::fromUtf8(output), AppError);
+ QTC_ASSERT(m_runControl, return);
+ m_runControl->showMessage(QString::fromUtf8(output), AppError);
});
connect(m_runner, &AndroidRunner::remoteOutput,
[this](const QByteArray &output) {
- QTC_ASSERT(m_engine, return);
- m_engine->showMessage(QString::fromUtf8(output), AppOutput);
+ QTC_ASSERT(m_runControl, return);
+ m_runControl->showMessage(QString::fromUtf8(output), AppOutput);
});
}
@@ -186,12 +181,12 @@ void AndroidDebugSupport::handleRemoteProcessStarted(int gdbServerPort, int qmlP
{
disconnect(m_runner, &AndroidRunner::remoteProcessStarted,
this, &AndroidDebugSupport::handleRemoteProcessStarted);
- QTC_ASSERT(m_engine, return);
+ QTC_ASSERT(m_runControl, return);
RemoteSetupResult result;
result.success = true;
result.gdbServerPort = gdbServerPort;
result.qmlServerPort = qmlPort;
- m_engine->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
} // namespace Internal
diff --git a/src/plugins/android/androiddebugsupport.h b/src/plugins/android/androiddebugsupport.h
index 4682a1ae07e..8e90eadde1f 100644
--- a/src/plugins/android/androiddebugsupport.h
+++ b/src/plugins/android/androiddebugsupport.h
@@ -33,10 +33,7 @@
#include "androidrunconfiguration.h"
-namespace Debugger {
-class DebuggerEngine;
-class DebuggerRunControl;
-}
+namespace Debugger { class DebuggerRunControl; }
namespace ProjectExplorer { class RunControl; }
@@ -60,7 +57,6 @@ public:
private:
void handleRemoteProcessStarted(int gdbServerPort, int qmlPort);
- Debugger::DebuggerEngine *m_engine;
Debugger::DebuggerRunControl *m_runControl;
AndroidRunner * const m_runner;
};
diff --git a/src/plugins/android/androiddeployconfiguration.cpp b/src/plugins/android/androiddeployconfiguration.cpp
index fe4ce4c2dbd..b538bb511aa 100644
--- a/src/plugins/android/androiddeployconfiguration.cpp
+++ b/src/plugins/android/androiddeployconfiguration.cpp
@@ -135,10 +135,5 @@ QString AndroidDeployConfigurationFactory::displayNameForId(Core::Id id) const
return QString();
}
-bool AndroidDeployConfigurationFactory::canHandle(Target *parent) const
-{
- return AndroidManager::supportsAndroid(parent);
-}
-
} // namespace Internal
} // namespace Android
diff --git a/src/plugins/android/androiddeployconfiguration.h b/src/plugins/android/androiddeployconfiguration.h
index 34d0e1709de..1b972949c93 100644
--- a/src/plugins/android/androiddeployconfiguration.h
+++ b/src/plugins/android/androiddeployconfiguration.h
@@ -70,9 +70,6 @@ public:
QList<Core::Id> availableCreationIds(ProjectExplorer::Target *parent) const;
// used to translate the ids to names to display to the user
QString displayNameForId(Core::Id id) const;
-
-private:
- bool canHandle(ProjectExplorer::Target *parent) const;
};
} // namespace Internal
diff --git a/src/plugins/android/androiddeployqtstep.cpp b/src/plugins/android/androiddeployqtstep.cpp
index a17f5206c8f..1eac6078f3d 100644
--- a/src/plugins/android/androiddeployqtstep.cpp
+++ b/src/plugins/android/androiddeployqtstep.cpp
@@ -142,14 +142,14 @@ ProjectExplorer::BuildStep *AndroidDeployQtStepFactory::clone(ProjectExplorer::B
/////////////////
AndroidDeployQtStep::AndroidDeployQtStep(ProjectExplorer::BuildStepList *parent)
- : ProjectExplorer::AbstractProcessStep(parent, Id)
+ : ProjectExplorer::BuildStep(parent, Id)
{
ctor();
}
AndroidDeployQtStep::AndroidDeployQtStep(ProjectExplorer::BuildStepList *parent,
AndroidDeployQtStep *other)
- : ProjectExplorer::AbstractProcessStep(parent, other)
+ : ProjectExplorer::BuildStep(parent, other)
{
ctor();
}
@@ -157,11 +157,17 @@ AndroidDeployQtStep::AndroidDeployQtStep(ProjectExplorer::BuildStepList *parent,
void AndroidDeployQtStep::ctor()
{
m_uninstallPreviousPackage = QtSupport::QtKitInformation::qtVersion(target()->kit())->qtVersion() < QtSupport::QtVersionNumber(5, 4, 0);
- m_uninstallPreviousPackageTemp = false;
m_uninstallPreviousPackageRun = false;
//: AndroidDeployQtStep default display name
setDefaultDisplayName(tr("Deploy to Android device"));
+
+ connect(this, &AndroidDeployQtStep::askForUninstall,
+ this, &AndroidDeployQtStep::slotAskForUninstall,
+ Qt::BlockingQueuedConnection);
+
+ connect(this, &AndroidDeployQtStep::setSerialNumber,
+ this, &AndroidDeployQtStep::slotSetSerialNumber);
}
bool AndroidDeployQtStep::init()
@@ -208,12 +214,10 @@ bool AndroidDeployQtStep::init()
if (!version)
return false;
- m_uninstallPreviousPackageRun = m_uninstallPreviousPackage || m_uninstallPreviousPackageTemp;
- m_uninstallPreviousPackageTemp = false;
- if (m_uninstallPreviousPackageRun) {
+ m_uninstallPreviousPackageRun = m_uninstallPreviousPackage;
+ if (m_uninstallPreviousPackageRun)
m_manifestName = AndroidManager::manifestPath(target());
- }
- ProjectExplorer::ProcessParameters *pp = processParameters();
+
m_useAndroiddeployqt = version->qtVersion() >= QtSupport::QtVersionNumber(5, 4, 0);
if (m_useAndroiddeployqt) {
Utils::FileName tmp = AndroidManager::androidQtSupport(target())->androiddeployqtPath(target());
@@ -222,14 +226,12 @@ bool AndroidDeployQtStep::init()
return false;
}
-
- pp->setCommand(tmp.toString());
- const QString output(bc->buildDirectory().appendPath(QLatin1String(Constants::ANDROID_BUILDDIRECTORY)).toString());
- pp->setWorkingDirectory(output);
+ m_command = tmp.toString();
+ m_workingDirectory = bc->buildDirectory().appendPath(QLatin1String(Constants::ANDROID_BUILDDIRECTORY)).toString();
Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--verbose"));
Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--output"));
- Utils::QtcProcess::addArg(&m_androiddeployqtArgs, output);
+ Utils::QtcProcess::addArg(&m_androiddeployqtArgs, m_workingDirectory);
Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--no-build"));
Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--input"));
tmp = AndroidManager::androidQtSupport(target())->androiddeployJsonPath(target());
@@ -239,11 +241,6 @@ bool AndroidDeployQtStep::init()
}
Utils::QtcProcess::addArg(&m_androiddeployqtArgs, tmp.toString());
- if (m_uninstallPreviousPackageRun)
- Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--install"));
- else
- Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--reinstall"));
-
Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--deployment"));
switch (androidBuildApkStep->deployAction()) {
case AndroidBuildApkStep::MinistroDeployment:
@@ -270,82 +267,169 @@ bool AndroidDeployQtStep::init()
}
} else {
m_uninstallPreviousPackageRun = true;
- pp->setCommand(AndroidConfigurations::currentConfig().adbToolPath().toString());
+ m_command = AndroidConfigurations::currentConfig().adbToolPath().toString();
m_apkPath = AndroidManager::androidQtSupport(target())->apkPath(target()).toString();
- pp->setWorkingDirectory(bc->buildDirectory().toString());
+ m_workingDirectory = bc->buildDirectory().toString();
}
- pp->setMacroExpander(bc->macroExpander());
- Utils::Environment env = bc->environment();
- pp->setEnvironment(env);
+ m_environment = bc->environment();
+
m_buildDirectory = bc->buildDirectory().toString();
- bool result = AbstractProcessStep::init();
- if (!result)
- return false;
+
+ m_adbPath = AndroidConfigurations::currentConfig().adbToolPath().toString();
if (AndroidConfigurations::currentConfig().findAvd(m_deviceAPILevel, m_targetArch).isEmpty())
AndroidConfigurations::currentConfig().startAVDAsync(m_avdName);
return true;
}
-void AndroidDeployQtStep::run(QFutureInterface<bool> &fi)
+AndroidDeployQtStep::DeployResult AndroidDeployQtStep::runDeploy(QFutureInterface<bool> &fi)
{
m_installOk = true;
- if (!m_avdName.isEmpty()) {
- QString serialNumber = AndroidConfigurations::currentConfig().waitForAvd(m_deviceAPILevel, m_targetArch, fi);
- if (serialNumber.isEmpty()) {
- fi.reportResult(false);
- emit finished();
- return;
- }
- m_serialNumber = serialNumber;
- AndroidManager::setDeviceSerialNumber(target(), serialNumber);
- }
-
- ProjectExplorer::ProcessParameters *pp = processParameters();
+ QString args;
if (m_useAndroiddeployqt) {
+ args = m_androiddeployqtArgs;
+ if (m_uninstallPreviousPackageRun)
+ Utils::QtcProcess::addArg(&args, QLatin1String("--install"));
+ else
+ Utils::QtcProcess::addArg(&args, QLatin1String("--reinstall"));
+
if (!m_serialNumber.isEmpty() && !m_serialNumber.startsWith(QLatin1String("????"))) {
- Utils::QtcProcess::addArg(&m_androiddeployqtArgs, QLatin1String("--device"));
- Utils::QtcProcess::addArg(&m_androiddeployqtArgs, m_serialNumber);
+ Utils::QtcProcess::addArg(&args, QLatin1String("--device"));
+ Utils::QtcProcess::addArg(&args, m_serialNumber);
}
- pp->setArguments(m_androiddeployqtArgs);
} else {
if (m_uninstallPreviousPackageRun) {
const QString packageName = AndroidManager::packageName(m_manifestName);
- if (packageName.isEmpty()){
+ if (packageName.isEmpty()) {
emit addOutput(tr("Cannot find the package name."), ErrorOutput);
- fi.reportResult(false);
- emit finished();
- return;
+ return Failure;
}
emit addOutput(tr("Uninstall previous package %1.").arg(packageName), MessageOutput);
- runCommand(AndroidConfigurations::currentConfig().adbToolPath().toString(),
+ runCommand(m_adbPath,
AndroidDeviceInfo::adbSelector(m_serialNumber)
<< QLatin1String("uninstall") << packageName);
}
- QString args;
foreach (const QString &arg, AndroidDeviceInfo::adbSelector(m_serialNumber))
Utils::QtcProcess::addArg(&args, arg);
Utils::QtcProcess::addArg(&args, QLatin1String("install"));
Utils::QtcProcess::addArg(&args, QLatin1String("-r"));
Utils::QtcProcess::addArg(&args, m_apkPath);
- pp->setArguments(args);
}
- pp->resolveAll();
- AbstractProcessStep::run(fi);
+ m_process = new Utils::QtcProcess;
+ m_process->setCommand(m_command, args);
+ m_process->setWorkingDirectory(m_workingDirectory);
+ m_process->setEnvironment(m_environment);
+
+ if (Utils::HostOsInfo::isWindowsHost())
+ m_process->setUseCtrlCStub(true);
+
+ connect(m_process, &Utils::QtcProcess::readyReadStandardOutput,
+ this, &AndroidDeployQtStep::processReadyReadStdOutput, Qt::DirectConnection);
+ connect(m_process, &Utils::QtcProcess::readyReadStandardError,
+ this, &AndroidDeployQtStep::processReadyReadStdError, Qt::DirectConnection);
+
+ m_process->start();
+
+ emit addOutput(tr("Starting: \"%1\" %2")
+ .arg(QDir::toNativeSeparators(m_command), args),
+ BuildStep::MessageOutput);
+
+ while (!m_process->waitForFinished(200)) {
+ if (fi.isCanceled()) {
+ m_process->kill();
+ m_process->waitForFinished();
+ }
+ }
+
+ QString line = QString::fromLocal8Bit(m_process->readAllStandardError());
+ if (!line.isEmpty())
+ stdError(line);
+
+ line = QString::fromLocal8Bit(m_process->readAllStandardOutput());
+ if (!line.isEmpty())
+ stdOutput(line);
+
+ QProcess::ExitStatus exitStatus = m_process->exitStatus();
+ int exitCode = m_process->exitCode();
+ delete m_process;
+ m_process = 0;
+
+ if (exitStatus == QProcess::NormalExit && exitCode == 0) {
+ emit addOutput(tr("The process \"%1\" exited normally.").arg(m_command),
+ BuildStep::MessageOutput);
+ } else if (exitStatus == QProcess::NormalExit) {
+ emit addOutput(tr("The process \"%1\" exited with code %2.")
+ .arg(m_command, QString::number(exitCode)),
+ BuildStep::ErrorMessageOutput);
+ } else {
+ emit addOutput(tr("The process \"%1\" crashed.").arg(m_command), BuildStep::ErrorMessageOutput);
+ }
+
+ if (exitCode == 0 && exitStatus == QProcess::NormalExit) {
+ if (!m_installOk) {
+ if (!m_uninstallPreviousPackageRun)
+ return AskUinstall;
+ else
+ return Failure;
+ }
+ return Success;
+ }
+ return Failure;
+}
+
+void AndroidDeployQtStep::slotAskForUninstall()
+{
+ int button = QMessageBox::critical(0, tr("Install failed"),
+ tr("Another application with the same package id but signed with "
+ "different certificate already exists.\n"
+ "Do you want to uninstall the existing package?"),
+ QMessageBox::Yes, QMessageBox::No);
+ m_askForUinstall = button == QMessageBox::Yes;
+}
+
+void AndroidDeployQtStep::slotSetSerialNumber(const QString &serialNumber)
+{
+ AndroidManager::setDeviceSerialNumber(target(), serialNumber);
+}
+
+void AndroidDeployQtStep::run(QFutureInterface<bool> &fi)
+{
+ if (!m_avdName.isEmpty()) {
+ QString serialNumber = AndroidConfigurations::currentConfig().waitForAvd(m_deviceAPILevel, m_targetArch, fi);
+ if (serialNumber.isEmpty()) {
+ fi.reportResult(false);
+ emit finished();
+ return;
+ }
+ m_serialNumber = serialNumber;
+ emit setSerialNumber(serialNumber);
+ }
+
+ DeployResult returnValue = runDeploy(fi);
+ if (returnValue == AskUinstall) {
+ emit askForUninstall();
+ if (m_askForUinstall) {
+ m_uninstallPreviousPackageRun = true;
+ returnValue = runDeploy(fi);
+ }
+ }
emit addOutput(tr("Pulling files necessary for debugging."), MessageOutput);
- runCommand(AndroidConfigurations::currentConfig().adbToolPath().toString(),
+ runCommand(m_adbPath,
AndroidDeviceInfo::adbSelector(m_serialNumber)
<< QLatin1String("pull") << QLatin1String("/system/bin/app_process")
<< QString::fromLatin1("%1/app_process").arg(m_buildDirectory));
- runCommand(AndroidConfigurations::currentConfig().adbToolPath().toString(),
+ runCommand(m_adbPath,
AndroidDeviceInfo::adbSelector(m_serialNumber) << QLatin1String("pull")
<< QLatin1String("/system/lib/libc.so")
<< QString::fromLatin1("%1/libc.so").arg(m_buildDirectory));
+
+ fi.reportResult(returnValue == Success ? true : false);
+ fi.reportFinished();
}
void AndroidDeployQtStep::runCommand(const QString &program, const QStringList &arguments)
@@ -361,7 +445,7 @@ void AndroidDeployQtStep::runCommand(const QString &program, const QStringList &
if (!buildProc.waitForFinished(2 * 60 * 1000)
|| buildProc.error() != QProcess::UnknownError
|| buildProc.exitCode() != 0) {
- QString mainMessage = tr("Packaging Error: Command \"%1 %2\" failed.")
+ QString mainMessage = tr("Packaging error: Command \"%1 %2\" failed.")
.arg(program).arg(arguments.join(QLatin1Char(' ')));
if (buildProc.error() != QProcess::UnknownError)
mainMessage += QLatin1Char(' ') + tr("Reason: %1").arg(buildProc.errorString());
@@ -376,32 +460,36 @@ ProjectExplorer::BuildStepConfigWidget *AndroidDeployQtStep::createConfigWidget(
return new AndroidDeployQtWidget(this);
}
-void AndroidDeployQtStep::stdOutput(const QString &line)
+void AndroidDeployQtStep::processReadyReadStdOutput()
{
- if (line.contains(InstallFailedInconsistentCertificatesString))
- m_installOk = false;
- AbstractProcessStep::stdOutput(line);
+ m_process->setReadChannel(QProcess::StandardOutput);
+ while (m_process->canReadLine()) {
+ QString line = QString::fromLocal8Bit(m_process->readLine());
+ stdOutput(line);
+ }
}
-void AndroidDeployQtStep::stdError(const QString &line)
+void AndroidDeployQtStep::stdOutput(const QString &line)
{
if (line.contains(InstallFailedInconsistentCertificatesString))
m_installOk = false;
- AbstractProcessStep::stdError(line);
+ emit addOutput(line, BuildStep::NormalOutput, BuildStep::DontAppendNewline);
}
-bool AndroidDeployQtStep::processSucceeded(int exitCode, QProcess::ExitStatus status)
+void AndroidDeployQtStep::processReadyReadStdError()
{
- if (!m_installOk && !m_uninstallPreviousPackageRun &&
- QMessageBox::critical(0, tr("Install failed"),
- tr("Another application with the same package id but signed with "
- "different ceritificate already exists.\n"
- "Do you want to uninstall the existing package next time?"),
- QMessageBox::Yes, QMessageBox::No)
- == QMessageBox::Yes) {
- m_uninstallPreviousPackageTemp = true;
+ m_process->setReadChannel(QProcess::StandardError);
+ while (m_process->canReadLine()) {
+ QString line = QString::fromLocal8Bit(m_process->readLine());
+ stdError(line);
}
- return m_installOk && AbstractProcessStep::processSucceeded(exitCode, status);
+}
+
+void AndroidDeployQtStep::stdError(const QString &line)
+{
+ if (line.contains(InstallFailedInconsistentCertificatesString))
+ m_installOk = false;
+ emit addOutput(line, BuildStep::ErrorOutput, BuildStep::DontAppendNewline);
}
bool AndroidDeployQtStep::fromMap(const QVariantMap &map)
@@ -424,7 +512,7 @@ void AndroidDeployQtStep::setUninstallPreviousPackage(bool uninstall)
bool AndroidDeployQtStep::runInGuiThread() const
{
- return true;
+ return false;
}
AndroidDeployQtStep::UninstallType AndroidDeployQtStep::uninstallPreviousPackage()
diff --git a/src/plugins/android/androiddeployqtstep.h b/src/plugins/android/androiddeployqtstep.h
index 844029862b1..00a675ebd39 100644
--- a/src/plugins/android/androiddeployqtstep.h
+++ b/src/plugins/android/androiddeployqtstep.h
@@ -38,6 +38,10 @@
#include <projectexplorer/abstractprocessstep.h>
#include <qtsupport/baseqtversion.h>
+namespace Utils {
+class QtcProcess;
+}
+
QT_BEGIN_NAMESPACE
class QAbstractItemModel;
QT_END_NAMESPACE
@@ -66,7 +70,7 @@ public:
ProjectExplorer::BuildStep *product);
};
-class AndroidDeployQtStep : public ProjectExplorer::AbstractProcessStep
+class AndroidDeployQtStep : public ProjectExplorer::BuildStep
{
Q_OBJECT
friend class AndroidDeployQtStepFactory;
@@ -89,6 +93,10 @@ public:
public slots:
void setUninstallPreviousPackage(bool uninstall);
+signals:
+ void askForUninstall();
+ void setSerialNumber(const QString &serialNumber);
+
private:
AndroidDeployQtStep(ProjectExplorer::BuildStepList *bc,
AndroidDeployQtStep *other);
@@ -97,11 +105,21 @@ private:
bool init();
void run(QFutureInterface<bool> &fi);
+ enum DeployResult { Success, Failure, AskUinstall };
+ DeployResult runDeploy(QFutureInterface<bool> &fi);
+ void slotAskForUninstall();
+ void slotSetSerialNumber(const QString &serialNumber);
+
ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
bool immutable() const { return true; }
+
+ void processReadyReadStdOutput();
void stdOutput(const QString &line);
+ void processReadyReadStdError();
void stdError(const QString &line);
- virtual bool processSucceeded(int exitCode, QProcess::ExitStatus status);
+
+ void slotProcessFinished(int, QProcess::ExitStatus);
+ void processFinished(int exitCode, QProcess::ExitStatus status);
Utils::FileName m_manifestName;
QString m_serialNumber;
@@ -112,13 +130,17 @@ private:
QString m_targetArch;
int m_deviceAPILevel;
bool m_uninstallPreviousPackage;
- bool m_uninstallPreviousPackageTemp;
bool m_uninstallPreviousPackageRun;
static const Core::Id Id;
bool m_installOk;
bool m_useAndroiddeployqt;
- AndroidBuildApkStep::AndroidDeployAction m_deployAction;
QString m_androiddeployqtArgs;
+ QString m_adbPath;
+ QString m_command;
+ QString m_workingDirectory;
+ Utils::Environment m_environment;
+ Utils::QtcProcess *m_process;
+ bool m_askForUinstall;
};
}
diff --git a/src/plugins/android/androidmanifestdocument.cpp b/src/plugins/android/androidmanifestdocument.cpp
index 2489b10f379..64696959d85 100644
--- a/src/plugins/android/androidmanifestdocument.cpp
+++ b/src/plugins/android/androidmanifestdocument.cpp
@@ -56,14 +56,12 @@ bool AndroidManifestDocument::save(QString *errorString, const QString &fileName
QString AndroidManifestDocument::defaultPath() const
{
- QFileInfo fi(filePath());
- return fi.absolutePath();
+ return filePath().toFileInfo().absolutePath();
}
QString AndroidManifestDocument::suggestedFileName() const
{
- QFileInfo fi(filePath());
- return fi.fileName();
+ return filePath().fileName();
}
bool AndroidManifestDocument::isModified() const
diff --git a/src/plugins/android/androidmanifesteditor.cpp b/src/plugins/android/androidmanifesteditor.cpp
index ed4a4c0a173..8d7fe8c4759 100644
--- a/src/plugins/android/androidmanifesteditor.cpp
+++ b/src/plugins/android/androidmanifesteditor.cpp
@@ -42,7 +42,7 @@
using namespace Android;
using namespace Internal;
-Android::Internal::AndroidManifestEditor::AndroidManifestEditor(AndroidManifestEditorWidget *editorWidget)
+AndroidManifestEditor::AndroidManifestEditor(AndroidManifestEditorWidget *editorWidget)
: Core::IEditor(editorWidget), m_toolBar(0)
{
m_toolBar = new QToolBar(editorWidget);
diff --git a/src/plugins/android/androidmanifesteditorwidget.cpp b/src/plugins/android/androidmanifesteditorwidget.cpp
index f6f0384d48d..8f27df9573b 100644
--- a/src/plugins/android/androidmanifesteditorwidget.cpp
+++ b/src/plugins/android/androidmanifesteditorwidget.cpp
@@ -476,12 +476,12 @@ bool AndroidManifestEditorWidget::eventFilter(QObject *obj, QEvent *event)
void AndroidManifestEditorWidget::updateTargetComboBox()
{
- const QString docPath(m_textEditorWidget->textDocument()->filePath());
- ProjectExplorer::Project *project = androidProject(docPath);
+ const QString docPath(m_textEditorWidget->textDocument()->filePath().toString());
+ Project *project = androidProject(docPath);
QStringList items;
if (project) {
- ProjectExplorer::Kit *kit = project->activeTarget()->kit();
- if (ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit) == Constants::ANDROID_DEVICE_TYPE)
+ Kit *kit = project->activeTarget()->kit();
+ if (DeviceTypeKitInformation::deviceTypeId(kit) == Constants::ANDROID_DEVICE_TYPE)
items = AndroidManager::androidQtSupport(project->activeTarget())->projectTargetApplications(project->activeTarget());
}
@@ -577,7 +577,7 @@ void AndroidManifestEditorWidget::preSave()
syncToEditor();
if (m_setAppName && m_appNameInStringsXml) {
- QString baseDir = QFileInfo(m_textEditorWidget->textDocument()->filePath()).absolutePath();
+ QString baseDir = m_textEditorWidget->textDocument()->filePath().toFileInfo().absolutePath();
QString fileName = baseDir + QLatin1String("/res/values/strings.xml");
QFile f(fileName);
if (f.open(QIODevice::ReadOnly)) {
@@ -601,7 +601,7 @@ void AndroidManifestEditorWidget::preSave()
m_setAppName = false;
}
- QString baseDir = QFileInfo(m_textEditorWidget->textDocument()->filePath()).absolutePath();
+ QString baseDir = m_textEditorWidget->textDocument()->filePath().toFileInfo().absolutePath();
if (!m_lIconPath.isEmpty()) {
copyIcon(LowDPI, baseDir, m_lIconPath);
m_lIconPath.clear();
@@ -646,7 +646,8 @@ bool AndroidManifestEditorWidget::syncToWidgets()
return false;
}
-bool AndroidManifestEditorWidget::checkDocument(QDomDocument doc, QString *errorMessage, int *errorLine, int *errorColumn)
+bool AndroidManifestEditorWidget::checkDocument(const QDomDocument &doc, QString *errorMessage,
+ int *errorLine, int *errorColumn)
{
QDomElement manifest = doc.documentElement();
if (manifest.tagName() != QLatin1String("manifest")) {
@@ -695,7 +696,7 @@ void AndroidManifestEditorWidget::updateInfoBar()
void AndroidManifestEditorWidget::updateSdkVersions()
{
- const QString docPath(m_textEditorWidget->textDocument()->filePath());
+ const QString docPath(m_textEditorWidget->textDocument()->filePath().toString());
QPair<int, int> apiLevels = AndroidManager::apiLevelRange();
for (int i = apiLevels.first; i < apiLevels.second + 1; ++i)
m_androidMinSdkVersion->addItem(tr("API %1: %2")
@@ -766,7 +767,7 @@ void AndroidManifestEditorWidget::syncToWidgets(const QDomDocument &doc)
setApiLevel(m_androidMinSdkVersion, usesSdkElement, QLatin1String("android:minSdkVersion"));
setApiLevel(m_androidTargetSdkVersion, usesSdkElement, QLatin1String("android:targetSdkVersion"));
- QString baseDir = QFileInfo(m_textEditorWidget->textDocument()->filePath()).absolutePath();
+ QString baseDir = m_textEditorWidget->textDocument()->filePath().toFileInfo().absolutePath();
QString fileName = baseDir + QLatin1String("/res/values/strings.xml");
QDomElement applicationElement = manifest.firstChildElement(QLatin1String("application"));
@@ -894,7 +895,7 @@ void AndroidManifestEditorWidget::syncToEditor()
namespace {
QXmlStreamAttributes modifyXmlStreamAttributes(const QXmlStreamAttributes &input, const QStringList &keys,
- const QStringList values, const QStringList &remove = QStringList())
+ const QStringList &values, const QStringList &remove = QStringList())
{
Q_ASSERT(keys.size() == values.size());
QXmlStreamAttributes result;
@@ -1158,7 +1159,9 @@ void AndroidManifestEditorWidget::parseUsesSdk(QXmlStreamReader &reader, QXmlStr
}
}
-QString AndroidManifestEditorWidget::parseUsesPermission(QXmlStreamReader &reader, QXmlStreamWriter &writer, const QSet<QString> permissions)
+QString AndroidManifestEditorWidget::parseUsesPermission(QXmlStreamReader &reader,
+ QXmlStreamWriter &writer,
+ const QSet<QString> &permissions)
{
Q_ASSERT(reader.isStartElement());
@@ -1374,7 +1377,7 @@ QModelIndex PermissionsModel::addPermission(const QString &permission)
return index(idx);
}
-bool PermissionsModel::updatePermission(QModelIndex index, const QString &permission)
+bool PermissionsModel::updatePermission(const QModelIndex &index, const QString &permission)
{
if (!index.isValid())
return false;
diff --git a/src/plugins/android/androidmanifesteditorwidget.h b/src/plugins/android/androidmanifesteditorwidget.h
index 0222d42062a..fcce653d051 100644
--- a/src/plugins/android/androidmanifesteditorwidget.h
+++ b/src/plugins/android/androidmanifesteditorwidget.h
@@ -69,7 +69,7 @@ public:
void setPermissions(const QStringList &permissions);
const QStringList &permissions();
QModelIndex addPermission(const QString &permission);
- bool updatePermission(QModelIndex index, const QString &permission);
+ bool updatePermission(const QModelIndex &index, const QString &permission);
void removePermission(int index);
QVariant data(const QModelIndex &index, int role) const;
@@ -137,7 +137,8 @@ private:
void syncToWidgets(const QDomDocument &doc);
void syncToEditor();
- bool checkDocument(QDomDocument doc, QString *errorMessage, int *errorLine, int *errorColumn);
+ bool checkDocument(const QDomDocument &doc, QString *errorMessage,
+ int *errorLine, int *errorColumn);
enum IconDPI { LowDPI, MediumDPI, HighDPI };
QIcon icon(const QString &baseDir, IconDPI dpi);
QString iconPath(const QString &baseDir, IconDPI dpi);
@@ -152,7 +153,9 @@ private:
void parseActivity(QXmlStreamReader &reader, QXmlStreamWriter &writer);
bool parseMetaData(QXmlStreamReader &reader, QXmlStreamWriter &writer);
void parseUsesSdk(QXmlStreamReader &reader, QXmlStreamWriter &writer);
- QString parseUsesPermission(QXmlStreamReader &reader, QXmlStreamWriter &writer, const QSet<QString> permissions);
+ QString parseUsesPermission(QXmlStreamReader &reader,
+ QXmlStreamWriter &writer,
+ const QSet<QString> &permissions);
QString parseComment(QXmlStreamReader &reader, QXmlStreamWriter &writer);
void parseUnknownElement(QXmlStreamReader &reader, QXmlStreamWriter &writer);
diff --git a/src/plugins/android/androidpotentialkit.cpp b/src/plugins/android/androidpotentialkit.cpp
index 7b5d97695e9..0008a835a93 100644
--- a/src/plugins/android/androidpotentialkit.cpp
+++ b/src/plugins/android/androidpotentialkit.cpp
@@ -53,7 +53,7 @@ QString AndroidPotentialKit::displayName() const
return tr("Configure Android...");
}
-void Android::Internal::AndroidPotentialKit::executeFromMenu()
+void AndroidPotentialKit::executeFromMenu()
{
Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
Constants::ANDROID_SETTINGS_ID);
diff --git a/src/plugins/android/androidqtsupport.h b/src/plugins/android/androidqtsupport.h
index 75e641adc70..b7ee4b52cde 100644
--- a/src/plugins/android/androidqtsupport.h
+++ b/src/plugins/android/androidqtsupport.h
@@ -69,7 +69,7 @@ public:
virtual void resetBuild(const ProjectExplorer::Target *target) = 0;
};
-} // namespace QtSupport
+} // namespace Android
#endif // ANDROIDSUPPORT_H
diff --git a/src/plugins/android/androidqtversion.cpp b/src/plugins/android/androidqtversion.cpp
index 4e2253ea251..45bc0549c21 100644
--- a/src/plugins/android/androidqtversion.cpp
+++ b/src/plugins/android/androidqtversion.cpp
@@ -43,7 +43,7 @@
#include <projectexplorer/target.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <proparser/profileevaluator.h>
@@ -88,26 +88,26 @@ QString AndroidQtVersion::invalidReason() const
return tmp;
}
-QList<ProjectExplorer::Abi> AndroidQtVersion::detectQtAbis() const
+QList<Abi> AndroidQtVersion::detectQtAbis() const
{
- QList<ProjectExplorer::Abi> abis = qtAbisFromLibrary(qtCorePaths(versionInfo(), qtVersionString()));
+ QList<Abi> abis = qtAbisFromLibrary(qtCorePaths(versionInfo(), qtVersionString()));
for (int i = 0; i < abis.count(); ++i) {
abis[i] = Abi(abis.at(i).architecture(),
abis.at(i).os(),
- ProjectExplorer::Abi::AndroidLinuxFlavor,
+ Abi::AndroidLinuxFlavor,
abis.at(i).binaryFormat(),
abis.at(i).wordWidth());
}
return abis;
}
-void AndroidQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const
+void AndroidQtVersion::addToEnvironment(const Kit *k, Utils::Environment &env) const
{
// this env vars are used by qmake mkspecs to generate makefiles (check QTDIR/mkspecs/android-g++/qmake.conf for more info)
env.set(QLatin1String("ANDROID_NDK_HOST"), AndroidConfigurations::currentConfig().toolchainHost());
env.set(QLatin1String("ANDROID_NDK_ROOT"), AndroidConfigurations::currentConfig().ndkLocation().toUserOutput());
- Project *project = ProjectExplorerPlugin::instance()->currentProject();
+ Project *project = ProjectTree::currentProject();
if (!project || !project->activeTarget()
|| QtSupport::QtKitInformation::qtVersion(k)->type() != QLatin1String(Constants::ANDROIDQT))
return;
diff --git a/src/plugins/android/androidrunfactories.cpp b/src/plugins/android/androidrunfactories.cpp
index 115f9d511c2..f5661f51f22 100644
--- a/src/plugins/android/androidrunfactories.cpp
+++ b/src/plugins/android/androidrunfactories.cpp
@@ -56,8 +56,7 @@ AndroidRunControlFactory::AndroidRunControlFactory(QObject *parent)
{
}
-bool AndroidRunControlFactory::canRun(RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const
+bool AndroidRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
if (mode != NormalRunMode && mode != DebugRunMode && mode != QmlProfilerRunMode)
return false;
@@ -65,7 +64,7 @@ bool AndroidRunControlFactory::canRun(RunConfiguration *runConfiguration,
}
RunControl *AndroidRunControlFactory::create(RunConfiguration *runConfig,
- ProjectExplorer::RunMode mode, QString *errorMessage)
+ RunMode mode, QString *errorMessage)
{
Q_ASSERT(canRun(runConfig, mode));
AndroidRunConfiguration *rc = qobject_cast<AndroidRunConfiguration *>(runConfig);
@@ -81,8 +80,8 @@ RunControl *AndroidRunControlFactory::create(RunConfiguration *runConfig,
case DebugRunModeWithBreakOnMain:
case CallgrindRunMode:
case MemcheckRunMode:
+ case MemcheckWithGdbRunMode:
case ClangStaticAnalyzerMode:
- default:
QTC_CHECK(false); // The other run modes are not supported
}
return 0;
diff --git a/src/plugins/android/androidsettingswidget.cpp b/src/plugins/android/androidsettingswidget.cpp
index 108e3855089..af79f85f7af 100644
--- a/src/plugins/android/androidsettingswidget.cpp
+++ b/src/plugins/android/androidsettingswidget.cpp
@@ -170,7 +170,6 @@ AndroidSettingsWidget::AndroidSettingsWidget(QWidget *parent)
m_ui->DataPartitionSizeSpinBox->setValue(m_androidConfig.partitionSize());
m_ui->CreateKitCheckBox->setChecked(m_androidConfig.automaticKitCreation());
m_ui->AVDTableView->setModel(&m_AVDModel);
- m_AVDModel.setAvdList(m_androidConfig.androidVirtualDevices());
m_ui->AVDTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
m_ui->AVDTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
@@ -180,11 +179,20 @@ AndroidSettingsWidget::AndroidSettingsWidget(QWidget *parent)
connect(m_ui->gdbWarningLabel, SIGNAL(linkActivated(QString)),
this, SLOT(showGdbWarningDialog()));
+ connect(&m_virtualDevicesWatcher, SIGNAL(finished()),
+ this, SLOT(updateAvds()));
+
check(All);
applyToUi(All);
connect(&m_futureWatcher, SIGNAL(finished()),
this, SLOT(avdAdded()));
+
+ connect(m_ui->NDKLocationPathChooser, SIGNAL(changed(QString)), this, SLOT(ndkLocationEditingFinished()));
+ connect(m_ui->SDKLocationPathChooser, SIGNAL(changed(QString)), this, SLOT(sdkLocationEditingFinished()));
+ connect(m_ui->AntLocationPathChooser, SIGNAL(changed(QString)), this, SLOT(antLocationEditingFinished()));
+ connect(m_ui->OpenJDKLocationPathChooser, SIGNAL(changed(QString)), this, SLOT(openJDKLocationEditingFinished()));
+
}
AndroidSettingsWidget::~AndroidSettingsWidget()
@@ -397,10 +405,41 @@ void AndroidSettingsWidget::applyToUi(AndroidSettingsWidget::Mode mode)
m_ui->AVDManagerFrame->setEnabled(false);
}
- m_AVDModel.setAvdList(m_androidConfig.androidVirtualDevices());
+ startUpdateAvd();
}
}
+void AndroidSettingsWidget::disableAvdControls()
+{
+ m_ui->AVDAddPushButton->setEnabled(false);
+ m_ui->AVDTableView->setEnabled(false);
+ m_ui->AVDRemovePushButton->setEnabled(false);
+ m_ui->AVDStartPushButton->setEnabled(false);
+}
+
+void AndroidSettingsWidget::enableAvdControls()
+{
+ m_ui->AVDTableView->setEnabled(true);
+ m_ui->AVDAddPushButton->setEnabled(true);
+ avdActivated(m_ui->AVDTableView->currentIndex());
+}
+
+void AndroidSettingsWidget::startUpdateAvd()
+{
+ disableAvdControls();
+ m_virtualDevicesWatcher.setFuture(m_androidConfig.androidVirtualDevicesFuture());
+}
+
+void AndroidSettingsWidget::updateAvds()
+{
+ m_AVDModel.setAvdList(m_virtualDevicesWatcher.result());
+ if (!m_lastAddedAvd.isEmpty()) {
+ m_ui->AVDTableView->setCurrentIndex(m_AVDModel.indexForAvdName(m_lastAddedAvd));
+ m_lastAddedAvd.clear();
+ }
+ enableAvdControls();
+}
+
bool AndroidSettingsWidget::sdkLocationIsValid() const
{
Utils::FileName androidExe = m_androidConfig.sdkLocation();
@@ -519,11 +558,11 @@ void AndroidSettingsWidget::openOpenJDKDownloadUrl()
void AndroidSettingsWidget::addAVD()
{
- m_ui->AVDAddPushButton->setEnabled(false);
+ disableAvdControls();
AndroidConfig::CreateAvdInfo info = m_androidConfig.gatherCreateAVDInfo(this);
if (info.target.isEmpty()) {
- m_ui->AVDAddPushButton->setEnabled(true);
+ enableAvdControls();
return;
}
@@ -532,29 +571,31 @@ void AndroidSettingsWidget::addAVD()
void AndroidSettingsWidget::avdAdded()
{
- m_ui->AVDAddPushButton->setEnabled(true);
AndroidConfig::CreateAvdInfo info = m_futureWatcher.result();
if (!info.error.isEmpty()) {
+ enableAvdControls();
QMessageBox::critical(this, QApplication::translate("AndroidConfig", "Error Creating AVD"), info.error);
return;
}
- m_AVDModel.setAvdList(m_androidConfig.androidVirtualDevices());
- m_ui->AVDTableView->setCurrentIndex(m_AVDModel.indexForAvdName(info.name));
+ startUpdateAvd();
+ m_lastAddedAvd = info.name;
}
void AndroidSettingsWidget::removeAVD()
{
+ disableAvdControls();
QString avdName = m_AVDModel.avdName(m_ui->AVDTableView->currentIndex());
if (QMessageBox::question(this, tr("Remove Android Virtual Device"),
tr("Remove device \"%1\"? This cannot be undone.").arg(avdName),
QMessageBox::Yes | QMessageBox::No)
- == QMessageBox::No)
+ == QMessageBox::No) {
+ enableAvdControls();
return;
+ }
m_androidConfig.removeAVD(avdName);
- m_AVDModel.setAvdList(m_androidConfig.androidVirtualDevices());
- avdActivated(m_ui->AVDTableView->currentIndex());
+ startUpdateAvd();
}
void AndroidSettingsWidget::startAVD()
@@ -562,7 +603,7 @@ void AndroidSettingsWidget::startAVD()
m_androidConfig.startAVDAsync(m_AVDModel.avdName(m_ui->AVDTableView->currentIndex()));
}
-void AndroidSettingsWidget::avdActivated(QModelIndex index)
+void AndroidSettingsWidget::avdActivated(const QModelIndex &index)
{
m_ui->AVDRemovePushButton->setEnabled(index.isValid());
m_ui->AVDStartPushButton->setEnabled(index.isValid());
diff --git a/src/plugins/android/androidsettingswidget.h b/src/plugins/android/androidsettingswidget.h
index 47220daf41f..d4679c5aebd 100644
--- a/src/plugins/android/androidsettingswidget.h
+++ b/src/plugins/android/androidsettingswidget.h
@@ -88,7 +88,7 @@ private slots:
void avdAdded();
void removeAVD();
void startAVD();
- void avdActivated(QModelIndex);
+ void avdActivated(const QModelIndex &);
void dataPartitionSizeEditingFinished();
void manageAVD();
void createKitToggled();
@@ -96,6 +96,7 @@ private slots:
void checkGdbFinished();
void showGdbWarningDialog();
+ void updateAvds();
private:
enum Mode { Sdk = 1, Ndk = 2, Java = 4, All = Sdk | Ndk | Java };
@@ -104,6 +105,9 @@ private:
void applyToUi(Mode mode);
bool sdkLocationIsValid() const;
bool sdkPlatformToolsInstalled() const;
+ void startUpdateAvd();
+ void enableAvdControls();
+ void disableAvdControls();
State m_sdkState;
State m_ndkState;
@@ -118,6 +122,9 @@ private:
QFutureWatcher<AndroidConfig::CreateAvdInfo> m_futureWatcher;
QFutureWatcher<QPair<QStringList, bool>> m_checkGdbWatcher;
QStringList m_gdbCheckPaths;
+
+ QFutureWatcher<QVector<AndroidDeviceInfo>> m_virtualDevicesWatcher;
+ QString m_lastAddedAvd;
};
} // namespace Internal
diff --git a/src/plugins/android/androidsettingswidget.ui b/src/plugins/android/androidsettingswidget.ui
index 7343d334c40..23d09510466 100644
--- a/src/plugins/android/androidsettingswidget.ui
+++ b/src/plugins/android/androidsettingswidget.ui
@@ -476,75 +476,11 @@
</customwidget>
</customwidgets>
<resources>
- <include location="android.qrc"/>
<include location="../coreplugin/core.qrc"/>
+ <include location="android.qrc"/>
</resources>
<connections>
<connection>
- <sender>NDKLocationPathChooser</sender>
- <signal>changed(QString)</signal>
- <receiver>AndroidSettingsWidget</receiver>
- <slot>ndkLocationEditingFinished()</slot>
- <hints>
- <hint type="sourcelabel">
- <x>605</x>
- <y>143</y>
- </hint>
- <hint type="destinationlabel">
- <x>352</x>
- <y>210</y>
- </hint>
- </hints>
- </connection>
- <connection>
- <sender>SDKLocationPathChooser</sender>
- <signal>changed(QString)</signal>
- <receiver>AndroidSettingsWidget</receiver>
- <slot>sdkLocationEditingFinished()</slot>
- <hints>
- <hint type="sourcelabel">
- <x>605</x>
- <y>82</y>
- </hint>
- <hint type="destinationlabel">
- <x>352</x>
- <y>210</y>
- </hint>
- </hints>
- </connection>
- <connection>
- <sender>AntLocationPathChooser</sender>
- <signal>changed(QString)</signal>
- <receiver>AndroidSettingsWidget</receiver>
- <slot>antLocationEditingFinished()</slot>
- <hints>
- <hint type="sourcelabel">
- <x>605</x>
- <y>315</y>
- </hint>
- <hint type="destinationlabel">
- <x>352</x>
- <y>210</y>
- </hint>
- </hints>
- </connection>
- <connection>
- <sender>OpenJDKLocationPathChooser</sender>
- <signal>changed(QString)</signal>
- <receiver>AndroidSettingsWidget</receiver>
- <slot>openJDKLocationEditingFinished()</slot>
- <hints>
- <hint type="sourcelabel">
- <x>605</x>
- <y>31</y>
- </hint>
- <hint type="destinationlabel">
- <x>352</x>
- <y>210</y>
- </hint>
- </hints>
- </connection>
- <connection>
<sender>AVDAddPushButton</sender>
<signal>clicked()</signal>
<receiver>AndroidSettingsWidget</receiver>
diff --git a/src/plugins/android/androidtoolchain.cpp b/src/plugins/android/androidtoolchain.cpp
index 01a1c133292..fe3d8650665 100644
--- a/src/plugins/android/androidtoolchain.cpp
+++ b/src/plugins/android/androidtoolchain.cpp
@@ -64,16 +64,14 @@ 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";
-QMap<ProjectExplorer::Abi::Architecture, QList<int> > AndroidToolChainFactory::m_newestVersionForArch;
-Utils::FileName AndroidToolChainFactory::m_ndkLocation;
+QMap<Abi::Architecture, QList<int> > AndroidToolChainFactory::m_newestVersionForArch;
+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,
- 32);
+ Abi abi = Abi(arch, Abi::LinuxOS, Abi::AndroidLinuxFlavor, Abi::ElfFormat, 32);
setTargetAbi(abi);
setDisplayName(QString::fromLatin1("Android GCC (%1-%2)")
.arg(Abi::toString(targetAbi().architecture()))
@@ -148,7 +146,7 @@ FileName AndroidToolChain::suggestedDebugger() const
FileName AndroidToolChain::suggestedGdbServer() const
{
- Utils::FileName path = AndroidConfigurations::currentConfig().ndkLocation();
+ FileName path = AndroidConfigurations::currentConfig().ndkLocation();
path.appendPath(QString::fromLatin1("prebuilt/android-%1/gdbserver/gdbserver")
.arg(Abi::toString(targetAbi().architecture())));
if (path.exists())
@@ -160,7 +158,7 @@ FileName AndroidToolChain::suggestedGdbServer() const
if (path.exists())
return path;
- return Utils::FileName();
+ return FileName();
}
QVariantMap AndroidToolChain::toMap() const
@@ -195,15 +193,13 @@ bool AndroidToolChain::fromMap(const QVariantMap &data)
m_ndkToolChainVersion = command.mid(index + 1);
QString platform = command.left(index);
Abi::Architecture arch = AndroidConfig::architectureForToolChainPrefix(platform);
- ProjectExplorer::Abi abi = ProjectExplorer::Abi(arch, ProjectExplorer::Abi::LinuxOS,
- ProjectExplorer::Abi::AndroidLinuxFlavor, ProjectExplorer::Abi::ElfFormat,
- 32);
+ Abi abi = Abi(arch, Abi::LinuxOS, Abi::AndroidLinuxFlavor, Abi::ElfFormat, 32);
setTargetAbi(abi);
} else {
m_ndkToolChainVersion = data.value(QLatin1String(ANDROID_NDK_TC_VERION)).toString();
}
- ProjectExplorer::Abi::Architecture arch = targetAbi().architecture();
+ Abi::Architecture arch = targetAbi().architecture();
m_secondaryToolChain = AndroidToolChainFactory::versionCompareLess(AndroidToolChainFactory::versionNumberFromString(m_ndkToolChainVersion),
AndroidToolChainFactory::newestToolChainVersionForArch(arch));
return isValid();
@@ -214,7 +210,7 @@ QList<FileName> AndroidToolChain::suggestedMkspecList() const
return QList<FileName>()<< FileName::fromLatin1("android-g++");
}
-QString AndroidToolChain::makeCommand(const Utils::Environment &env) const
+QString AndroidToolChain::makeCommand(const Environment &env) const
{
QStringList extraDirectories = AndroidConfigurations::currentConfig().makeExtraSearchDirectories();
if (HostOsInfo::isWindowsHost()) {
@@ -291,7 +287,7 @@ ToolChain *AndroidToolChainFactory::restore(const QVariantMap &data)
return 0;
}
-QList<AndroidToolChainFactory::AndroidToolChainInformation> AndroidToolChainFactory::toolchainPathsForNdk(const Utils::FileName &ndkPath)
+QList<AndroidToolChainFactory::AndroidToolChainInformation> AndroidToolChainFactory::toolchainPathsForNdk(const FileName &ndkPath)
{
QList<AndroidToolChainInformation> result;
if (ndkPath.isEmpty())
@@ -301,7 +297,7 @@ QList<AndroidToolChainFactory::AndroidToolChainInformation> AndroidToolChainFact
QDirIterator it(path.appendPath(QLatin1String("toolchains")).toString(),
QStringList() << QLatin1String("*"), QDir::Dirs);
while (it.hasNext()) {
- const QString &fileName = QFileInfo(it.next()).fileName();
+ const QString &fileName = FileName::fromString(it.next()).fileName();
int idx = versionRegExp.indexIn(fileName);
if (idx == -1)
continue;
@@ -364,7 +360,7 @@ bool AndroidToolChainFactory::versionCompareLess(AndroidToolChain *atc, AndroidT
return versionCompareLess(a, b);
}
-QList<ToolChain *> AndroidToolChainFactory::createToolChainsForNdk(const Utils::FileName &ndkPath)
+QList<ToolChain *> AndroidToolChainFactory::createToolChainsForNdk(const FileName &ndkPath)
{
QList<ToolChain *> result;
if (ndkPath.isEmpty())
@@ -376,7 +372,7 @@ QList<ToolChain *> AndroidToolChainFactory::createToolChainsForNdk(const Utils::
QMap<Abi::Architecture, AndroidToolChain *> newestToolChainForArch;
while (it.hasNext()) {
- const QString &fileName = QFileInfo(it.next()).fileName();
+ const QString &fileName = FileName::fromString(it.next()).fileName();
int idx = versionRegExp.indexIn(fileName);
if (idx == -1)
continue;
@@ -417,7 +413,7 @@ QList<int> AndroidToolChainFactory::newestToolChainVersionForArch(Abi::Architect
QDirIterator it(path.appendPath(QLatin1String("toolchains")).toString(),
QStringList() << QLatin1String("*"), QDir::Dirs);
while (it.hasNext()) {
- const QString &fileName = QFileInfo(it.next()).fileName();
+ const QString &fileName = FileName::fromString(it.next()).fileName();
int idx = versionRegExp.indexIn(fileName);
if (idx == -1)
continue;
diff --git a/src/plugins/android/javaeditor.cpp b/src/plugins/android/javaeditor.cpp
index 0c3da51689e..acd347eb2e0 100644
--- a/src/plugins/android/javaeditor.cpp
+++ b/src/plugins/android/javaeditor.cpp
@@ -71,14 +71,12 @@ JavaDocument::JavaDocument()
QString JavaDocument::defaultPath() const
{
- QFileInfo fi(filePath());
- return fi.absolutePath();
+ return filePath().toFileInfo().absolutePath();
}
QString JavaDocument::suggestedFileName() const
{
- QFileInfo fi(filePath());
- return fi.fileName();
+ return filePath().fileName();
}
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
index 69a36ee952e..708f016056a 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
@@ -62,7 +62,7 @@ using namespace ProjectExplorer::Constants;
//////////////////////////////////////
// AutotoolsBuildConfiguration class
//////////////////////////////////////
-AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target *parent)
+AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(Target *parent)
: BuildConfiguration(parent, Core::Id(AUTOTOOLS_BC_ID))
{ }
@@ -71,11 +71,11 @@ NamedWidget *AutotoolsBuildConfiguration::createConfigWidget()
return new AutotoolsBuildSettingsWidget(this);
}
-AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target *parent, Core::Id id)
+AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(Target *parent, Core::Id id)
: BuildConfiguration(parent, id)
{ }
-AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target *parent,
+AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(Target *parent,
AutotoolsBuildConfiguration *source)
: BuildConfiguration(parent, source)
{
@@ -173,7 +173,7 @@ bool AutotoolsBuildConfigurationFactory::canHandle(const Target *t) const
return t->project()->id() == Constants::AUTOTOOLS_PROJECT_ID;
}
-BuildInfo *AutotoolsBuildConfigurationFactory::createBuildInfo(const ProjectExplorer::Kit *k,
+BuildInfo *AutotoolsBuildConfigurationFactory::createBuildInfo(const Kit *k,
const Utils::FileName &buildDir) const
{
BuildInfo *info = new BuildInfo(this);
@@ -230,7 +230,7 @@ void AutotoolsBuildConfiguration::setBuildDirectory(const Utils::FileName &direc
if (directory == buildDirectory())
return;
BuildConfiguration::setBuildDirectory(directory);
- ProjectExplorer::BuildStepList *bsl = stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
+ BuildStepList *bsl = stepList(BUILDSTEPS_BUILD);
foreach (BuildStep *bs, bsl->steps()) {
ConfigureStep *cs = qobject_cast<ConfigureStep *>(bs);
if (cs) {
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
index 5a7ee7066cf..3fccdec78b8 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
@@ -64,7 +64,8 @@ AutotoolsBuildSettingsWidget::AutotoolsBuildSettingsWidget(AutotoolsBuildConfigu
m_pathChooser->setEnvironment(bc->environment());
m_pathChooser->setHistoryCompleter(QLatin1String("AutoTools.BuildDir.History"));
fl->addRow(tr("Build directory:"), m_pathChooser);
- connect(m_pathChooser, SIGNAL(changed(QString)), this, SLOT(buildDirectoryChanged()));
+ connect(m_pathChooser, &Utils::PathChooser::changed,
+ this, &AutotoolsBuildSettingsWidget::buildDirectoryChanged);
m_pathChooser->setBaseFileName(bc->target()->project()->projectDirectory());
m_pathChooser->setPath(m_buildConfiguration->rawBuildDirectory().toString());
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsopenprojectwizard.cpp b/src/plugins/autotoolsprojectmanager/autotoolsopenprojectwizard.cpp
index 9ff19788ae7..3452524c268 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsopenprojectwizard.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsopenprojectwizard.cpp
@@ -101,7 +101,7 @@ BuildPathPage::BuildPathPage(AutotoolsOpenProjectWizard *wizard)
m_pc->setHistoryCompleter(QLatin1String("AutoTools.BuildDir.History"));
m_pc->setBaseDirectory(m_wizard->sourceDirectory());
m_pc->setPath(m_wizard->buildDirectory());
- connect(m_pc, SIGNAL(changed(QString)), this, SLOT(buildDirectoryChanged()));
+ connect(m_pc, &Utils::PathChooser::changed, this, &BuildPathPage::buildDirectoryChanged);
fl->addRow(tr("Build directory:"), m_pc);
setTitle(tr("Build Location"));
}
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp b/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
index cac334f113d..8e5b5f9dd44 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
@@ -143,8 +143,8 @@ bool AutotoolsProject::fromMap(const QVariantMap &map)
if (!Project::fromMap(map))
return false;
- connect(m_fileWatcher, SIGNAL(fileChanged(QString)),
- this, SLOT(onFileChanged(QString)));
+ connect(m_fileWatcher, &Utils::FileSystemWatcher::fileChanged,
+ this, &AutotoolsProject::onFileChanged);
// Load the project tree structure.
loadProjectTree();
@@ -172,11 +172,11 @@ void AutotoolsProject::loadProjectTree()
// Parse the makefile asynchronously in a thread
m_makefileParserThread = new MakefileParserThread(m_fileName);
- connect(m_makefileParserThread, SIGNAL(started()),
- this, SLOT(makefileParsingStarted()));
+ connect(m_makefileParserThread, &MakefileParserThread::started,
+ this, &AutotoolsProject::makefileParsingStarted);
- connect(m_makefileParserThread, SIGNAL(finished()),
- this, SLOT(makefileParsingFinished()));
+ connect(m_makefileParserThread, &MakefileParserThread::finished,
+ this, &AutotoolsProject::makefileParsingFinished);
m_makefileParserThread->start();
}
@@ -408,9 +408,7 @@ void AutotoolsProject::updateCppCodeModel()
return;
m_codeModelFuture.cancel();
- CppTools::ProjectInfo pInfo = modelManager->projectInfo(this);
- pInfo.clearProjectParts();
-
+ CppTools::ProjectInfo pInfo = CppTools::ProjectInfo(this);
CppTools::ProjectPartBuilder ppBuilder(pInfo);
const QStringList cflags = m_makefileParserThread->cflags();
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp b/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp
index aed0c45bc9b..0669e4a7528 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectfile.cpp
@@ -43,7 +43,7 @@ AutotoolsProjectFile::AutotoolsProjectFile(AutotoolsProject *project, const QStr
{
setId("Autotools.ProjectFile");
setMimeType(QLatin1String(Constants::MAKEFILE_MIMETYPE));
- setFilePath(fileName);
+ setFilePath(Utils::FileName::fromString(fileName));
}
bool AutotoolsProjectFile::save(QString *errorString, const QString &fileName, bool autoSave)
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp
index 1ed8d30683e..7f961ea293f 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.cpp
@@ -40,7 +40,7 @@ using namespace AutotoolsProjectManager::Internal;
using namespace ProjectExplorer;
AutotoolsProjectNode::AutotoolsProjectNode(AutotoolsProject *project, Core::IDocument *projectFile) :
- ProjectNode(projectFile->filePath()),
+ ProjectNode(projectFile->filePath().toString()),
m_project(project),
m_projectFile(projectFile)
{
@@ -51,10 +51,10 @@ bool AutotoolsProjectNode::showInSimpleTree() const
return true;
}
-QList<ProjectExplorer::ProjectAction> AutotoolsProjectNode::supportedActions(Node *node) const
+QList<ProjectAction> AutotoolsProjectNode::supportedActions(Node *node) const
{
Q_UNUSED(node);
- return QList<ProjectExplorer::ProjectAction>();
+ return QList<ProjectAction>();
}
bool AutotoolsProjectNode::canAddSubProject(const QString &proFilePath) const
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h
index 9b210df0ce9..c9c52716df3 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectnode.h
@@ -53,8 +53,6 @@ class AutotoolsProject;
*/
class AutotoolsProjectNode : public ProjectExplorer::ProjectNode
{
- Q_OBJECT
-
public:
AutotoolsProjectNode(AutotoolsProject *project, Core::IDocument *projectFile);
diff --git a/src/plugins/autotoolsprojectmanager/makefileparser.cpp b/src/plugins/autotoolsprojectmanager/makefileparser.cpp
index e0709bfa77b..3c1e94d1335 100644
--- a/src/plugins/autotoolsprojectmanager/makefileparser.cpp
+++ b/src/plugins/autotoolsprojectmanager/makefileparser.cpp
@@ -292,7 +292,7 @@ void MakefileParser::parseSubDirs()
continue;
MakefileParser parser(subDirMakefile);
- connect(&parser, SIGNAL(status(QString)), this, SIGNAL(status(QString)));
+ connect(&parser, &MakefileParser::status, this, &MakefileParser::status);
const bool success = parser.parse();
// Don't return, try to parse as many sub directories
diff --git a/src/plugins/autotoolsprojectmanager/makefileparserthread.cpp b/src/plugins/autotoolsprojectmanager/makefileparserthread.cpp
index 89f56b32e16..36b7a87f020 100644
--- a/src/plugins/autotoolsprojectmanager/makefileparserthread.cpp
+++ b/src/plugins/autotoolsprojectmanager/makefileparserthread.cpp
@@ -46,7 +46,8 @@ MakefileParserThread::MakefileParserThread(const QString &makefile) :
m_makefiles(),
m_includePaths()
{
- connect(&m_parser, SIGNAL(status(QString)), this, SIGNAL(status(QString)));
+ connect(&m_parser, &MakefileParser::status,
+ this, &MakefileParserThread::status);
}
QStringList MakefileParserThread::sources() const
diff --git a/src/plugins/autotoolsprojectmanager/makestep.cpp b/src/plugins/autotoolsprojectmanager/makestep.cpp
index 9056dbefd03..b0a66cd7bfd 100644
--- a/src/plugins/autotoolsprojectmanager/makestep.cpp
+++ b/src/plugins/autotoolsprojectmanager/makestep.cpp
@@ -304,7 +304,7 @@ void MakeStepConfigWidget::updateDetails()
BuildConfiguration *bc = m_makeStep->buildConfiguration();
if (!bc)
bc = m_makeStep->target()->activeBuildConfiguration();
- ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(m_makeStep->target()->kit());
+ ToolChain *tc = ToolChainKitInformation::toolChain(m_makeStep->target()->kit());
if (tc) {
QString arguments = Utils::QtcProcess::joinArgs(m_makeStep->m_buildTargets);
diff --git a/src/plugins/baremetal/baremetal.pro b/src/plugins/baremetal/baremetal.pro
index 7cf1db563dd..6f534d90aa7 100644
--- a/src/plugins/baremetal/baremetal.pro
+++ b/src/plugins/baremetal/baremetal.pro
@@ -4,6 +4,7 @@ include(../../qtcreatorplugin.pri)
# BareMetal files
SOURCES += baremetalplugin.cpp \
+ baremetalcustomrunconfiguration.cpp\
baremetaldevice.cpp \
baremetalrunconfigurationfactory.cpp \
baremetalrunconfiguration.cpp \
@@ -13,10 +14,20 @@ SOURCES += baremetalplugin.cpp \
baremetaldeviceconfigurationwizardpages.cpp \
baremetaldeviceconfigurationwizard.cpp \
baremetaldeviceconfigurationwidget.cpp \
- baremetaldeviceconfigurationfactory.cpp
+ baremetaldeviceconfigurationfactory.cpp \
+ baremetaldebugsupport.cpp \
+ gdbserverproviderprocess.cpp \
+ gdbserverproviderssettingspage.cpp \
+ gdbserverprovider.cpp \
+ gdbserverproviderchooser.cpp \
+ gdbserverprovidermanager.cpp \
+ openocdgdbserverprovider.cpp \
+ defaultgdbserverprovider.cpp \
+ stlinkutilgdbserverprovider.cpp
HEADERS += baremetalplugin.h \
baremetalconstants.h \
+ baremetalcustomrunconfiguration.h \
baremetaldevice.h \
baremetalrunconfigurationfactory.h \
baremetalrunconfiguration.h \
@@ -26,4 +37,15 @@ HEADERS += baremetalplugin.h \
baremetaldeviceconfigurationfactory.h \
baremetaldeviceconfigurationwidget.h \
baremetaldeviceconfigurationwizard.h \
- baremetaldeviceconfigurationwizardpages.h
+ baremetaldeviceconfigurationwizardpages.h \
+ baremetaldebugsupport.h \
+ gdbserverproviderprocess.h \
+ gdbserverproviderssettingspage.h \
+ gdbserverprovider.h \
+ gdbserverproviderchooser.h \
+ gdbserverprovidermanager.h \
+ openocdgdbserverprovider.h \
+ defaultgdbserverprovider.h \
+ stlinkutilgdbserverprovider.h
+
+RESOURCES = baremetal.qrc
diff --git a/src/plugins/baremetal/baremetal.qbs b/src/plugins/baremetal/baremetal.qbs
index 54dfff066e3..0474e562d13 100644
--- a/src/plugins/baremetal/baremetal.qbs
+++ b/src/plugins/baremetal/baremetal.qbs
@@ -13,7 +13,9 @@ QtcPlugin {
Depends { name: "QtSupport" }
files: [
+ "baremetal.qrc",
"baremetalconstants.h",
+ "baremetalcustomrunconfiguration.cpp", "baremetalcustomrunconfiguration.h",
"baremetaldevice.cpp", "baremetaldevice.h",
"baremetaldeviceconfigurationfactory.cpp", "baremetaldeviceconfigurationfactory.h",
"baremetaldeviceconfigurationwidget.cpp", "baremetaldeviceconfigurationwidget.h",
@@ -25,5 +27,14 @@ QtcPlugin {
"baremetalrunconfigurationfactory.cpp", "baremetalrunconfigurationfactory.h",
"baremetalrunconfigurationwidget.cpp", "baremetalrunconfigurationwidget.h",
"baremetalruncontrolfactory.cpp", "baremetalruncontrolfactory.h",
+ "baremetaldebugsupport.cpp", "baremetaldebugsupport.h",
+ "gdbserverproviderprocess.cpp", "gdbserverproviderprocess.h",
+ "gdbserverproviderssettingspage.cpp", "gdbserverproviderssettingspage.h",
+ "gdbserverprovider.cpp", "gdbserverprovider.h",
+ "gdbserverproviderchooser.cpp", "gdbserverproviderchooser.h",
+ "gdbserverprovidermanager.cpp", "gdbserverprovidermanager.h",
+ "openocdgdbserverprovider.cpp", "openocdgdbserverprovider.h",
+ "defaultgdbserverprovider.cpp", "defaultgdbserverprovider.h",
+ "stlinkutilgdbserverprovider.cpp", "stlinkutilgdbserverprovider.h",
]
}
diff --git a/src/plugins/baremetal/baremetal.qrc b/src/plugins/baremetal/baremetal.qrc
new file mode 100644
index 00000000000..1226d8f5878
--- /dev/null
+++ b/src/plugins/baremetal/baremetal.qrc
@@ -0,0 +1,5 @@
+<RCC>
+ <qresource prefix="/baremetal">
+ <file>images/QtBareMetal.png</file>
+ </qresource>
+</RCC>
diff --git a/src/plugins/baremetal/baremetalconstants.h b/src/plugins/baremetal/baremetalconstants.h
index c2b28950168..519988c8ddb 100644
--- a/src/plugins/baremetal/baremetalconstants.h
+++ b/src/plugins/baremetal/baremetalconstants.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -39,8 +40,18 @@ const char BareMetalOsType[] = "BareMetalOsType";
const char ACTION_ID[] = "BareMetal.Action";
const char MENU_ID[] = "BareMetal.Menu";
+const char BAREMETAL_SETTINGS_CATEGORY[] = "ZZ.BareMetal";
+const char BAREMETAL_SETTINGS_TR_CATEGORY[] = QT_TRANSLATE_NOOP("BareMetal", "BareMetal");
+const char BAREMETAL_SETTINGS_CATEGORY_ICON[] = ":/baremetal/images/QtBareMetal.png";
+
+const char GDB_PROVIDERS_SETTINGS_ID[] = "AA.BareMetal.GdbServerProvidersOptions";
+
+// Debugger Server Provider Ids
+const char OPENOCD_PROVIDER_ID[] = "BareMetal.GdbServerProvider.OpenOcd";
+const char DEFAULT_PROVIDER_ID[] = "BareMetal.GdbServerProvider.Default";
+const char STLINK_UTIL_PROVIDER_ID[] = "BareMetal.GdbServerProvider.STLinkUtil";
+
} // namespace BareMetal
} // namespace Constants
#endif // BAREMETALCONSTANTS_H
-
diff --git a/src/plugins/baremetal/baremetalcustomrunconfiguration.cpp b/src/plugins/baremetal/baremetalcustomrunconfiguration.cpp
new file mode 100644
index 00000000000..2cc8b2236f1
--- /dev/null
+++ b/src/plugins/baremetal/baremetalcustomrunconfiguration.cpp
@@ -0,0 +1,201 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "baremetalcustomrunconfiguration.h"
+
+#include <projectexplorer/target.h>
+#include <qtsupport/qtoutputformatter.h>
+#include <utils/detailswidget.h>
+#include <utils/qtcprocess.h>
+#include <utils/pathchooser.h>
+
+#include <QDir>
+#include <QFileInfo>
+#include <QVBoxLayout>
+#include <QLabel>
+#include <QString>
+#include <QLineEdit>
+
+using namespace Utils;
+
+namespace BareMetal {
+namespace Internal {
+
+class BareMetalCustomRunConfigWidget : public ProjectExplorer::RunConfigWidget
+{
+ Q_OBJECT
+public:
+ BareMetalCustomRunConfigWidget(BareMetalCustomRunConfiguration *runConfig)
+ : m_runConfig(runConfig)
+ {
+ auto const mainLayout = new QVBoxLayout(this);
+ mainLayout->setMargin(0);
+ auto const detailsContainer = new DetailsWidget(this);
+ mainLayout->addWidget(detailsContainer);
+ detailsContainer->setState(DetailsWidget::NoSummary);
+ auto const detailsWidget = new QWidget(this);
+ detailsContainer->setWidget(detailsWidget);
+
+ auto exeLabel = new QLabel(tr("Executable:"));
+ auto executableChooser = new PathChooser;
+ executableChooser->setExpectedKind(PathChooser::File);
+ executableChooser->setPath(m_runConfig->localExecutableFilePath());
+ auto argumentsLabel = new QLabel(tr("Arguments:"));
+ auto arguments = new QLineEdit();
+ arguments->setText(m_runConfig->arguments());
+ auto wdirLabel = new QLabel(tr("Work directory:"));
+ auto workdirChooser = new PathChooser;
+ workdirChooser->setExpectedKind(PathChooser::Directory);
+ workdirChooser->setPath(m_runConfig->workingDirectory());
+
+ auto clayout = new QGridLayout(this);
+ detailsWidget->setLayout(clayout);
+
+ clayout->addWidget(exeLabel, 0, 0);
+ clayout->addWidget(executableChooser, 0, 1);
+ clayout->addWidget(argumentsLabel, 1, 0);
+ clayout->addWidget(arguments, 1, 1);
+ clayout->addWidget(wdirLabel, 2, 0);
+ clayout->addWidget(workdirChooser, 2, 1);
+
+ connect(executableChooser, &PathChooser::pathChanged,
+ this, &BareMetalCustomRunConfigWidget::handleLocalExecutableChanged);
+ connect(arguments, &QLineEdit::textChanged,
+ this, &BareMetalCustomRunConfigWidget::handleArgumentsChanged);
+ connect(workdirChooser, &PathChooser::pathChanged,
+ this, &BareMetalCustomRunConfigWidget::handleWorkingDirChanged);
+ connect(this, &BareMetalCustomRunConfigWidget::setWorkdir,
+ workdirChooser, &PathChooser::setPath);
+ }
+
+signals:
+ void setWorkdir(const QString workdir);
+
+private:
+ void handleLocalExecutableChanged(const QString &path)
+ {
+ m_runConfig->setLocalExecutableFilePath(path.trimmed());
+ if (m_runConfig->workingDirectory().isEmpty()) {
+ QFileInfo fi(path);
+ emit setWorkdir(fi.dir().canonicalPath());
+ handleWorkingDirChanged(fi.dir().canonicalPath());
+ }
+ }
+
+ void handleArgumentsChanged(const QString &arguments)
+ {
+ m_runConfig->setArguments(arguments.trimmed());
+ }
+
+ void handleWorkingDirChanged(const QString &wd)
+ {
+ m_runConfig->setWorkingDirectory(wd.trimmed());
+ }
+
+private:
+ QString displayName() const { return m_runConfig->displayName(); }
+
+ BareMetalCustomRunConfiguration * const m_runConfig;
+};
+
+BareMetalCustomRunConfiguration::BareMetalCustomRunConfiguration(ProjectExplorer::Target *parent)
+ : BareMetalRunConfiguration(parent, runConfigId(), QString())
+{
+}
+
+BareMetalCustomRunConfiguration::BareMetalCustomRunConfiguration(ProjectExplorer::Target *parent,
+ BareMetalCustomRunConfiguration *source)
+ : BareMetalRunConfiguration(parent, source)
+ , m_localExecutable(source->m_localExecutable)
+{
+}
+
+bool BareMetalCustomRunConfiguration::isConfigured() const
+{
+ return !m_localExecutable.isEmpty();
+}
+
+ProjectExplorer::RunConfiguration::ConfigurationState
+BareMetalCustomRunConfiguration::ensureConfigured(QString *errorMessage)
+{
+ if (!isConfigured()) {
+ if (errorMessage) {
+ *errorMessage = tr("The remote executable must be set "
+ "in order to run a custom remote run configuration.");
+ }
+ return UnConfigured;
+ }
+ return Configured;
+}
+
+QWidget *BareMetalCustomRunConfiguration::createConfigurationWidget()
+{
+ return new BareMetalCustomRunConfigWidget(this);
+}
+
+Utils::OutputFormatter *BareMetalCustomRunConfiguration::createOutputFormatter() const
+{
+ return new QtSupport::QtOutputFormatter(target()->project());
+}
+
+Core::Id BareMetalCustomRunConfiguration::runConfigId()
+{
+ return "BareMetal.CustomRunConfig";
+}
+
+QString BareMetalCustomRunConfiguration::runConfigDefaultDisplayName()
+{
+ return tr("Custom Executable (on GDB server or hardware debugger)");
+}
+
+static QString exeKey()
+{
+ return QLatin1String("BareMetal.CustomRunConfig.Executable");
+}
+
+bool BareMetalCustomRunConfiguration::fromMap(const QVariantMap &map)
+{
+ if (!BareMetalRunConfiguration::fromMap(map))
+ return false;
+ m_localExecutable = map.value(exeKey()).toString();
+ return true;
+}
+
+QVariantMap BareMetalCustomRunConfiguration::toMap() const
+{
+ QVariantMap map = BareMetalRunConfiguration::toMap();
+ map.insert(exeKey(), m_localExecutable);
+ return map;
+}
+
+} // namespace Internal
+} // namespace BareMetal
+
+#include "baremetalcustomrunconfiguration.moc"
diff --git a/src/plugins/baremetal/baremetalcustomrunconfiguration.h b/src/plugins/baremetal/baremetalcustomrunconfiguration.h
new file mode 100644
index 00000000000..94f0bc24a54
--- /dev/null
+++ b/src/plugins/baremetal/baremetalcustomrunconfiguration.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 BAREMETALCUSTOMRUNCONFIGURATION_H
+#define BAREMETALCUSTOMRUNCONFIGURATION_H
+
+#include "baremetalrunconfiguration.h"
+
+namespace Utils { class Environment; }
+
+namespace BareMetal {
+namespace Internal {
+
+class BareMetalCustomRunConfiguration : public BareMetalRunConfiguration
+{
+ Q_OBJECT
+public:
+ BareMetalCustomRunConfiguration(ProjectExplorer::Target *parent);
+ BareMetalCustomRunConfiguration(ProjectExplorer::Target *parent,
+ BareMetalCustomRunConfiguration *source);
+
+ bool isEnabled() const { return true; }
+ bool isConfigured() const;
+ ConfigurationState ensureConfigured(QString *errorMessage);
+ QWidget *createConfigurationWidget();
+ Utils::OutputFormatter *createOutputFormatter() const;
+
+ virtual QString localExecutableFilePath() const { return m_localExecutable; }
+
+ void setLocalExecutableFilePath(const QString &executable) { m_localExecutable = executable; }
+
+ static Core::Id runConfigId();
+ static QString runConfigDefaultDisplayName();
+
+ bool fromMap(const QVariantMap &map);
+ QVariantMap toMap() const;
+
+private:
+ QString m_localExecutable;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // Include guard.
diff --git a/src/plugins/baremetal/baremetaldebugsupport.cpp b/src/plugins/baremetal/baremetaldebugsupport.cpp
new file mode 100644
index 00000000000..c2c4fb02b17
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldebugsupport.cpp
@@ -0,0 +1,202 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "baremetaldebugsupport.h"
+#include "baremetalrunconfiguration.h"
+#include "baremetaldevice.h"
+
+#include "gdbserverprovider.h"
+#include "gdbserverprovidermanager.h"
+
+#include <debugger/debuggerruncontrol.h>
+#include <debugger/debuggerstartparameters.h>
+
+#include <projectexplorer/devicesupport/deviceapplicationrunner.h>
+
+namespace BareMetal {
+namespace Internal {
+
+BareMetalDebugSupport::BareMetalDebugSupport(
+ const ProjectExplorer::IDevice::ConstPtr device,
+ Debugger::DebuggerRunControl *runControl)
+ : QObject(runControl)
+ , m_appRunner(new ProjectExplorer::DeviceApplicationRunner(this))
+ , m_runControl(runControl)
+ , m_device(device)
+ , m_state(BareMetalDebugSupport::Inactive)
+{
+ Q_ASSERT(runControl);
+ connect(m_runControl.data(), &Debugger::DebuggerRunControl::requestRemoteSetup,
+ this, &BareMetalDebugSupport::remoteSetupRequested);
+ connect(runControl, &Debugger::DebuggerRunControl::finished,
+ this, &BareMetalDebugSupport::debuggingFinished);
+}
+
+BareMetalDebugSupport::~BareMetalDebugSupport()
+{
+ setFinished();
+}
+
+void BareMetalDebugSupport::remoteSetupRequested()
+{
+ QTC_ASSERT(m_state == Inactive, return);
+ startExecution();
+}
+
+void BareMetalDebugSupport::debuggingFinished()
+{
+ setFinished();
+ reset();
+}
+
+void BareMetalDebugSupport::remoteOutputMessage(const QByteArray &output)
+{
+ QTC_ASSERT(m_state == Inactive || m_state == Running, return);
+ showMessage(QString::fromUtf8(output), Debugger::AppOutput);
+}
+
+void BareMetalDebugSupport::remoteErrorOutputMessage(const QByteArray &output)
+{
+ QTC_ASSERT(m_state == Inactive, return);
+ showMessage(QString::fromUtf8(output), Debugger::AppError);
+
+ // FIXME: Should we here parse an outputn?
+}
+
+void BareMetalDebugSupport::remoteProcessStarted()
+{
+ QTC_ASSERT(m_state == StartingRunner, return);
+ adapterSetupDone();
+}
+
+void BareMetalDebugSupport::appRunnerFinished(bool success)
+{
+ if (m_state == Inactive)
+ return;
+
+ if (m_state == Running) {
+ if (!success)
+ m_runControl->notifyInferiorIll();
+ } else if (m_state == StartingRunner) {
+ Debugger::RemoteSetupResult result;
+ result.success = false;
+ result.reason = tr("Debugging failed.");
+ m_runControl->notifyEngineRemoteSetupFinished(result);
+ }
+
+ reset();
+}
+
+void BareMetalDebugSupport::progressReport(const QString &progressOutput)
+{
+ showMessage(progressOutput + QLatin1Char('\n'), Debugger::LogStatus);
+}
+
+void BareMetalDebugSupport::appRunnerError(const QString &error)
+{
+ if (m_state == Running) {
+ showMessage(error, Debugger::AppError);
+ m_runControl->notifyInferiorIll();
+ } else if (m_state != Inactive) {
+ adapterSetupFailed(error);
+ }
+}
+
+void BareMetalDebugSupport::adapterSetupDone()
+{
+ m_state = Running;
+ Debugger::RemoteSetupResult result;
+ result.success = true;
+ m_runControl->notifyEngineRemoteSetupFinished(result);
+}
+
+void BareMetalDebugSupport::adapterSetupFailed(const QString &error)
+{
+ debuggingFinished();
+
+ Debugger::RemoteSetupResult result;
+ result.success = false;
+ result.reason = tr("Initial setup failed: %1").arg(error);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
+}
+
+void BareMetalDebugSupport::startExecution()
+{
+ auto dev = qSharedPointerCast<const BareMetalDevice>(m_device);
+ QTC_ASSERT(dev, return);
+
+ const GdbServerProvider *p = GdbServerProviderManager::instance()->findProvider(
+ dev->gdbServerProviderId());
+ QTC_ASSERT(p, return);
+
+ m_state = StartingRunner;
+ showMessage(tr("Starting GDB server...") + QLatin1Char('\n'), Debugger::LogStatus);
+
+ connect(m_appRunner.data(), &ProjectExplorer::DeviceApplicationRunner::remoteStderr,
+ this, &BareMetalDebugSupport::remoteErrorOutputMessage);
+ connect(m_appRunner.data(), &ProjectExplorer::DeviceApplicationRunner::remoteStdout,
+ this, &BareMetalDebugSupport::remoteOutputMessage);
+ connect(m_appRunner.data(), &ProjectExplorer::DeviceApplicationRunner::remoteProcessStarted,
+ this, &BareMetalDebugSupport::remoteProcessStarted);
+ connect(m_appRunner.data(), &ProjectExplorer::DeviceApplicationRunner::finished,
+ this, &BareMetalDebugSupport::appRunnerFinished);
+ connect(m_appRunner.data(), &ProjectExplorer::DeviceApplicationRunner::reportProgress,
+ this, &BareMetalDebugSupport::progressReport);
+ connect(m_appRunner.data(), &ProjectExplorer::DeviceApplicationRunner::reportError,
+ this, &BareMetalDebugSupport::appRunnerError);
+
+ const QString cmd = p->executable();
+ const QStringList args = p->arguments();
+ m_appRunner->start(m_device, cmd, args);
+}
+
+void BareMetalDebugSupport::setFinished()
+{
+ if (m_state == Inactive)
+ return;
+ if (m_state == Running)
+ m_appRunner->stop();
+ m_state = Inactive;
+}
+
+void BareMetalDebugSupport::reset()
+{
+ m_appRunner->disconnect(this);
+ m_state = Inactive;
+}
+
+void BareMetalDebugSupport::showMessage(const QString &msg, int channel)
+{
+ if (m_state != Inactive)
+ m_runControl->showMessage(msg, channel);
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetaldebugsupport.h b/src/plugins/baremetal/baremetaldebugsupport.h
new file mode 100644
index 00000000000..160987a077e
--- /dev/null
+++ b/src/plugins/baremetal/baremetaldebugsupport.h
@@ -0,0 +1,91 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 BAREMETALDEBUGSUPPORT_H
+#define BAREMETALDEBUGSUPPORT_H
+
+#include <QObject>
+#include <QPointer>
+
+#include <projectexplorer/devicesupport/idevice.h>
+
+namespace Debugger { class DebuggerRunControl; }
+
+namespace ProjectExplorer {
+class DeviceApplicationRunner;
+class IDevice;
+}
+
+namespace BareMetal {
+namespace Internal {
+
+class GdbServerProvider;
+class BareMetalRunConfiguration;
+
+class BareMetalDebugSupport : public QObject
+{
+ Q_OBJECT
+
+public:
+ explicit BareMetalDebugSupport(const ProjectExplorer::IDevice::ConstPtr device,
+ Debugger::DebuggerRunControl *runControl);
+ ~BareMetalDebugSupport();
+
+private slots:
+ void remoteSetupRequested();
+ void debuggingFinished();
+ void remoteOutputMessage(const QByteArray &output);
+ void remoteErrorOutputMessage(const QByteArray &output);
+ void remoteProcessStarted();
+ void appRunnerFinished(bool success);
+ void progressReport(const QString &progressOutput);
+ void appRunnerError(const QString &error);
+
+private:
+ enum State { Inactive, StartingRunner, Running };
+
+ void adapterSetupDone();
+ void adapterSetupFailed(const QString &error);
+
+ void startExecution();
+ void setFinished();
+ void reset();
+ void showMessage(const QString &msg, int channel);
+
+ QPointer<ProjectExplorer::DeviceApplicationRunner> m_appRunner;
+ const QPointer<Debugger::DebuggerRunControl> m_runControl;
+ const ProjectExplorer::IDevice::ConstPtr m_device;
+ BareMetalDebugSupport::State m_state;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // BAREMETALDEBUGSUPPORT_H
diff --git a/src/plugins/baremetal/baremetaldevice.cpp b/src/plugins/baremetal/baremetaldevice.cpp
index e3a362ad409..2df60b0546b 100644
--- a/src/plugins/baremetal/baremetaldevice.cpp
+++ b/src/plugins/baremetal/baremetaldevice.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -30,6 +31,9 @@
#include "baremetaldevice.h"
#include "baremetaldeviceconfigurationwidget.h"
+
+#include "gdbserverproviderprocess.h"
+
#include <coreplugin/id.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
@@ -39,8 +43,7 @@ using namespace ProjectExplorer;
namespace BareMetal {
namespace Internal {
-const char GdbResetKey[] = "GdbResetCommand";
-const char GdbCommandsKey[] = "GdbCommands";
+const char gdbServerProviderIdKeyC[] = "GdbServerProviderId";
BareMetalDevice::Ptr BareMetalDevice::create()
{
@@ -57,18 +60,26 @@ BareMetalDevice::Ptr BareMetalDevice::create(const BareMetalDevice &other)
return Ptr(new BareMetalDevice(other));
}
+QString BareMetalDevice::gdbServerProviderId() const
+{
+ return m_gdbServerProviderId;
+}
+
+void BareMetalDevice::setGdbServerProviderId(const QString &id)
+{
+ m_gdbServerProviderId = id;
+}
+
void BareMetalDevice::fromMap(const QVariantMap &map)
{
IDevice::fromMap(map);
- setGdbResetCommands(map.value(QLatin1String(GdbResetKey)).toString());
- setGdbInitCommands(map.value(QLatin1String(GdbCommandsKey)).toString());
+ setGdbServerProviderId(map.value(QLatin1String(gdbServerProviderIdKeyC)).toString());
}
QVariantMap BareMetalDevice::toMap() const
{
QVariantMap map = IDevice::toMap();
- map.insert(QLatin1String(GdbResetKey), gdbResetCommands());
- map.insert(QLatin1String(GdbCommandsKey), gdbInitCommands());
+ map.insert(QLatin1String(gdbServerProviderIdKeyC), gdbServerProviderId());
return map;
}
@@ -79,7 +90,7 @@ BareMetalDevice::IDevice::Ptr BareMetalDevice::clone() const
DeviceProcessSignalOperation::Ptr BareMetalDevice::signalOperation() const
{
- return ProjectExplorer::DeviceProcessSignalOperation::Ptr();
+ return DeviceProcessSignalOperation::Ptr();
}
QString BareMetalDevice::displayType() const
@@ -87,7 +98,7 @@ QString BareMetalDevice::displayType() const
return QCoreApplication::translate("BareMetal::Internal::BareMetalDevice", "Bare Metal");
}
-ProjectExplorer::IDeviceWidget *BareMetalDevice::createWidget()
+IDeviceWidget *BareMetalDevice::createWidget()
{
return new BareMetalDeviceConfigurationWidget(sharedFromThis());
}
@@ -109,6 +120,11 @@ void BareMetalDevice::executeAction(Core::Id actionId, QWidget *parent)
Q_UNUSED(parent);
}
+DeviceProcess *BareMetalDevice::createProcess(QObject *parent) const
+{
+ return new GdbServerProviderProcess(sharedFromThis(), parent);
+}
+
BareMetalDevice::BareMetalDevice(const QString &name, Core::Id type, MachineType machineType, Origin origin, Core::Id id)
: IDevice(type, origin, machineType, id)
{
@@ -118,50 +134,7 @@ BareMetalDevice::BareMetalDevice(const QString &name, Core::Id type, MachineType
BareMetalDevice::BareMetalDevice(const BareMetalDevice &other)
: IDevice(other)
{
- setGdbResetCommands(other.gdbResetCommands());
- setGdbInitCommands(other.gdbInitCommands());
-}
-
-QString BareMetalDevice::exampleString()
-{
- return QLatin1String("<p><i>")
- + QCoreApplication::translate("BareMetal", "Example:")
- + QLatin1String("</i><p>");
-}
-
-QString BareMetalDevice::hostLineToolTip()
-{
- return QLatin1String("<html>")
- + QCoreApplication::translate("BareMetal",
- "Enter your hostname like \"localhost\" or \"192.0.2.1\" or "
- "a command which must support GDB pipelining "
- "starting with a pipe symbol.")
- + exampleString() + QLatin1String(
- "&nbsp;&nbsp;|openocd -c \"gdb_port pipe; "
- "log_output openocd.log\" -f boards/myboard.cfg");
-}
-
-QString BareMetalDevice::resetCommandToolTip()
-{
- return QLatin1String("<html>")
- + QCoreApplication::translate("BareMetal",
- "Enter the hardware reset command here.<br>"
- "The CPU should be halted after this command.")
- + exampleString() + QLatin1String(
- "&nbsp;&nbsp;monitor reset halt");
-}
-
-QString BareMetalDevice::initCommandToolTip()
-{
- return QLatin1String("<html>")
- + QCoreApplication::translate("BareMetal",
- "Enter commands to reset the board, and write the nonvolatile memory.")
- + exampleString() + QLatin1String(
- "&nbsp;&nbsp;set remote hardware-breakpoint-limit 6<br/>"
- "&nbsp;&nbsp;set remote hardware-watchpoint-limit 4<br/>"
- "&nbsp;&nbsp;monitor reset halt<br/>"
- "&nbsp;&nbsp;load<br/>"
- "&nbsp;&nbsp;monitor reset halt");
+ setGdbServerProviderId(other.gdbServerProviderId());
}
} //namespace Internal
diff --git a/src/plugins/baremetal/baremetaldevice.h b/src/plugins/baremetal/baremetaldevice.h
index 416c3e0ee5e..41c115865b5 100644
--- a/src/plugins/baremetal/baremetaldevice.h
+++ b/src/plugins/baremetal/baremetaldevice.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -56,20 +57,15 @@ public:
ProjectExplorer::DeviceProcessSignalOperation::Ptr signalOperation() const;
- QString gdbResetCommands() const { return m_gdbResetCommands; }
- void setGdbResetCommands(const QString &gdbResetCommands) { m_gdbResetCommands = gdbResetCommands; }
+ bool canCreateProcess() const { return true; }
+ ProjectExplorer::DeviceProcess *createProcess(QObject *parent) const;
- QString gdbInitCommands() const { return m_gdbInitCommands; }
- void setGdbInitCommands(const QString &gdbCommands) { m_gdbInitCommands=gdbCommands; }
+ QString gdbServerProviderId() const;
+ void setGdbServerProviderId(const QString &id);
virtual void fromMap(const QVariantMap &map);
virtual QVariantMap toMap() const;
- static QString exampleString();
- static QString hostLineToolTip();
- static QString initCommandToolTip();
- static QString resetCommandToolTip();
-
protected:
BareMetalDevice() {}
BareMetalDevice(const QString &name, Core::Id type,
@@ -78,8 +74,7 @@ protected:
private:
BareMetalDevice &operator=(const BareMetalDevice &);
- QString m_gdbResetCommands;
- QString m_gdbInitCommands;
+ QString m_gdbServerProviderId;
};
} //namespace Internal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp
index 8872d93740c..11023cfecb4 100644
--- a/src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -29,21 +30,14 @@
****************************************************************************/
#include "baremetaldeviceconfigurationwidget.h"
-
#include "baremetaldevice.h"
-#include <coreplugin/variablechooser.h>
-#include <ssh/sshconnection.h>
+#include "gdbserverproviderchooser.h"
+#include "gdbserverprovider.h"
+
#include <utils/qtcassert.h>
#include <QFormLayout>
-#include <QLabel>
-#include <QLineEdit>
-#include <QSpinBox>
-#include <QPlainTextEdit>
-
-using namespace Core;
-using namespace QSsh;
namespace BareMetal {
namespace Internal {
@@ -52,77 +46,31 @@ BareMetalDeviceConfigurationWidget::BareMetalDeviceConfigurationWidget(
const ProjectExplorer::IDevice::Ptr &deviceConfig, QWidget *parent)
: IDeviceWidget(deviceConfig, parent)
{
- SshConnectionParameters sshParams = device()->sshParameters();
- QSharedPointer<BareMetalDevice> p = qSharedPointerCast<BareMetalDevice>(device());
- QTC_ASSERT(!p.isNull(), return);
-
- m_gdbHostLineEdit = new QLineEdit(this);
- m_gdbHostLineEdit->setText(sshParams.host);
- m_gdbHostLineEdit->setToolTip(BareMetalDevice::hostLineToolTip());
+ const auto dev = qSharedPointerCast<const BareMetalDevice>(device());
+ QTC_ASSERT(dev, return);
- m_gdbPortSpinBox = new QSpinBox(this);
- m_gdbPortSpinBox->setRange(1, 65535);
- m_gdbPortSpinBox->setValue(sshParams.port);
-
- m_gdbInitCommandsTextEdit = new QPlainTextEdit(this);
- m_gdbInitCommandsTextEdit->setPlainText(p->gdbInitCommands());
- m_gdbInitCommandsTextEdit->setToolTip(BareMetalDevice::initCommandToolTip());
-
- m_gdbResetCommandsTextEdit = new QPlainTextEdit(this);
- m_gdbResetCommandsTextEdit->setPlainText(p->gdbResetCommands());
- m_gdbResetCommandsTextEdit->setToolTip(BareMetalDevice::resetCommandToolTip());
-
- QFormLayout *formLayout = new QFormLayout(this);
+ auto formLayout = new QFormLayout(this);
formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
- formLayout->addRow(tr("GDB host:"), m_gdbHostLineEdit);
- formLayout->addRow(tr("GDB port:"), m_gdbPortSpinBox);
- formLayout->addRow(tr("Init commands:"), m_gdbInitCommandsTextEdit);
- formLayout->addRow(tr("Reset commands:"), m_gdbResetCommandsTextEdit);
-
- auto chooser = new VariableChooser(this);
- chooser->addSupportedWidget(m_gdbResetCommandsTextEdit);
- chooser->addSupportedWidget(m_gdbInitCommandsTextEdit);
- connect(m_gdbHostLineEdit, SIGNAL(editingFinished()), SLOT(hostnameChanged()));
- connect(m_gdbPortSpinBox, SIGNAL(valueChanged(int)), SLOT(portChanged()));
- connect(m_gdbResetCommandsTextEdit, SIGNAL(textChanged()),SLOT(gdbResetCommandsChanged()));
- connect(m_gdbInitCommandsTextEdit, SIGNAL(textChanged()), SLOT(gdbInitCommandsChanged()));
-}
-
-void BareMetalDeviceConfigurationWidget::hostnameChanged()
-{
- SshConnectionParameters sshParams = device()->sshParameters();
- sshParams.host = m_gdbHostLineEdit->text().trimmed();
- device()->setSshParameters(sshParams);
-}
+ m_gdbServerProviderChooser = new GdbServerProviderChooser(true, this);
+ m_gdbServerProviderChooser->populate();
+ m_gdbServerProviderChooser->setCurrentProviderId(dev->gdbServerProviderId());
+ formLayout->addRow(tr("GDB server provider:"), m_gdbServerProviderChooser);
-void BareMetalDeviceConfigurationWidget::portChanged()
-{
- SshConnectionParameters sshParams = device()->sshParameters();
- sshParams.port = m_gdbPortSpinBox->value();
- device()->setSshParameters(sshParams);
-}
-
-void BareMetalDeviceConfigurationWidget::gdbResetCommandsChanged()
-{
- QSharedPointer<BareMetalDevice> p = qSharedPointerCast<BareMetalDevice>(device());
- QTC_ASSERT(!p.isNull(), return);
- p->setGdbResetCommands(m_gdbResetCommandsTextEdit->toPlainText().trimmed());
+ connect(m_gdbServerProviderChooser.data(), &GdbServerProviderChooser::providerChanged,
+ this, &BareMetalDeviceConfigurationWidget::gdbServerProviderChanged);
}
-void BareMetalDeviceConfigurationWidget::gdbInitCommandsChanged()
+void BareMetalDeviceConfigurationWidget::gdbServerProviderChanged()
{
- QSharedPointer<BareMetalDevice> p = qSharedPointerCast<BareMetalDevice>(device());
- QTC_ASSERT(!p.isNull(), return);
- p->setGdbInitCommands(m_gdbInitCommandsTextEdit->toPlainText());
+ auto dev = qSharedPointerCast<BareMetalDevice>(device());
+ QTC_ASSERT(dev, return);
+ dev->setGdbServerProviderId(m_gdbServerProviderChooser->currentProviderId());
}
void BareMetalDeviceConfigurationWidget::updateDeviceFromUi()
{
- hostnameChanged();
- portChanged();
- gdbResetCommandsChanged();
- gdbInitCommandsChanged();
+ gdbServerProviderChanged();
}
} // namespace Internal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwidget.h b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.h
index 46d40386eab..bf1643d1bd2 100644
--- a/src/plugins/baremetal/baremetaldeviceconfigurationwidget.h
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwidget.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -33,15 +34,13 @@
#include <projectexplorer/devicesupport/idevicewidget.h>
-QT_BEGIN_NAMESPACE
-class QLineEdit;
-class QSpinBox;
-class QPlainTextEdit;
-QT_END_NAMESPACE
+#include <QPointer>
namespace BareMetal {
namespace Internal {
+class GdbServerProviderChooser;
+
class BareMetalDeviceConfigurationWidget
: public ProjectExplorer::IDeviceWidget
{
@@ -52,19 +51,12 @@ public:
const ProjectExplorer::IDevice::Ptr &deviceConfig, QWidget *parent = 0);
private slots:
- void hostnameChanged();
- void portChanged();
- void gdbResetCommandsChanged();
- void gdbInitCommandsChanged();
+ void gdbServerProviderChanged();
private:
void updateDeviceFromUi();
- void initGui();
- QLineEdit *m_gdbHostLineEdit;
- QSpinBox *m_gdbPortSpinBox;
- QPlainTextEdit *m_gdbResetCommandsTextEdit;
- QPlainTextEdit *m_gdbInitCommandsTextEdit;
+ QPointer<GdbServerProviderChooser> m_gdbServerProviderChooser;
};
} // namespace Internal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp b/src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp
index 12749a6eb76..2981d1fdb43 100644
--- a/src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizard.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -32,9 +33,6 @@
#include "baremetaldeviceconfigurationwizardpages.h"
#include "baremetaldevice.h"
#include "baremetalconstants.h"
-#include "ssh/sshconnection.h"
-
-using namespace ProjectExplorer;
namespace BareMetal {
namespace Internal {
@@ -50,19 +48,14 @@ BareMetalDeviceConfigurationWizard::BareMetalDeviceConfigurationWizard(QWidget *
m_setupPage->setCommitPage(true);
}
-IDevice::Ptr BareMetalDeviceConfigurationWizard::device() const
+ProjectExplorer::IDevice::Ptr BareMetalDeviceConfigurationWizard::device() const
{
- //sshParams is not really used as ssh parameters but as debugger parameters
- QSsh::SshConnectionParameters sshParams;
- sshParams.host = m_setupPage->gdbHostname();
- sshParams.port = m_setupPage->gdbPort();
- BareMetalDevice::Ptr device = BareMetalDevice::create(m_setupPage->configurationName(),
- Constants::BareMetalOsType,
- IDevice::Hardware);
- device->setSshParameters(sshParams);
- device->setGdbResetCommands(m_setupPage->gdbResetCommands());
- device->setGdbInitCommands(m_setupPage->gdbInitCommands());
- return device;
+ auto dev = BareMetalDevice::create(m_setupPage->configurationName(),
+ Constants::BareMetalOsType,
+ ProjectExplorer::IDevice::Hardware);
+
+ dev->setGdbServerProviderId(m_setupPage->gdbServerProviderId());
+ return dev;
}
} // namespace Internal
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp
index ea473ef6a2d..e4b34741571 100644
--- a/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -31,66 +32,35 @@
#include "baremetaldeviceconfigurationwizardpages.h"
#include "baremetaldevice.h"
+#include "gdbserverproviderchooser.h"
+
#include <coreplugin/variablechooser.h>
#include <projectexplorer/devicesupport/idevice.h>
#include <QFormLayout>
#include <QLineEdit>
-#include <QPlainTextEdit>
-#include <QSpinBox>
-
-using namespace Core;
namespace BareMetal {
namespace Internal {
-BareMetalDeviceConfigurationWizardSetupPage::BareMetalDeviceConfigurationWizardSetupPage(QWidget *parent)
+BareMetalDeviceConfigurationWizardSetupPage::BareMetalDeviceConfigurationWizardSetupPage(
+ QWidget *parent)
: QWizardPage(parent)
{
setTitle(tr("Set up GDB Server or Hardware Debugger"));
- m_nameLineEdit = new QLineEdit(this);
-
- m_hostNameLineEdit = new QLineEdit(this);
- m_hostNameLineEdit->setToolTip(BareMetalDevice::hostLineToolTip());
- m_hostNameLineEdit->setText(QLatin1String(
- "|openocd -c \"gdb_port pipe\" -c \"log_output openocd.log;\" "
- "-f board/stm3241g_eval_stlink.cfg"));
-
- m_portSpinBox = new QSpinBox(this);
- m_portSpinBox->setRange(1, 65535);
- m_portSpinBox->setValue(3333);
-
- m_gdbInitCommandsPlainTextEdit = new QPlainTextEdit(this);
- m_gdbInitCommandsPlainTextEdit->setToolTip(BareMetalDevice::initCommandToolTip());
- m_gdbInitCommandsPlainTextEdit->setPlainText(QLatin1String(
- "set remote hardware-breakpoint-limit 6\n"
- "set remote hardware-watchpoint-limit 4\n"
- "monitor reset halt\n"
- "load\n"
- "monitor reset halt"));
-
- m_gdbResetCommandsTextEdit = new QPlainTextEdit(this);
- m_gdbResetCommandsTextEdit->setToolTip(BareMetalDevice::resetCommandToolTip());
- m_gdbResetCommandsTextEdit->setPlainText(QLatin1String("monitor reset halt"));
-
- QFormLayout *formLayout = new QFormLayout(this);
+ auto formLayout = new QFormLayout(this);
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
+ m_nameLineEdit = new QLineEdit(this);
formLayout->addRow(tr("Name:"), m_nameLineEdit);
- formLayout->addRow(tr("GDB host:"), m_hostNameLineEdit);
- formLayout->addRow(tr("GDB port:"), m_portSpinBox);
- formLayout->addRow(tr("Init commands:"), m_gdbInitCommandsPlainTextEdit);
- formLayout->addRow(tr("Reset commands:"), m_gdbResetCommandsTextEdit);
-
- connect(m_nameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged()));
- connect(m_hostNameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged()));
- connect(m_portSpinBox, SIGNAL(valueChanged(int)), SIGNAL(completeChanged()));
- connect(m_gdbResetCommandsTextEdit, SIGNAL(textChanged()), SIGNAL(completeChanged()));
- connect(m_gdbInitCommandsPlainTextEdit, SIGNAL(textChanged()), SIGNAL(completeChanged()));
-
- auto chooser = new VariableChooser(this);
- chooser->addSupportedWidget(m_gdbResetCommandsTextEdit);
- chooser->addSupportedWidget(m_gdbInitCommandsPlainTextEdit);
+ m_gdbServerProviderChooser = new GdbServerProviderChooser(false, this);
+ m_gdbServerProviderChooser->populate();
+ formLayout->addRow(tr("GDB server provider:"), m_gdbServerProviderChooser);
+
+ connect(m_nameLineEdit, SIGNAL(textChanged(QString)),
+ SIGNAL(completeChanged()));
+ connect(m_gdbServerProviderChooser.data(), &GdbServerProviderChooser::providerChanged,
+ this, &QWizardPage::completeChanged);
}
void BareMetalDeviceConfigurationWizardSetupPage::initializePage()
@@ -108,24 +78,9 @@ QString BareMetalDeviceConfigurationWizardSetupPage::configurationName() const
return m_nameLineEdit->text().trimmed();
}
-QString BareMetalDeviceConfigurationWizardSetupPage::gdbHostname() const
-{
- return m_hostNameLineEdit->text().trimmed();
-}
-
-quint16 BareMetalDeviceConfigurationWizardSetupPage::gdbPort() const
-{
- return quint16(m_portSpinBox->value());
-}
-
-QString BareMetalDeviceConfigurationWizardSetupPage::gdbResetCommands() const
-{
- return m_gdbResetCommandsTextEdit->toPlainText().trimmed();
-}
-
-QString BareMetalDeviceConfigurationWizardSetupPage::gdbInitCommands() const
+QString BareMetalDeviceConfigurationWizardSetupPage::gdbServerProviderId() const
{
- return m_gdbInitCommandsPlainTextEdit->toPlainText().trimmed();
+ return m_gdbServerProviderChooser->currentProviderId();
}
QString BareMetalDeviceConfigurationWizardSetupPage::defaultConfigurationName() const
diff --git a/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h
index 6d69d48779e..d3dc0e8f0de 100644
--- a/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h
+++ b/src/plugins/baremetal/baremetaldeviceconfigurationwizardpages.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -31,17 +32,19 @@
#ifndef BAREMETALDEVICECONFIGURATIONWIZARDPAGES_H
#define BAREMETALDEVICECONFIGURATIONWIZARDPAGES_H
+#include <QPointer>
+
#include <QWizardPage>
QT_BEGIN_NAMESPACE
class QLineEdit;
-class QSpinBox;
-class QPlainTextEdit;
QT_END_NAMESPACE
namespace BareMetal {
namespace Internal {
+class GdbServerProviderChooser;
+
class BareMetalDeviceConfigurationWizardSetupPage : public QWizardPage
{
Q_OBJECT
@@ -52,19 +55,13 @@ public:
void initializePage();
bool isComplete() const;
QString configurationName() const;
- QString gdbHostname() const;
- quint16 gdbPort() const;
- QString gdbResetCommands() const;
- QString gdbInitCommands() const;
+ QString gdbServerProviderId() const;
virtual QString defaultConfigurationName() const;
private:
- QLineEdit *m_nameLineEdit;
- QLineEdit *m_hostNameLineEdit;
- QSpinBox *m_portSpinBox;
- QPlainTextEdit *m_gdbResetCommandsTextEdit;
- QPlainTextEdit *m_gdbInitCommandsPlainTextEdit;
+ QPointer<QLineEdit> m_nameLineEdit;
+ QPointer<GdbServerProviderChooser> m_gdbServerProviderChooser;
};
} // namespace Internal
diff --git a/src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp b/src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp
index 1c8d2f78745..930120a686a 100644
--- a/src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp
+++ b/src/plugins/baremetal/baremetalgdbcommandsdeploystep.cpp
@@ -109,7 +109,7 @@ QVariantMap BareMetalGdbCommandsDeployStep::toMap() const
return map;
}
-ProjectExplorer::BuildStepConfigWidget *BareMetalGdbCommandsDeployStep::createConfigWidget()
+BuildStepConfigWidget *BareMetalGdbCommandsDeployStep::createConfigWidget()
{
return new BareMetalGdbCommandsDeployStepWidget(*this);
}
diff --git a/src/plugins/baremetal/baremetalplugin.cpp b/src/plugins/baremetal/baremetalplugin.cpp
index 47af5df647e..a0a841d71b7 100644
--- a/src/plugins/baremetal/baremetalplugin.cpp
+++ b/src/plugins/baremetal/baremetalplugin.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -34,6 +35,9 @@
#include "baremetalruncontrolfactory.h"
#include "baremetalrunconfigurationfactory.h"
+#include "gdbserverproviderssettingspage.h"
+#include "gdbserverprovidermanager.h"
+
#include <coreplugin/icore.h>
#include <coreplugin/icontext.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -67,10 +71,15 @@ bool BareMetalPlugin::initialize(const QStringList &arguments, QString *errorStr
addAutoReleasedObject(new BareMetalDeviceConfigurationFactory);
addAutoReleasedObject(new BareMetalRunControlFactory);
addAutoReleasedObject(new BareMetalRunConfigurationFactory);
+ addAutoReleasedObject(new GdbServerProvidersSettingsPage);
return true;
}
+void BareMetalPlugin::extensionsInitialized()
+{
+ GdbServerProviderManager::instance()->restoreProviders();
+}
+
} // namespace Internal
} // namespace BareMetal
-
diff --git a/src/plugins/baremetal/baremetalplugin.h b/src/plugins/baremetal/baremetalplugin.h
index 5dd82395d10..43b7ec2e02f 100644
--- a/src/plugins/baremetal/baremetalplugin.h
+++ b/src/plugins/baremetal/baremetalplugin.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -46,11 +47,10 @@ public:
~BareMetalPlugin();
bool initialize(const QStringList &arguments, QString *errorString);
- void extensionsInitialized() { }
+ void extensionsInitialized();
};
} // namespace Internal
} // namespace BareMetal
#endif // BAREMETAL_H
-
diff --git a/src/plugins/baremetal/baremetalrunconfiguration.cpp b/src/plugins/baremetal/baremetalrunconfiguration.cpp
index 12cf0c7e1a3..811bbd25e57 100644
--- a/src/plugins/baremetal/baremetalrunconfiguration.cpp
+++ b/src/plugins/baremetal/baremetalrunconfiguration.cpp
@@ -137,7 +137,7 @@ QString BareMetalRunConfiguration::defaultDisplayName()
QString BareMetalRunConfiguration::localExecutableFilePath() const
{
return target()->applicationTargets()
- .targetForProject(Utils::FileName::fromString(m_projectFilePath)).toString();
+ .targetForProject(FileName::fromString(m_projectFilePath)).toString();
}
QString BareMetalRunConfiguration::arguments() const
@@ -176,7 +176,7 @@ void BareMetalRunConfiguration::handleBuildSystemDataUpdated()
updateEnableState();
}
-const char *BareMetalRunConfiguration::IdPrefix = "BareMetalRunConfiguration";
+const char *BareMetalRunConfiguration::IdPrefix = "BareMetal";
} // namespace Internal
} // namespace BareMetal
diff --git a/src/plugins/baremetal/baremetalrunconfiguration.h b/src/plugins/baremetal/baremetalrunconfiguration.h
index 75e053b1837..1af747eed69 100644
--- a/src/plugins/baremetal/baremetalrunconfiguration.h
+++ b/src/plugins/baremetal/baremetalrunconfiguration.h
@@ -55,7 +55,7 @@ public:
QWidget *createConfigurationWidget();
Utils::OutputFormatter *createOutputFormatter() const;
- QString localExecutableFilePath() const;
+ virtual QString localExecutableFilePath() const;
QString arguments() const;
void setArguments(const QString &args);
QString workingDirectory() const;
diff --git a/src/plugins/baremetal/baremetalrunconfigurationfactory.cpp b/src/plugins/baremetal/baremetalrunconfigurationfactory.cpp
index 46ed1b38b48..d9f3b71dd04 100644
--- a/src/plugins/baremetal/baremetalrunconfigurationfactory.cpp
+++ b/src/plugins/baremetal/baremetalrunconfigurationfactory.cpp
@@ -30,6 +30,7 @@
#include "baremetalrunconfigurationfactory.h"
#include "baremetalconstants.h"
+#include "baremetalcustomrunconfiguration.h"
#include "baremetalrunconfiguration.h"
#include <projectexplorer/buildtargetinfo.h>
@@ -55,7 +56,7 @@ static QString pathFromId(Core::Id id)
}
BareMetalRunConfigurationFactory::BareMetalRunConfigurationFactory(QObject *parent) :
- ProjectExplorer::IRunConfigurationFactory(parent)
+ IRunConfigurationFactory(parent)
{
setObjectName(QLatin1String("BareMetalRunConfigurationFactory"));
}
@@ -68,14 +69,17 @@ bool BareMetalRunConfigurationFactory::canCreate(Target *parent, Core::Id id) co
{
if (!canHandle(parent))
return false;
- return !parent->applicationTargets().targetForProject(pathFromId(id)).isEmpty();
+ return id == BareMetalCustomRunConfiguration::runConfigId()
+ || !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);
+ const Core::Id id = idFromMap(map);
+ return id == BareMetalCustomRunConfiguration::runConfigId()
+ || idFromMap(map).name().startsWith(BareMetalRunConfiguration::IdPrefix);
}
bool BareMetalRunConfigurationFactory::canClone(Target *parent, RunConfiguration *source) const
@@ -95,30 +99,37 @@ QList<Core::Id> BareMetalRunConfigurationFactory::availableCreationIds(Target *p
const Core::Id base = Core::Id(BareMetalRunConfiguration::IdPrefix);
foreach (const BuildTargetInfo &bti, parent->applicationTargets().list)
result << base.withSuffix(bti.projectFilePath.toString());
+ result << BareMetalCustomRunConfiguration::runConfigId();
return result;
}
QString BareMetalRunConfigurationFactory::displayNameForId(Core::Id id) const
{
+ if (id == BareMetalCustomRunConfiguration::runConfigId())
+ return BareMetalCustomRunConfiguration::runConfigDefaultDisplayName();
return tr("%1 (on GDB server or hardware debugger)")
.arg(QFileInfo(pathFromId(id)).completeBaseName());
}
RunConfiguration *BareMetalRunConfigurationFactory::doCreate(Target *parent, Core::Id id)
{
- Q_UNUSED(id);
+ if (id == BareMetalCustomRunConfiguration::runConfigId())
+ return new BareMetalCustomRunConfiguration(parent);
return new BareMetalRunConfiguration(parent, id, pathFromId(id));
}
RunConfiguration *BareMetalRunConfigurationFactory::doRestore(Target *parent, const QVariantMap &map)
{
- Q_UNUSED(map);
+ if (idFromMap(map) == BareMetalCustomRunConfiguration::runConfigId())
+ return new BareMetalCustomRunConfiguration(parent);
return doCreate(parent,Core::Id(BareMetalRunConfiguration::IdPrefix));
}
RunConfiguration *BareMetalRunConfigurationFactory::clone(Target *parent, RunConfiguration *source)
{
QTC_ASSERT(canClone(parent, source), return 0);
+ if (BareMetalCustomRunConfiguration *old = qobject_cast<BareMetalCustomRunConfiguration *>(source))
+ return new BareMetalCustomRunConfiguration(parent, old);
BareMetalRunConfiguration *old = static_cast<BareMetalRunConfiguration*>(source);
return new BareMetalRunConfiguration(parent,old);
}
diff --git a/src/plugins/baremetal/baremetalruncontrolfactory.cpp b/src/plugins/baremetal/baremetalruncontrolfactory.cpp
index 252a01c3cf2..47734c14722 100644
--- a/src/plugins/baremetal/baremetalruncontrolfactory.cpp
+++ b/src/plugins/baremetal/baremetalruncontrolfactory.cpp
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -32,6 +33,10 @@
#include "baremetalgdbcommandsdeploystep.h"
#include "baremetalrunconfiguration.h"
#include "baremetaldevice.h"
+#include "baremetaldebugsupport.h"
+
+#include "gdbserverprovider.h"
+#include "gdbserverprovidermanager.h"
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerstartparameters.h>
@@ -58,7 +63,7 @@ namespace BareMetal {
namespace Internal {
BareMetalRunControlFactory::BareMetalRunControlFactory(QObject *parent) :
- ProjectExplorer::IRunControlFactory(parent)
+ IRunControlFactory(parent)
{
}
@@ -68,82 +73,97 @@ BareMetalRunControlFactory::~BareMetalRunControlFactory()
bool BareMetalRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
- if (mode != NormalRunMode && mode != DebugRunMode && mode != DebugRunModeWithBreakOnMain
- && mode != QmlProfilerRunMode) {
+ if (mode != NormalRunMode && mode != DebugRunMode && mode != DebugRunModeWithBreakOnMain)
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 = 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().toString();
- if (const BuildConfiguration *buildConfig = target->activeBuildConfiguration())
- params.projectBuildDirectory = buildConfig->buildDirectory().toString();
- params.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
- }
- if (device->sshParameters().host.startsWith(QLatin1Char('|'))) //gdb pipe mode enabled
- params.remoteChannel = device->sshParameters().host;
- else
- params.remoteChannel = device->sshParameters().host + QLatin1Char(':') + QString::number(device->sshParameters().port);
- params.remoteSetupNeeded = false; // qml stuff, not needed
- params.commandsAfterConnect = device->gdbInitCommands().toLatin1();
- params.commandsForReset = device->gdbResetCommands().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().toLatin1());
- }
- }
- }
- params.useContinueInsteadOfRun = true; //we can't execute as its always running
- return params;
-}
-
-RunControl *BareMetalRunControlFactory::create(RunConfiguration *runConfiguration,
- RunMode mode,
- QString *errorMessage)
+RunControl *BareMetalRunControlFactory::create(
+ RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage)
{
QTC_ASSERT(canRun(runConfiguration, mode), return 0);
- BareMetalRunConfiguration *rc = qobject_cast<BareMetalRunConfiguration *>(runConfiguration);
+ const auto rc = qobject_cast<BareMetalRunConfiguration *>(runConfiguration);
QTC_ASSERT(rc, return 0);
- IDevice::ConstPtr dev = DeviceKitInformation::device(rc->target()->kit());
+
+ const QString bin = rc->localExecutableFilePath();
+ if (bin.isEmpty()) {
+ *errorMessage = tr("Cannot debug: Local executable is not set.");
+ return 0;
+ } else if (!QFile::exists(bin)) {
+ *errorMessage = tr("Cannot debug: Could not find executable for \"%1\".")
+ .arg(bin);
+ return 0;
+ }
+
+ const Target *target = rc->target();
+ QTC_ASSERT(target, return 0);
+
+ const Kit *kit = target->kit();
+ QTC_ASSERT(kit, return 0);
+
+ auto dev = qSharedPointerCast<const BareMetalDevice>(DeviceKitInformation::device(kit));
if (!dev) {
*errorMessage = tr("Cannot debug: Kit has no device.");
return 0;
}
- DebuggerStartParameters sp = startParameters(rc);
- if (!QFile::exists(sp.executable)) {
- *errorMessage = QApplication::translate("Core::Internal::ExecuteFilter",
- "Could not find executable for \"%1\".")
- .arg(sp.executable);
+
+ const GdbServerProvider *p = GdbServerProviderManager::instance()->findProvider(
+ dev->gdbServerProviderId());
+ if (!p) {
+ *errorMessage = tr("Cannot debug: Device has no GDB server provider configuration.");
return 0;
}
- return DebuggerRunControlFactory::doCreate(sp, runConfiguration, errorMessage);
+
+ DebuggerStartParameters sp;
+
+ if (const ToolChain *tc = ToolChainKitInformation::toolChain(kit))
+ sp.toolChainAbi = tc->targetAbi();
+
+ if (const Project *project = target->project()) {
+ sp.projectSourceDirectory = project->projectDirectory().toString();
+ sp.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
+
+ if (const BuildConfiguration *bc = target->activeBuildConfiguration()) {
+ sp.projectBuildDirectory = bc->buildDirectory().toString();
+ if (const BuildStepList *bsl = bc->stepList(BareMetalGdbCommandsDeployStep::stepId())) {
+ foreach (const BuildStep *bs, bsl->steps()) {
+ const auto ds = qobject_cast<const BareMetalGdbCommandsDeployStep *>(bs);
+ if (ds) {
+ if (!sp.commandsAfterConnect.endsWith("\n"))
+ sp.commandsAfterConnect.append("\n");
+ sp.commandsAfterConnect.append(ds->gdbCommands().toLatin1());
+ }
+ }
+ }
+ }
+ }
+
+ sp.executable = bin;
+ sp.sysRoot = SysRootKitInformation::sysRoot(kit).toString();
+ sp.debuggerCommand = DebuggerKitInformation::debuggerCommand(kit).toString();
+ sp.languages |= CppLanguage;
+ sp.processArgs = rc->arguments();
+ sp.startMode = AttachToRemoteServer;
+ sp.displayName = rc->displayName();
+ sp.commandsAfterConnect = p->initCommands().toLatin1();
+ sp.commandsForReset = p->resetCommands().toLatin1();
+ sp.remoteChannel = p->channel();
+ sp.useContinueInsteadOfRun = true;
+
+ if (p->startupMode() == GdbServerProvider::StartupOnNetwork)
+ sp.remoteSetupNeeded = true;
+
+ sp.runConfiguration = rc;
+ DebuggerRunControl *runControl = DebuggerRunControlFactory::doCreate(sp, errorMessage);
+ if (runControl && sp.remoteSetupNeeded) {
+ const auto debugSupport = new BareMetalDebugSupport(dev, runControl);
+ Q_UNUSED(debugSupport);
+ }
+
+ return runControl;
}
} // namespace Internal
diff --git a/src/plugins/baremetal/baremetalruncontrolfactory.h b/src/plugins/baremetal/baremetalruncontrolfactory.h
index f55b153086e..68f5e15645a 100644
--- a/src/plugins/baremetal/baremetalruncontrolfactory.h
+++ b/src/plugins/baremetal/baremetalruncontrolfactory.h
@@ -1,6 +1,7 @@
/****************************************************************************
**
** Copyright (C) 2015 Tim Sander <tim@krieglstein.org>
+** Copyright (C) 2015 Denis Shienkov <denis.shienkov@gmail.com>
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
@@ -46,7 +47,6 @@ class BareMetalRunControlFactory : public ProjectExplorer::IRunControlFactory
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,
diff --git a/src/plugins/baremetal/defaultgdbserverprovider.cpp b/src/plugins/baremetal/defaultgdbserverprovider.cpp
new file mode 100644
index 00000000000..e76b3b60eff
--- /dev/null
+++ b/src/plugins/baremetal/defaultgdbserverprovider.cpp
@@ -0,0 +1,211 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "defaultgdbserverprovider.h"
+#include "baremetalconstants.h"
+#include "gdbserverprovidermanager.h"
+
+#include <utils/qtcassert.h>
+
+#include <coreplugin/variablechooser.h>
+
+#include <QFormLayout>
+#include <QPlainTextEdit>
+
+namespace BareMetal {
+namespace Internal {
+
+static const char hostKeyC[] = "BareMetal.DefaultGdbServerProvider.Host";
+static const char portKeyC[] = "BareMetal.DefaultGdbServerProvider.Port";
+
+DefaultGdbServerProvider::DefaultGdbServerProvider()
+ : GdbServerProvider(QLatin1String(Constants::DEFAULT_PROVIDER_ID))
+ , m_host(QLatin1String("localhost"))
+ , m_port(3333)
+{
+}
+
+DefaultGdbServerProvider::DefaultGdbServerProvider(const DefaultGdbServerProvider &other)
+ : GdbServerProvider(other)
+ , m_host(other.m_host)
+ , m_port(other.m_port)
+{
+}
+
+QString DefaultGdbServerProvider::typeDisplayName() const
+{
+ return DefaultGdbServerProviderFactory::tr("Default");
+}
+
+QString DefaultGdbServerProvider::channel() const
+{
+ // Just return as "host:port" form.
+ if (m_port == 0)
+ return m_host;
+ return m_host + QLatin1Char(':') + QString::number(m_port);
+}
+
+bool DefaultGdbServerProvider::isValid() const
+{
+ if (!GdbServerProvider::isValid())
+ return false;
+
+ if (m_host.isEmpty())
+ return false;
+ return true;
+}
+
+GdbServerProvider *DefaultGdbServerProvider::clone() const
+{
+ return new DefaultGdbServerProvider(*this);
+}
+
+QVariantMap DefaultGdbServerProvider::toMap() const
+{
+ auto data = GdbServerProvider::toMap();
+ data.insert(QLatin1String(hostKeyC), m_host);
+ data.insert(QLatin1String(portKeyC), m_port);
+ return data;
+}
+
+bool DefaultGdbServerProvider::fromMap(const QVariantMap &data)
+{
+ if (!GdbServerProvider::fromMap(data))
+ return false;
+
+ m_host = data.value(QLatin1String(hostKeyC)).toString();
+ m_port = data.value(QLatin1String(portKeyC)).toInt();
+ return true;
+}
+
+bool DefaultGdbServerProvider::operator==(const GdbServerProvider &other) const
+{
+ if (!GdbServerProvider::operator==(other))
+ return false;
+
+ const auto p = static_cast<const DefaultGdbServerProvider *>(&other);
+ return m_host == p->m_host && m_port == p->m_port;
+}
+
+GdbServerProviderConfigWidget *DefaultGdbServerProvider::configurationWidget()
+{
+ return new DefaultGdbServerProviderConfigWidget(this);
+}
+
+DefaultGdbServerProviderFactory::DefaultGdbServerProviderFactory()
+{
+ setId(QLatin1String(Constants::DEFAULT_PROVIDER_ID));
+ setDisplayName(tr("Default"));
+}
+
+GdbServerProvider *DefaultGdbServerProviderFactory::create()
+{
+ return new DefaultGdbServerProvider;
+}
+
+bool DefaultGdbServerProviderFactory::canRestore(const QVariantMap &data)
+{
+ const auto id = idFromMap(data);
+ return id.startsWith(QLatin1String(Constants::DEFAULT_PROVIDER_ID)
+ + QLatin1Char(':'));
+}
+
+GdbServerProvider *DefaultGdbServerProviderFactory::restore(const QVariantMap &data)
+{
+ auto p = new DefaultGdbServerProvider;
+ auto updated = data;
+ if (p->fromMap(updated))
+ return p;
+ delete p;
+ return 0;
+}
+
+DefaultGdbServerProviderConfigWidget::DefaultGdbServerProviderConfigWidget(
+ DefaultGdbServerProvider *provider)
+ : GdbServerProviderConfigWidget(provider)
+{
+ Q_ASSERT(provider);
+
+ m_hostWidget = new HostWidget(this);
+ m_mainLayout->addRow(tr("Host:"), m_hostWidget);
+
+ m_initCommandsTextEdit = new QPlainTextEdit(this);
+ m_initCommandsTextEdit->setToolTip(defaultInitCommandsTooltip());
+ m_mainLayout->addRow(tr("Init commands:"), m_initCommandsTextEdit);
+ m_resetCommandsTextEdit = new QPlainTextEdit(this);
+ m_resetCommandsTextEdit->setToolTip(defaultResetCommandsTooltip());
+ m_mainLayout->addRow(tr("Reset commands:"), m_resetCommandsTextEdit);
+
+ addErrorLabel();
+ setFromProvider();
+
+ auto chooser = new Core::VariableChooser(this);
+ chooser->addSupportedWidget(m_initCommandsTextEdit.data());
+ chooser->addSupportedWidget(m_resetCommandsTextEdit.data());
+
+ connect(m_hostWidget.data(), &HostWidget::dataChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_initCommandsTextEdit.data(), &QPlainTextEdit::textChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_resetCommandsTextEdit.data(), &QPlainTextEdit::textChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+}
+
+void DefaultGdbServerProviderConfigWidget::applyImpl()
+{
+ auto p = static_cast<DefaultGdbServerProvider *>(provider());
+ Q_ASSERT(p);
+
+ p->m_host = m_hostWidget->host();
+ p->m_port = m_hostWidget->port();
+ p->setInitCommands(m_initCommandsTextEdit->toPlainText());
+ p->setResetCommands(m_resetCommandsTextEdit->toPlainText());
+}
+
+void DefaultGdbServerProviderConfigWidget::discardImpl()
+{
+ setFromProvider();
+}
+
+void DefaultGdbServerProviderConfigWidget::setFromProvider()
+{
+ const auto p = static_cast<DefaultGdbServerProvider *>(provider());
+ Q_ASSERT(p);
+
+ const auto b = blockSignals(true);
+ m_hostWidget->setHost(p->m_host);
+ m_hostWidget->setPort(p->m_port);
+ m_initCommandsTextEdit->setPlainText(p->initCommands());
+ m_resetCommandsTextEdit->setPlainText(p->resetCommands());
+ blockSignals(b);
+}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/baremetal/defaultgdbserverprovider.h b/src/plugins/baremetal/defaultgdbserverprovider.h
new file mode 100644
index 00000000000..c9390f39814
--- /dev/null
+++ b/src/plugins/baremetal/defaultgdbserverprovider.h
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 DEFAULTGDBSERVERPROVIDER_H
+#define DEFAULTGDBSERVERPROVIDER_H
+
+#include "gdbserverprovider.h"
+
+namespace BareMetal {
+namespace Internal {
+
+class DefaultGdbServerProviderConfigWidget;
+class DefaultGdbServerProviderFactory;
+
+class DefaultGdbServerProvider : public GdbServerProvider
+{
+public:
+ QString typeDisplayName() const;
+
+ QVariantMap toMap() const;
+ bool fromMap(const QVariantMap &data);
+
+ bool operator==(const GdbServerProvider &) const;
+
+ GdbServerProviderConfigWidget *configurationWidget();
+ GdbServerProvider *clone() const;
+
+ QString channel() const;
+
+ bool isValid() const;
+
+private:
+ explicit DefaultGdbServerProvider();
+ explicit DefaultGdbServerProvider(const DefaultGdbServerProvider &);
+
+ QString m_host;
+ quint16 m_port;
+
+ friend class DefaultGdbServerProviderConfigWidget;
+ friend class DefaultGdbServerProviderFactory;
+};
+
+class DefaultGdbServerProviderFactory : public GdbServerProviderFactory
+{
+ Q_OBJECT
+
+public:
+ explicit DefaultGdbServerProviderFactory();
+
+ GdbServerProvider *create();
+
+ bool canRestore(const QVariantMap &data);
+ GdbServerProvider *restore(const QVariantMap &data);
+
+ GdbServerProviderConfigWidget *configurationWidget(GdbServerProvider *);
+};
+
+class DefaultGdbServerProviderConfigWidget : public GdbServerProviderConfigWidget
+{
+ Q_OBJECT
+
+public:
+ explicit DefaultGdbServerProviderConfigWidget(DefaultGdbServerProvider *);
+
+private:
+ void applyImpl();
+ void discardImpl();
+
+ void setFromProvider();
+
+ QPointer<HostWidget> m_hostWidget;
+ QPointer<QPlainTextEdit> m_initCommandsTextEdit;
+ QPointer<QPlainTextEdit> m_resetCommandsTextEdit;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // DEFAULTGDBSERVERPROVIDER_H
diff --git a/src/plugins/baremetal/gdbserverprovider.cpp b/src/plugins/baremetal/gdbserverprovider.cpp
new file mode 100644
index 00000000000..5f49c5d0853
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverprovider.cpp
@@ -0,0 +1,414 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "gdbserverprovider.h"
+#include "gdbserverprovidermanager.h"
+
+#include <utils/qtcassert.h>
+#include <utils/environment.h>
+
+#include <QCoreApplication>
+#include <QUuid>
+
+#include <QFormLayout>
+#include <QLineEdit>
+#include <QLabel>
+#include <QComboBox>
+#include <QSpinBox>
+#include <QPlainTextEdit>
+
+namespace BareMetal {
+namespace Internal {
+
+const char idKeyC[] = "BareMetal.GdbServerProvider.Id";
+const char displayNameKeyC[] = "BareMetal.GdbServerProvider.DisplayName";
+const char startupModeKeyC[] = "BareMetal.GdbServerProvider.Mode";
+const char initCommandsKeyC[] = "BareMetal.GdbServerProvider.InitCommands";
+const char resetCommandsKeyC[] = "BareMetal.GdbServerProvider.ResetCommands";
+
+static QString createId(const QString &id)
+{
+ QString newId = id.left(id.indexOf(QLatin1Char(':')));
+ newId.append(QLatin1Char(':') + QUuid::createUuid().toString());
+ return newId;
+}
+
+GdbServerProvider::GdbServerProvider(const QString &id)
+ : m_id(createId(id))
+ , m_startupMode(NoStartup)
+{
+}
+
+GdbServerProvider::GdbServerProvider(const GdbServerProvider &other)
+ : m_id(other.m_id)
+ , m_startupMode(other.m_startupMode)
+ , m_initCommands(other.m_initCommands)
+ , m_resetCommands(other.m_resetCommands)
+{
+ m_displayName = QCoreApplication::translate(
+ "BareMetal::GdbServerProvider", "Clone of %1")
+ .arg(other.displayName());
+}
+
+GdbServerProvider::~GdbServerProvider()
+{
+}
+
+QString GdbServerProvider::displayName() const
+{
+ if (m_displayName.isEmpty())
+ return typeDisplayName();
+ return m_displayName;
+}
+
+void GdbServerProvider::setDisplayName(const QString &name)
+{
+ if (m_displayName == name)
+ return;
+
+ m_displayName = name;
+ providerUpdated();
+}
+
+QString GdbServerProvider::id() const
+{
+ return m_id;
+}
+
+GdbServerProvider::StartupMode GdbServerProvider::startupMode() const
+{
+ return m_startupMode;
+}
+
+void GdbServerProvider::setStartupMode(StartupMode m)
+{
+ if (m == m_startupMode)
+ return;
+ m_startupMode = m;
+}
+
+QString GdbServerProvider::initCommands() const
+{
+ return m_initCommands;
+}
+
+void GdbServerProvider::setInitCommands(const QString &cmds)
+{
+ if (cmds == m_initCommands)
+ return;
+ m_initCommands = cmds;
+}
+
+QString GdbServerProvider::resetCommands() const
+{
+ return m_resetCommands;
+}
+
+void GdbServerProvider::setResetCommands(const QString &cmds)
+{
+ if (cmds == m_resetCommands)
+ return;
+ m_resetCommands = cmds;
+}
+
+QString GdbServerProvider::executable() const
+{
+ return QString();
+}
+
+QStringList GdbServerProvider::arguments() const
+{
+ return QStringList();
+}
+
+bool GdbServerProvider::operator==(const GdbServerProvider &other) const
+{
+ if (this == &other)
+ return true;
+
+ const QString thisId = id().left(id().indexOf(QLatin1Char(':')));
+ const QString otherId = other.id().left(other.id().indexOf(QLatin1Char(':')));
+
+ // We ignore displayname
+ return thisId == otherId
+ && m_startupMode == other.m_startupMode
+ && m_initCommands == other.m_initCommands
+ && m_resetCommands == other.m_resetCommands
+ ;
+}
+
+QVariantMap GdbServerProvider::toMap() const
+{
+ QVariantMap result;
+ result.insert(QLatin1String(idKeyC), m_id);
+ result.insert(QLatin1String(displayNameKeyC), m_displayName);
+ result.insert(QLatin1String(startupModeKeyC), m_startupMode);
+ result.insert(QLatin1String(initCommandsKeyC), m_initCommands);
+ result.insert(QLatin1String(resetCommandsKeyC), m_resetCommands);
+ return result;
+}
+
+bool GdbServerProvider::isValid() const
+{
+ return !channel().isNull();
+}
+
+bool GdbServerProvider::canStartupMode(StartupMode m) const
+{
+ return m == NoStartup;
+}
+
+void GdbServerProvider::providerUpdated()
+{
+ GdbServerProviderManager::instance()->notifyAboutUpdate(this);
+}
+
+bool GdbServerProvider::fromMap(const QVariantMap &data)
+{
+ m_id = data.value(QLatin1String(idKeyC)).toString();
+ m_displayName = data.value(QLatin1String(displayNameKeyC)).toString();
+ m_startupMode = static_cast<StartupMode>(data.value(QLatin1String(startupModeKeyC)).toInt());
+ m_initCommands = data.value(QLatin1String(initCommandsKeyC)).toString();
+ m_resetCommands = data.value(QLatin1String(resetCommandsKeyC)).toString();
+ return true;
+}
+
+QString GdbServerProviderFactory::id() const
+{
+ return m_id;
+}
+
+void GdbServerProviderFactory::setId(const QString &id)
+{
+ m_id = id;
+}
+
+QString GdbServerProviderFactory::displayName() const
+{
+ return m_displayName;
+}
+
+void GdbServerProviderFactory::setDisplayName(const QString &name)
+{
+ m_displayName = name;
+}
+
+QString GdbServerProviderFactory::idFromMap(const QVariantMap &data)
+{
+ return data.value(QLatin1String(idKeyC)).toString();
+}
+
+void GdbServerProviderFactory::idToMap(QVariantMap &data, const QString id)
+{
+ data.insert(QLatin1String(idKeyC), id);
+}
+
+GdbServerProviderConfigWidget::GdbServerProviderConfigWidget(
+ GdbServerProvider *provider)
+ : m_provider(provider)
+{
+ Q_ASSERT(provider);
+
+ m_mainLayout = new QFormLayout(this);
+ m_mainLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
+
+ m_nameLineEdit = new QLineEdit(this);
+ m_nameLineEdit->setToolTip(tr("Enter the name of the GDB server provider."));
+ m_mainLayout->addRow(tr("Name:"), m_nameLineEdit);
+
+ m_startupModeComboBox = new QComboBox(this);
+ m_startupModeComboBox->setToolTip(tr("Choose the desired startup mode "
+ "of the GDB server provider."));
+ m_mainLayout->addRow(tr("Startup mode:"), m_startupModeComboBox);
+
+ populateStartupModes();
+ setFromProvider();
+
+ connect(m_nameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(dirty()));
+ connect(m_startupModeComboBox, SIGNAL(currentIndexChanged(int)), SIGNAL(dirty()));
+}
+
+void GdbServerProviderConfigWidget::apply()
+{
+ m_provider->setDisplayName(m_nameLineEdit->text());
+ m_provider->setStartupMode(startupMode());
+
+ applyImpl();
+}
+
+void GdbServerProviderConfigWidget::discard()
+{
+ m_nameLineEdit->setText(m_provider->displayName());
+ discardImpl();
+}
+
+GdbServerProvider *GdbServerProviderConfigWidget::provider() const
+{
+ return m_provider;
+}
+
+void GdbServerProviderConfigWidget::addErrorLabel()
+{
+ if (!m_errorLabel) {
+ m_errorLabel = new QLabel;
+ m_errorLabel->setVisible(false);
+ }
+ m_mainLayout->addRow(m_errorLabel);
+}
+
+GdbServerProvider::StartupMode GdbServerProviderConfigWidget::startupModeFromIndex(
+ int idx) const
+{
+ return static_cast<GdbServerProvider::StartupMode>(
+ m_startupModeComboBox->itemData(idx).toInt());
+}
+
+GdbServerProvider::StartupMode GdbServerProviderConfigWidget::startupMode() const
+{
+ const int idx = m_startupModeComboBox->currentIndex();
+ return startupModeFromIndex(idx);
+}
+
+void GdbServerProviderConfigWidget::setStartupMode(GdbServerProvider::StartupMode m)
+{
+ for (int idx = 0; idx < m_startupModeComboBox->count(); ++idx) {
+ if (m == startupModeFromIndex(idx)) {
+ m_startupModeComboBox->setCurrentIndex(idx);
+ break;
+ }
+ }
+}
+
+void GdbServerProviderConfigWidget::populateStartupModes()
+{
+ for (int i = 0; i < GdbServerProvider::StartupModesCount; ++i) {
+ const auto m = static_cast<GdbServerProvider::StartupMode>(i);
+ if (!m_provider->canStartupMode(m))
+ continue;
+
+ const int idx = m_startupModeComboBox->count();
+ m_startupModeComboBox->insertItem(
+ idx,
+ (m == GdbServerProvider::NoStartup)
+ ? tr("No startup")
+ : ((m == GdbServerProvider::StartupOnNetwork)
+ ? tr("Startup in TCP/IP mode")
+ : tr("Startup in Pipe mode")),
+ m);
+ }
+}
+
+void GdbServerProviderConfigWidget::setErrorMessage(const QString &m)
+{
+ QTC_ASSERT(m_errorLabel, return);
+ if (m.isEmpty()) {
+ clearErrorMessage();
+ } else {
+ m_errorLabel->setText(m);
+ m_errorLabel->setStyleSheet(QLatin1String("background-color: \"red\""));
+ m_errorLabel->setVisible(true);
+ }
+}
+
+void GdbServerProviderConfigWidget::clearErrorMessage()
+{
+ QTC_ASSERT(m_errorLabel, return);
+ m_errorLabel->clear();
+ m_errorLabel->setStyleSheet(QString());
+ m_errorLabel->setVisible(false);
+}
+
+void GdbServerProviderConfigWidget::setFromProvider()
+{
+ const bool b = blockSignals(true);
+ m_nameLineEdit->setText(m_provider->displayName());
+ setStartupMode(m_provider->startupMode());
+ blockSignals(b);
+}
+
+QString GdbServerProviderConfigWidget::defaultInitCommandsTooltip()
+{
+ return QCoreApplication::translate("BareMetal",
+ "Enter GDB commands to reset of the board, "
+ "and to write the nonvolatile memory.");
+}
+
+QString GdbServerProviderConfigWidget::defaultResetCommandsTooltip()
+{
+ return QCoreApplication::translate("BareMetal",
+ "Enter GDB commands to hardware reset. "
+ "The MCU should be halted after this commands.");
+}
+
+HostWidget::HostWidget(QWidget *parent)
+ : QWidget(parent)
+{
+ m_hostLineEdit = new QLineEdit(this);
+ m_hostLineEdit->setToolTip(tr("Enter TCP/IP hostname of the GDB server provider, "
+ "like \"localhost\" or \"192.0.2.1\"."));
+ m_portSpinBox = new QSpinBox(this);
+ m_portSpinBox->setRange(0, 65535);
+ m_portSpinBox->setToolTip(tr("Enter TCP/IP port which will be listened by "
+ "the GDB server provider."));
+ auto layout = new QHBoxLayout(this);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->addWidget(m_hostLineEdit);
+ layout->addWidget(m_portSpinBox);
+
+ connect(m_hostLineEdit, SIGNAL(textChanged(QString)), SIGNAL(dataChanged()));
+ connect(m_portSpinBox, SIGNAL(valueChanged(int)), SIGNAL(dataChanged()));
+}
+
+void HostWidget::setHost(const QString &host)
+{
+ const bool b = blockSignals(true);
+ m_hostLineEdit->setText(host);
+ blockSignals(b);
+}
+
+QString HostWidget::host() const
+{
+ return m_hostLineEdit->text();
+}
+
+void HostWidget::setPort(const quint16 &port)
+{
+ const bool b = blockSignals(true);
+ m_portSpinBox->setValue(port);
+ blockSignals(b);
+}
+
+quint16 HostWidget::port() const
+{
+ return m_portSpinBox->value();
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/gdbserverprovider.h b/src/plugins/baremetal/gdbserverprovider.h
new file mode 100644
index 00000000000..d3d7f5d9454
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverprovider.h
@@ -0,0 +1,208 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 GDBSERVERPROVIDER_H
+#define GDBSERVERPROVIDER_H
+
+#include <QObject>
+#include <QPointer>
+#include <QVariantMap>
+
+#include <QWidget>
+
+#include <utils/fileutils.h>
+
+QT_BEGIN_NAMESPACE
+class QFormLayout;
+class QLineEdit;
+class QLabel;
+class QComboBox;
+class QSpinBox;
+class QPlainTextEdit;
+QT_END_NAMESPACE
+
+namespace BareMetal {
+namespace Internal {
+
+class GdbServerProviderConfigWidget;
+class GdbServerProviderFactory;
+class GdbServerProviderManager;
+
+class GdbServerProvider
+{
+public:
+ enum StartupMode {
+ NoStartup = 0,
+ StartupOnNetwork,
+ StartupOnPipe,
+ StartupModesCount
+ };
+
+ virtual ~GdbServerProvider();
+
+ QString displayName() const;
+ void setDisplayName(const QString &name);
+
+ QString id() const;
+
+ StartupMode startupMode() const;
+ QString initCommands() const;
+ QString resetCommands() const;
+
+ virtual bool operator==(const GdbServerProvider &) const;
+
+ virtual QString typeDisplayName() const = 0;
+
+ virtual GdbServerProviderConfigWidget *configurationWidget() = 0;
+
+ virtual QString channel() const = 0;
+ virtual GdbServerProvider *clone() const = 0;
+
+ virtual QVariantMap toMap() const;
+
+ virtual QString executable() const;
+ virtual QStringList arguments() const;
+
+ virtual bool isValid() const;
+ virtual bool canStartupMode(StartupMode) const;
+
+protected:
+ explicit GdbServerProvider(const QString &id);
+ explicit GdbServerProvider(const GdbServerProvider &);
+
+ void setStartupMode(StartupMode);
+ void setInitCommands(const QString &);
+ void setResetCommands(const QString &);
+
+ void providerUpdated();
+
+ virtual bool fromMap(const QVariantMap &data);
+
+private:
+ QString m_id;
+ mutable QString m_displayName;
+ StartupMode m_startupMode;
+ QString m_initCommands;
+ QString m_resetCommands;
+
+ friend class GdbServerProviderConfigWidget;
+};
+
+class GdbServerProviderFactory : public QObject
+{
+ Q_OBJECT
+
+public:
+ QString id() const;
+ QString displayName() const;
+
+ virtual GdbServerProvider *create() = 0;
+
+ virtual bool canRestore(const QVariantMap &data) = 0;
+ virtual GdbServerProvider *restore(const QVariantMap &data) = 0;
+
+ static QString idFromMap(const QVariantMap &data);
+ static void idToMap(QVariantMap &data, const QString id);
+
+protected:
+ void setId(const QString &id);
+ void setDisplayName(const QString &name);
+
+private:
+ QString m_displayName;
+ QString m_id;
+};
+
+class GdbServerProviderConfigWidget : public QWidget
+{
+ Q_OBJECT
+
+public:
+ explicit GdbServerProviderConfigWidget(GdbServerProvider *);
+ GdbServerProvider *provider() const;
+ void apply();
+ void discard();
+
+signals:
+ void dirty();
+
+protected slots:
+ void setErrorMessage(const QString &);
+ void clearErrorMessage();
+
+protected:
+ virtual void applyImpl() = 0;
+ virtual void discardImpl() = 0;
+
+ void addErrorLabel();
+
+ GdbServerProvider::StartupMode startupModeFromIndex(int idx) const;
+ GdbServerProvider::StartupMode startupMode() const;
+ void setStartupMode(GdbServerProvider::StartupMode mode);
+ void populateStartupModes();
+
+ static QString defaultInitCommandsTooltip();
+ static QString defaultResetCommandsTooltip();
+
+ QPointer<QFormLayout> m_mainLayout;
+ QPointer<QLineEdit> m_nameLineEdit;
+ QPointer<QComboBox> m_startupModeComboBox;
+
+private:
+ void setFromProvider();
+
+ GdbServerProvider *m_provider;
+ QPointer<QLabel> m_errorLabel;
+};
+
+class HostWidget : public QWidget
+{
+ Q_OBJECT
+
+public:
+ explicit HostWidget(QWidget *parent = 0);
+
+ void setHost(const QString &host);
+ QString host() const;
+ void setPort(const quint16 &port);
+ quint16 port() const;
+
+signals:
+ void dataChanged();
+
+private:
+ QPointer<QLineEdit> m_hostLineEdit;
+ QPointer<QSpinBox> m_portSpinBox;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // GDBSERVERPROVIDER_H
diff --git a/src/plugins/baremetal/gdbserverproviderchooser.cpp b/src/plugins/baremetal/gdbserverproviderchooser.cpp
new file mode 100644
index 00000000000..8f52198a094
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverproviderchooser.cpp
@@ -0,0 +1,124 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "gdbserverproviderchooser.h"
+
+#include "gdbserverprovidermanager.h"
+#include "gdbserverprovider.h"
+#include "baremetalconstants.h"
+
+#include <coreplugin/icore.h>
+
+#include <QComboBox>
+#include <QHBoxLayout>
+#include <QPushButton>
+#include <QSettings>
+
+namespace BareMetal {
+namespace Internal {
+
+GdbServerProviderChooser::GdbServerProviderChooser(
+ bool useManageButton, QWidget *parent)
+ : QWidget(parent)
+{
+ m_chooser = new QComboBox(this);
+ m_chooser->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
+ m_manageButton = new QPushButton(tr("Manage..."), this);
+ m_manageButton->setEnabled(useManageButton);
+ m_manageButton->setVisible(useManageButton);
+
+ auto layout = new QHBoxLayout(this);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->addWidget(m_chooser);
+ layout->addWidget(m_manageButton);
+ setFocusProxy(m_manageButton);
+
+ connect(m_chooser, SIGNAL(currentIndexChanged(int)),
+ SLOT(currentIndexChanged(int)));
+ connect(m_manageButton, SIGNAL(clicked()),
+ SLOT(manageButtonClicked()));
+ connect(GdbServerProviderManager::instance(), SIGNAL(providersChanged()),
+ SLOT(populate()));
+}
+
+QString GdbServerProviderChooser::currentProviderId() const
+{
+ const int idx = m_chooser->currentIndex();
+ return qvariant_cast<QString>(m_chooser->itemData(idx));
+}
+
+void GdbServerProviderChooser::setCurrentProviderId(const QString &id)
+{
+ for (int i = 0; i < m_chooser->count(); ++i) {
+ if (id != qvariant_cast<QString>(m_chooser->itemData(i)))
+ continue;
+ m_chooser->setCurrentIndex(i);
+ }
+}
+
+void GdbServerProviderChooser::manageButtonClicked()
+{
+ Core::ICore::showOptionsDialog(Constants::BAREMETAL_SETTINGS_CATEGORY,
+ Constants::GDB_PROVIDERS_SETTINGS_ID, this);
+}
+
+void GdbServerProviderChooser::currentIndexChanged(int index)
+{
+ Q_UNUSED(index);
+ emit providerChanged();
+}
+
+bool GdbServerProviderChooser::providerMatches(const GdbServerProvider *provider) const
+{
+ return provider->isValid();
+}
+
+QString GdbServerProviderChooser::providerText(const GdbServerProvider *provider) const
+{
+ return provider->displayName();
+}
+
+void GdbServerProviderChooser::populate()
+{
+ const bool b = m_chooser->blockSignals(true);
+ m_chooser->clear();
+ m_chooser->addItem(tr("None"));
+
+ foreach (const GdbServerProvider *p,
+ GdbServerProviderManager::instance()->providers()) {
+ if (!providerMatches(p))
+ continue;
+ m_chooser->addItem(providerText(p), qVariantFromValue(p->id()));
+ }
+ m_chooser->blockSignals(b);
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/gdbserverproviderchooser.h b/src/plugins/baremetal/gdbserverproviderchooser.h
new file mode 100644
index 00000000000..284f117a3fc
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverproviderchooser.h
@@ -0,0 +1,83 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 GDBSERVERPROVIDERCHOOSER_H
+#define GDBSERVERPROVIDERCHOOSER_H
+
+#include <QPointer>
+
+#include <QWidget>
+
+QT_BEGIN_NAMESPACE
+class QComboBox;
+class QPushButton;
+QT_END_NAMESPACE
+
+namespace Core { class Id; }
+
+namespace BareMetal {
+namespace Internal {
+
+class GdbServerProvider;
+
+class GdbServerProviderChooser : public QWidget
+{
+ Q_OBJECT
+
+public:
+ explicit GdbServerProviderChooser(
+ bool useManageButton = true, QWidget *parent = 0);
+
+ QString currentProviderId() const;
+ void setCurrentProviderId(const QString &id);
+
+signals:
+ void providerChanged();
+
+public slots:
+ void populate();
+
+private slots:
+ void currentIndexChanged(int index);
+ void manageButtonClicked();
+
+protected:
+ bool providerMatches(const GdbServerProvider *) const;
+ QString providerText(const GdbServerProvider *) const;
+
+private:
+ QPointer<QComboBox> m_chooser;
+ QPointer<QPushButton> m_manageButton;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // GDBSERVERPROVIDERCHOOSER_H
diff --git a/src/plugins/baremetal/gdbserverprovidermanager.cpp b/src/plugins/baremetal/gdbserverprovidermanager.cpp
new file mode 100644
index 00000000000..16f0cbb54c9
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverprovidermanager.cpp
@@ -0,0 +1,215 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "gdbserverprovidermanager.h"
+#include "gdbserverprovider.h"
+
+#include "openocdgdbserverprovider.h"
+#include "defaultgdbserverprovider.h"
+#include "stlinkutilgdbserverprovider.h"
+
+#include <coreplugin/icore.h>
+
+#include <extensionsystem/pluginmanager.h>
+
+#include <utils/persistentsettings.h>
+#include <utils/qtcassert.h>
+#include <utils/algorithm.h>
+
+#include <QDir>
+
+namespace BareMetal {
+namespace Internal {
+
+const char dataKeyC[] = "GdbServerProvider.";
+const char countKeyC[] = "GdbServerProvider.Count";
+const char fileVersionKeyC[] = "Version";
+const char fileNameKeyC[] = "/qtcreator/gdbserverproviders.xml";
+
+static Utils::FileName settingsFileName(const QString &path)
+{
+ const QFileInfo settingsLocation(Core::ICore::settings()->fileName());
+ return Utils::FileName::fromString(settingsLocation.absolutePath() + path);
+}
+
+static QList<GdbServerProviderFactory *> createFactories()
+{
+ QList<GdbServerProviderFactory *> result;
+ result << new DefaultGdbServerProviderFactory
+ << new OpenOcdGdbServerProviderFactory
+ << new StLinkUtilGdbServerProviderFactory
+ ;
+ return result;
+}
+
+GdbServerProviderManager *GdbServerProviderManager::m_instance = 0;
+
+GdbServerProviderManager::GdbServerProviderManager(QObject *parent)
+ : QObject(parent)
+ , m_configFile(settingsFileName(QLatin1String(fileNameKeyC)))
+ , m_factories(createFactories())
+{
+ m_writer = new Utils::PersistentSettingsWriter(
+ m_configFile, QLatin1String("QtCreatorGdbServerProviders"));
+
+ connect(Core::ICore::instance(), &Core::ICore::saveSettingsRequested,
+ this, &GdbServerProviderManager::saveProviders);
+
+ connect(this, SIGNAL(providerAdded(GdbServerProvider*)),
+ SIGNAL(providersChanged()));
+ connect(this, SIGNAL(providerRemoved(GdbServerProvider*)),
+ SIGNAL(providersChanged()));
+ connect(this, SIGNAL(providerUpdated(GdbServerProvider*)),
+ SIGNAL(providersChanged()));
+}
+
+GdbServerProviderManager::~GdbServerProviderManager()
+{
+ qDeleteAll(m_providers);
+ m_providers.clear();
+ delete m_writer;
+ m_instance = 0;
+}
+
+GdbServerProviderManager *GdbServerProviderManager::instance()
+{
+ if (!m_instance)
+ m_instance = new GdbServerProviderManager;
+ return m_instance;
+}
+
+void GdbServerProviderManager::restoreProviders()
+{
+ Utils::PersistentSettingsReader reader;
+ if (!reader.load(m_configFile))
+ return;
+
+ const QVariantMap data = reader.restoreValues();
+ const int version = data.value(QLatin1String(fileVersionKeyC), 0).toInt();
+ if (version < 1)
+ return;
+
+ const int count = data.value(QLatin1String(countKeyC), 0).toInt();
+ for (int i = 0; i < count; ++i) {
+ const QString key = QString::fromLatin1(dataKeyC) + QString::number(i);
+ if (!data.contains(key))
+ break;
+
+ const QVariantMap map = data.value(key).toMap();
+ bool restored = false;
+ foreach (GdbServerProviderFactory *f, m_factories) {
+ if (f->canRestore(map)) {
+ if (GdbServerProvider *p = f->restore(map)) {
+ registerProvider(p);
+ restored = true;
+ break;
+ }
+ }
+ }
+ if (!restored)
+ qWarning("Warning: Unable to restore provider '%s' stored in %s.",
+ qPrintable(GdbServerProviderFactory::idFromMap(map)),
+ qPrintable(m_configFile.toUserOutput()));
+ }
+
+ emit providersLoaded();
+}
+
+void GdbServerProviderManager::saveProviders()
+{
+ QVariantMap data;
+ data.insert(QLatin1String(fileVersionKeyC), 1);
+
+ int count = 0;
+ foreach (const GdbServerProvider *p, m_providers) {
+ if (p->isValid()) {
+ const QVariantMap tmp = p->toMap();
+ if (tmp.isEmpty())
+ continue;
+ const QString key = QString::fromLatin1(dataKeyC) + QString::number(count);
+ data.insert(key, tmp);
+ ++count;
+ }
+ }
+ data.insert(QLatin1String(countKeyC), count);
+ m_writer->save(data, Core::ICore::mainWindow());
+}
+
+QList<GdbServerProvider *> GdbServerProviderManager::providers() const
+{
+ return m_providers;
+}
+
+QList<GdbServerProviderFactory *> GdbServerProviderManager::factories() const
+{
+ return m_factories;
+}
+
+GdbServerProvider *GdbServerProviderManager::findProvider(const QString &id) const
+{
+ if (id.isEmpty())
+ return 0;
+
+ return Utils::findOrDefault(m_providers, Utils::equal(&GdbServerProvider::id, id));
+}
+
+void GdbServerProviderManager::notifyAboutUpdate(GdbServerProvider *provider)
+{
+ if (!provider || !m_providers.contains(provider))
+ return;
+ emit providerUpdated(provider);
+}
+
+bool GdbServerProviderManager::registerProvider(GdbServerProvider *provider)
+{
+ if (!provider || m_providers.contains(provider))
+ return true;
+ foreach (const GdbServerProvider *current, m_providers) {
+ if (*provider == *current)
+ return false;
+ QTC_ASSERT(current->id() != provider->id(), return false);
+ }
+
+ m_providers.append(provider);
+ emit providerAdded(provider);
+ return true;
+}
+
+void GdbServerProviderManager::deregisterProvider(GdbServerProvider *provider)
+{
+ if (!provider || !m_providers.contains(provider))
+ return;
+ m_providers.removeOne(provider);
+ emit providerRemoved(provider);
+ delete provider;
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/gdbserverprovidermanager.h b/src/plugins/baremetal/gdbserverprovidermanager.h
new file mode 100644
index 00000000000..9de36f21777
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverprovidermanager.h
@@ -0,0 +1,92 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 GDBSERVERPROVIDERMANAGER_H
+#define GDBSERVERPROVIDERMANAGER_H
+
+#include <QObject>
+#include <QList>
+
+#include <utils/fileutils.h>
+
+namespace Utils { class PersistentSettingsWriter; }
+
+namespace BareMetal {
+namespace Internal {
+
+class BareMetalPlugin;
+class GdbServerProvider;
+class GdbServerProviderFactory;
+
+class GdbServerProviderManager : public QObject
+{
+ Q_OBJECT
+
+public:
+ static GdbServerProviderManager *instance();
+ ~GdbServerProviderManager();
+
+ QList<GdbServerProvider *> providers() const;
+ QList<GdbServerProviderFactory *> factories() const;
+ GdbServerProvider *findProvider(const QString &id) const;
+ bool registerProvider(GdbServerProvider *);
+ void deregisterProvider(GdbServerProvider *);
+
+public slots:
+ void saveProviders();
+
+signals:
+ void providerAdded(GdbServerProvider *);
+ void providerRemoved(GdbServerProvider *);
+ void providerUpdated(GdbServerProvider *);
+ void providersChanged();
+ void providersLoaded();
+
+private:
+ explicit GdbServerProviderManager(QObject *parent = 0);
+
+ void restoreProviders();
+ void notifyAboutUpdate(GdbServerProvider *);
+
+ Utils::PersistentSettingsWriter *m_writer;
+ QList<GdbServerProvider *> m_providers;
+ const Utils::FileName m_configFile;
+ const QList<GdbServerProviderFactory *> m_factories;
+
+ static GdbServerProviderManager *m_instance;
+
+ friend class BareMetalPlugin; // for constructor
+ friend class GdbServerProvider;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // GDBSERVERPROVIDERMANAGER_H
diff --git a/src/plugins/baremetal/gdbserverproviderprocess.cpp b/src/plugins/baremetal/gdbserverproviderprocess.cpp
new file mode 100644
index 00000000000..a7351ffaa3c
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverproviderprocess.cpp
@@ -0,0 +1,134 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "gdbserverproviderprocess.h"
+
+#include <projectexplorer/devicesupport/idevice.h>
+
+#include <utils/environment.h>
+#include <utils/qtcprocess.h>
+#include <utils/qtcassert.h>
+
+#include <QStringList>
+
+namespace BareMetal {
+namespace Internal {
+
+GdbServerProviderProcess::GdbServerProviderProcess(
+ const QSharedPointer<const ProjectExplorer::IDevice> &device,
+ QObject *parent)
+ : ProjectExplorer::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, &QProcess::readyReadStandardOutput,
+ this, &ProjectExplorer::DeviceProcess::readyReadStandardOutput);
+ connect(m_process, &QProcess::readyReadStandardError,
+ this, &ProjectExplorer::DeviceProcess::readyReadStandardError);
+ connect(m_process, &QProcess::started,
+ this, &ProjectExplorer::DeviceProcess::started);
+}
+
+void GdbServerProviderProcess::start(const QString &executable, const QStringList &arguments)
+{
+ QTC_ASSERT(m_process->state() == QProcess::NotRunning, return);
+ m_process->start(executable, arguments);
+}
+
+void GdbServerProviderProcess::interrupt()
+{
+ device()->signalOperation()->interruptProcess(Utils::qPidToPid(m_process->pid()));
+}
+
+void GdbServerProviderProcess::terminate()
+{
+ m_process->terminate();
+}
+
+void GdbServerProviderProcess::kill()
+{
+ m_process->kill();
+}
+
+QProcess::ProcessState GdbServerProviderProcess::state() const
+{
+ return m_process->state();
+}
+
+QProcess::ExitStatus GdbServerProviderProcess::exitStatus() const
+{
+ return m_process->exitStatus();
+}
+
+int GdbServerProviderProcess::exitCode() const
+{
+ return m_process->exitCode();
+}
+
+QString GdbServerProviderProcess::errorString() const
+{
+ return m_process->errorString();
+}
+
+Utils::Environment GdbServerProviderProcess::environment() const
+{
+ return Utils::Environment(m_process->processEnvironment().toStringList());
+}
+
+void GdbServerProviderProcess::setEnvironment(const Utils::Environment &env)
+{
+ m_process->setProcessEnvironment(env.toProcessEnvironment());
+}
+
+void GdbServerProviderProcess::setWorkingDirectory(const QString &dir)
+{
+ m_process->setWorkingDirectory(dir);
+}
+
+QByteArray GdbServerProviderProcess::readAllStandardOutput()
+{
+ return m_process->readAllStandardOutput();
+}
+
+QByteArray GdbServerProviderProcess::readAllStandardError()
+{
+ return m_process->readAllStandardError();
+}
+
+qint64 GdbServerProviderProcess::write(const QByteArray &data)
+{
+ return m_process->write(data);
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/gdbserverproviderprocess.h b/src/plugins/baremetal/gdbserverproviderprocess.h
new file mode 100644
index 00000000000..dcfbb229fb6
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverproviderprocess.h
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 GDBSERVERPROVIDERPROCESS_H
+#define GDBSERVERPROVIDERPROCESS_H
+
+#include <projectexplorer/devicesupport/deviceprocess.h>
+
+namespace BareMetal {
+namespace Internal {
+
+class GdbServerProviderProcess : public ProjectExplorer::DeviceProcess
+{
+ Q_OBJECT
+public:
+ explicit GdbServerProviderProcess(
+ const QSharedPointer<const ProjectExplorer::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 &);
+ void setWorkingDirectory(const QString &);
+
+ QByteArray readAllStandardOutput();
+ QByteArray readAllStandardError();
+
+ qint64 write(const QByteArray &data);
+
+private:
+ QProcess * const m_process;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // GDBSERVERPROVIDERPROCESS_H
diff --git a/src/plugins/baremetal/gdbserverproviderssettingspage.cpp b/src/plugins/baremetal/gdbserverproviderssettingspage.cpp
new file mode 100644
index 00000000000..043cc33c70e
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverproviderssettingspage.cpp
@@ -0,0 +1,621 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "gdbserverproviderssettingspage.h"
+#include "gdbserverprovider.h"
+#include "baremetalconstants.h"
+#include "gdbserverprovidermanager.h"
+
+#include <coreplugin/icore.h>
+#include <extensionsystem/pluginmanager.h>
+
+#include <utils/detailswidget.h>
+#include <utils/qtcassert.h>
+#include <utils/algorithm.h>
+
+#include <QApplication>
+#include <QAction>
+#include <QHBoxLayout>
+#include <QHeaderView>
+#include <QItemSelectionModel>
+#include <QMenu>
+#include <QMessageBox>
+#include <QPushButton>
+#include <QSignalMapper>
+#include <QSpacerItem>
+#include <QTextStream>
+#include <QTreeView>
+#include <QVBoxLayout>
+
+namespace BareMetal {
+namespace Internal {
+
+class GdbServerProviderNode
+{
+public:
+ explicit GdbServerProviderNode(GdbServerProviderNode *parent,
+ GdbServerProvider *provider = 0,
+ bool changed = false);
+ ~GdbServerProviderNode();
+
+ GdbServerProviderNode *parent;
+ QList<GdbServerProviderNode *> childNodes;
+ GdbServerProvider *provider;
+ GdbServerProviderConfigWidget *widget;
+ bool changed;
+};
+
+GdbServerProviderNode::GdbServerProviderNode(
+ GdbServerProviderNode *parent,
+ GdbServerProvider *provider,
+ bool changed)
+ : parent(parent)
+ , provider(provider)
+ , changed(changed)
+{
+ if (parent)
+ parent->childNodes.append(this);
+
+ widget = provider ? provider->configurationWidget() : 0;
+}
+
+GdbServerProviderNode::~GdbServerProviderNode()
+{
+ // Do not delete provider, we do not own it.
+
+ for (int i = childNodes.size(); --i >= 0; ) {
+ GdbServerProviderNode *child = childNodes.at(i);
+ child->parent = 0;
+ delete child;
+ }
+
+ if (parent)
+ parent->childNodes.removeOne(this);
+}
+
+GdbServerProviderModel::GdbServerProviderModel(QObject *parent)
+ : QAbstractItemModel(parent)
+ , m_root(new GdbServerProviderNode(0))
+{
+ const GdbServerProviderManager *manager = GdbServerProviderManager::instance();
+
+ connect(manager, &GdbServerProviderManager::providerAdded,
+ this, &GdbServerProviderModel::addProvider);
+ connect(manager, &GdbServerProviderManager::providerRemoved,
+ this, &GdbServerProviderModel::removeProvider);
+
+ foreach (GdbServerProvider *p, manager->providers())
+ addProvider(p);
+}
+
+GdbServerProviderModel::~GdbServerProviderModel()
+{
+ delete m_root;
+}
+
+QModelIndex GdbServerProviderModel::index(
+ int row, int column, const QModelIndex &parent) const
+{
+ if (!parent.isValid()) {
+ if (row >= 0 && row < m_root->childNodes.count())
+ return createIndex(row, column, m_root->childNodes.at(row));
+ }
+
+ return QModelIndex();
+}
+
+QModelIndex GdbServerProviderModel::index(
+ const QModelIndex &topIdx, const GdbServerProvider *provider) const
+{
+ const GdbServerProviderNode *current =
+ topIdx.isValid() ? nodeFromIndex(topIdx) : m_root;
+ QTC_ASSERT(current, return QModelIndex());
+
+ if (current->provider == provider)
+ return topIdx;
+
+ for (int i = 0; i < current->childNodes.count(); ++i) {
+ const QModelIndex idx = index(index(current->childNodes.at(i)), provider);
+ if (idx.isValid())
+ return idx;
+ }
+ return QModelIndex();
+}
+
+QModelIndex GdbServerProviderModel::parent(const QModelIndex &idx) const
+{
+ const GdbServerProviderNode *n = nodeFromIndex(idx);
+ return (n->parent == m_root) ? QModelIndex() : index(n->parent);
+}
+
+int GdbServerProviderModel::rowCount(const QModelIndex &parent) const
+{
+ if (!parent.isValid())
+ return m_root->childNodes.count();
+
+ const GdbServerProviderNode *n = nodeFromIndex(parent);
+ return n->childNodes.count();
+}
+
+int GdbServerProviderModel::columnCount(const QModelIndex &parent) const
+{
+ Q_UNUSED(parent);
+ return ColumnsCount;
+}
+
+QVariant GdbServerProviderModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid())
+ return QVariant();
+
+ const GdbServerProviderNode *n = nodeFromIndex(index);
+ QTC_ASSERT(n, return QVariant());
+
+ if (!n->provider)
+ return QVariant();
+
+ if (role == Qt::FontRole) {
+ QFont f = QApplication::font();
+ if (n->changed)
+ f.setBold(true);
+ return f;
+ } else if (role == Qt::DisplayRole) {
+ return (index.column() == NameIndex)
+ ? n->provider->displayName()
+ : n->provider->typeDisplayName();
+ }
+
+ // FIXME: Need to handle also and ToolTipRole role?
+
+ return QVariant();
+}
+
+Qt::ItemFlags GdbServerProviderModel::flags(const QModelIndex &index) const
+{
+ if (!index.isValid())
+ return 0;
+
+ const GdbServerProviderNode *n = nodeFromIndex(index);
+ Q_ASSERT(n);
+ return (n->provider) ? (Qt::ItemIsEnabled | Qt::ItemIsSelectable)
+ : Qt::ItemIsEnabled;
+}
+
+QVariant GdbServerProviderModel::headerData(
+ int section, Qt::Orientation orientation, int role) const
+{
+ if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
+ return section == NameIndex ? tr("Name") : tr("Type");
+ return QVariant();
+}
+
+GdbServerProvider *GdbServerProviderModel::provider(
+ const QModelIndex &index) const
+{
+ if (!index.isValid())
+ return 0;
+
+ const GdbServerProviderNode *n = nodeFromIndex(index);
+ Q_ASSERT(n);
+ return n->provider;
+}
+
+GdbServerProviderConfigWidget *GdbServerProviderModel::widget(
+ const QModelIndex &index) const
+{
+ if (!index.isValid())
+ return 0;
+
+ const GdbServerProviderNode *n = nodeFromIndex(index);
+ Q_ASSERT(n);
+ return n->widget;
+}
+
+bool GdbServerProviderModel::isDirty() const
+{
+ return Utils::anyOf(m_root->childNodes, [](GdbServerProviderNode *n) {
+ return n->changed;
+ });
+}
+
+bool GdbServerProviderModel::isDirty(GdbServerProvider *p) const
+{
+ return Utils::anyOf(m_root->childNodes, [p](GdbServerProviderNode *n) {
+ return n->provider == p && n->changed;
+ });
+}
+
+void GdbServerProviderModel::setDirty()
+{
+ const auto w = qobject_cast<GdbServerProviderConfigWidget *>(sender());
+ foreach (GdbServerProviderNode *n, m_root->childNodes) {
+ if (n->widget == w) {
+ n->changed = true;
+ emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
+ }
+ }
+}
+
+void GdbServerProviderModel::apply()
+{
+ // Remove unused providers
+ foreach (const GdbServerProviderNode *n, m_toRemoveNodes) {
+ Q_ASSERT(!n->parent);
+ GdbServerProviderManager::instance()->deregisterProvider(n->provider);
+ }
+ Q_ASSERT(m_toRemoveNodes.isEmpty());
+
+ // Update providers
+ foreach (GdbServerProviderNode *n, m_root->childNodes) {
+ Q_ASSERT(n);
+
+ if (!n->changed)
+ continue;
+
+ Q_ASSERT(n->provider);
+ if (n->widget)
+ n->widget->apply();
+
+ n->changed = false;
+
+ emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
+ }
+
+ // Add new (and already updated) providers
+ QStringList removedProviders;
+ foreach (const GdbServerProviderNode *n, m_toAddNodes) {
+ if (!GdbServerProviderManager::instance()->registerProvider(n->provider))
+ removedProviders << n->provider->displayName();
+ }
+
+ qDeleteAll(m_toAddNodes);
+
+ if (removedProviders.count() == 1) {
+ QMessageBox::warning(Core::ICore::dialogParent(),
+ tr("Duplicate Providers Detected"),
+ tr("The following provider was already configured:<br>"
+ "&nbsp;%1<br>"
+ "It was not configured again.")
+ .arg(removedProviders.at(0)));
+
+ } else if (!removedProviders.isEmpty()) {
+ QMessageBox::warning(Core::ICore::dialogParent(),
+ tr("Duplicate Providers Detected"),
+ tr("The following providers were already configured:<br>"
+ "&nbsp;%1<br>"
+ "They were not configured again.")
+ .arg(removedProviders.join(QLatin1String(",<br>&nbsp;"))));
+ }
+}
+
+void GdbServerProviderModel::markForRemoval(GdbServerProvider *provider)
+{
+ GdbServerProviderNode *n = findNode(m_root->childNodes, provider);
+ QTC_ASSERT(n, return);
+
+ const int row = m_root->childNodes.indexOf(n);
+ emit beginRemoveRows(index(m_root), row, row);
+ m_root->childNodes.removeOne(n);
+ n->parent = 0;
+
+ if (m_toAddNodes.contains(n)) {
+ delete n->provider;
+ n->provider = 0;
+ m_toAddNodes.removeOne(n);
+ delete n;
+ } else {
+ m_toRemoveNodes.append(n);
+ }
+
+ emit endRemoveRows();
+}
+
+void GdbServerProviderModel::markForAddition(GdbServerProvider *provider)
+{
+ const int pos = m_root->childNodes.size();
+ emit beginInsertRows(index(m_root), pos, pos);
+ GdbServerProviderNode *n = createNode(m_root, provider, true);
+ m_toAddNodes.append(n);
+ emit endInsertRows();
+}
+
+QModelIndex GdbServerProviderModel::index(
+ GdbServerProviderNode *n, int column) const
+{
+ if (n == m_root)
+ return QModelIndex();
+
+ if (n->parent == m_root)
+ return index(m_root->childNodes.indexOf(n), column, QModelIndex());
+
+ return index(n->parent->childNodes.indexOf(n),
+ column, index(n->parent));
+}
+
+GdbServerProviderNode *GdbServerProviderModel::createNode(
+ GdbServerProviderNode *parent,
+ GdbServerProvider *provider, bool changed)
+{
+ auto n = new GdbServerProviderNode(parent, provider, changed);
+ if (n->widget) {
+ connect(n->widget, &GdbServerProviderConfigWidget::dirty,
+ this, &GdbServerProviderModel::setDirty);
+ }
+ return n;
+}
+
+GdbServerProviderNode *GdbServerProviderModel::nodeFromIndex(
+ const QModelIndex &index) const
+{
+ return static_cast<GdbServerProviderNode *>(index.internalPointer());
+}
+
+GdbServerProviderNode *GdbServerProviderModel::findNode(
+ const QList<GdbServerProviderNode *> &container,
+ const GdbServerProvider *provider)
+{
+ return Utils::findOrDefault(container, [provider](GdbServerProviderNode *n) {
+ return n->provider == provider;
+ });
+}
+
+void GdbServerProviderModel::addProvider(GdbServerProvider *provider)
+{
+ GdbServerProviderNode *n = findNode(m_toAddNodes, provider);
+ if (n) {
+ m_toAddNodes.removeOne(n);
+ // do not delete n: Still used elsewhere!
+ return;
+ }
+
+ const int row = m_root->childNodes.count();
+
+ beginInsertRows(index(m_root), row, row);
+ createNode(m_root, provider, false);
+ endInsertRows();
+
+ emit providerStateChanged();
+}
+
+void GdbServerProviderModel::removeProvider(GdbServerProvider *provider)
+{
+ GdbServerProviderNode *n = findNode(m_toRemoveNodes, provider);
+ if (n) {
+ m_toRemoveNodes.removeOne(n);
+ delete n;
+ return;
+ }
+
+ int row = 0;
+ foreach (GdbServerProviderNode *current, m_root->childNodes) {
+ if (current->provider == provider) {
+ n = current;
+ break;
+ }
+ ++row;
+ }
+
+ beginRemoveRows(index(m_root), row, row);
+ m_root->childNodes.removeAt(row);
+ delete n;
+ endRemoveRows();
+
+ emit providerStateChanged();
+}
+
+GdbServerProvidersSettingsPage::GdbServerProvidersSettingsPage(
+ QObject *parent)
+ : Core::IOptionsPage(parent)
+{
+ setCategory(Constants::BAREMETAL_SETTINGS_CATEGORY);
+
+ setDisplayCategory(QCoreApplication::translate(
+ "BareMetal", Constants::BAREMETAL_SETTINGS_TR_CATEGORY));
+
+ setCategoryIcon(QLatin1String(Constants::BAREMETAL_SETTINGS_CATEGORY_ICON));
+
+ setId(Constants::GDB_PROVIDERS_SETTINGS_ID);
+ setDisplayName(tr("GDB Server Providers"));
+}
+
+QWidget *GdbServerProvidersSettingsPage::widget()
+{
+ if (!m_configWidget) {
+ // Actual page setup:
+ m_configWidget = new QWidget;
+
+ m_providerView = new QTreeView(m_configWidget);
+ m_providerView->setUniformRowHeights(true);
+ m_providerView->header()->setStretchLastSection(false);
+
+ 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 Utils::DetailsWidget(m_configWidget);
+ m_container->setState(Utils::DetailsWidget::NoSummary);
+ m_container->setMinimumWidth(500);
+ m_container->setVisible(false);
+
+ auto buttonLayout = new QHBoxLayout();
+ buttonLayout->setSpacing(6);
+ buttonLayout->setContentsMargins(0, 0, 0, 0);
+ buttonLayout->addWidget(m_addButton);
+ buttonLayout->addWidget(m_cloneButton);
+ buttonLayout->addWidget(m_delButton);
+ auto spacerItem = new QSpacerItem(40, 10, QSizePolicy::Expanding, QSizePolicy::Minimum);
+ buttonLayout->addItem(spacerItem);
+
+ auto verticalLayout = new QVBoxLayout();
+ verticalLayout->addWidget(m_providerView);
+ verticalLayout->addLayout(buttonLayout);
+
+ auto horizontalLayout = new QHBoxLayout(m_configWidget);
+ horizontalLayout->addLayout(verticalLayout);
+ horizontalLayout->addWidget(m_container);
+ Q_ASSERT(!m_model);
+ m_model = new GdbServerProviderModel(m_configWidget);
+
+ connect(m_model.data(), &GdbServerProviderModel::providerStateChanged,
+ this, &GdbServerProvidersSettingsPage::updateState);
+
+ m_providerView->setModel(m_model);
+
+ auto headerView = m_providerView->header();
+ headerView->setSectionResizeMode(0, QHeaderView::ResizeToContents);
+ headerView->setSectionResizeMode(1, QHeaderView::Stretch);
+ m_providerView->expandAll();
+
+ m_selectionModel = m_providerView->selectionModel();
+
+ connect(m_selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
+ SLOT(providerSelectionChanged()));
+
+ connect(GdbServerProviderManager::instance(), &GdbServerProviderManager::providersChanged,
+ this, &GdbServerProvidersSettingsPage::providerSelectionChanged);
+
+ // Set up add menu:
+ auto addMenu = new QMenu(m_addButton);
+ auto mapper = new QSignalMapper(addMenu);
+ connect(mapper, SIGNAL(mapped(QObject*)), SLOT(createProvider(QObject*)));
+
+ foreach (const auto f, GdbServerProviderManager::instance()->factories()) {
+ auto action = new QAction(addMenu);
+ action->setText(f->displayName());
+ connect(action, SIGNAL(triggered()), mapper, SLOT(map()));
+ mapper->setMapping(action, static_cast<QObject *>(f));
+ addMenu->addAction(action);
+ }
+
+ connect(m_cloneButton, SIGNAL(clicked()), mapper, SLOT(map()));
+ mapper->setMapping(m_cloneButton, static_cast<QObject *>(0));
+
+ m_addButton->setMenu(addMenu);
+
+ connect(m_delButton.data(), &QPushButton::clicked,
+ this, &GdbServerProvidersSettingsPage::removeProvider);
+
+ updateState();
+ }
+
+ return m_configWidget;
+}
+
+void GdbServerProvidersSettingsPage::apply()
+{
+ if (m_model)
+ m_model->apply();
+}
+
+void GdbServerProvidersSettingsPage::finish()
+{
+ disconnect(GdbServerProviderManager::instance(), SIGNAL(providersChanged()),
+ this, SLOT(providerSelectionChanged()));
+
+ delete m_configWidget;
+}
+
+void GdbServerProvidersSettingsPage::providerSelectionChanged()
+{
+ if (!m_container)
+ return;
+ const QModelIndex current = currentIndex();
+ QWidget *w = m_container->takeWidget(); // Prevent deletion.
+ if (w)
+ w->setVisible(false);
+ w = current.isValid() ? m_model->widget(current) : 0;
+ m_container->setWidget(w);
+ m_container->setVisible(w != 0);
+ updateState();
+}
+
+void GdbServerProvidersSettingsPage::createProvider(QObject *factoryObject)
+{
+ GdbServerProvider *provider = 0;
+
+ auto f = static_cast<GdbServerProviderFactory *>(factoryObject);
+ if (!f) {
+ GdbServerProvider *old = m_model->provider(currentIndex());
+ if (!old)
+ return;
+ provider = old->clone();
+ } else {
+ provider = f->create();
+ } if (!provider) {
+ return;
+ }
+
+ m_model->markForAddition(provider);
+
+ const QModelIndex newIdx = m_model->index(QModelIndex(), provider);
+ m_selectionModel->select(newIdx,
+ QItemSelectionModel::Clear
+ | QItemSelectionModel::SelectCurrent
+ | QItemSelectionModel::Rows);
+}
+
+void GdbServerProvidersSettingsPage::removeProvider()
+{
+ GdbServerProvider *p = m_model->provider(currentIndex());
+ if (!p)
+ return;
+ m_model->markForRemoval(p);
+}
+
+void GdbServerProvidersSettingsPage::updateState()
+{
+ if (!m_cloneButton)
+ return;
+
+ bool canCopy = false;
+ bool canDelete = false;
+ const GdbServerProvider *p = m_model->provider(currentIndex());
+ if (p) {
+ canCopy = p->isValid();
+ canDelete = true;
+ }
+
+ m_cloneButton->setEnabled(canCopy);
+ m_delButton->setEnabled(canDelete);
+}
+
+QModelIndex GdbServerProvidersSettingsPage::currentIndex() const
+{
+ if (!m_selectionModel)
+ return QModelIndex();
+
+ const QModelIndexList rows = m_selectionModel->selectedRows();
+ if (rows.count() != 1)
+ return QModelIndex();
+ return rows.at(0);
+}
+
+} // namespace Internal
+} // namespace BareMetal
diff --git a/src/plugins/baremetal/gdbserverproviderssettingspage.h b/src/plugins/baremetal/gdbserverproviderssettingspage.h
new file mode 100644
index 00000000000..cb912e8ed39
--- /dev/null
+++ b/src/plugins/baremetal/gdbserverproviderssettingspage.h
@@ -0,0 +1,149 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 GDBSERVERPROVIDERSSETTINGSPAGE_H
+#define GDBSERVERPROVIDERSSETTINGSPAGE_H
+
+#include <coreplugin/dialogs/ioptionspage.h>
+
+#include <QAbstractItemModel>
+#include <QPointer>
+
+QT_BEGIN_NAMESPACE
+class QItemSelectionModel;
+class QPushButton;
+class QTreeView;
+QT_END_NAMESPACE
+
+namespace Utils { class DetailsWidget; }
+
+namespace BareMetal {
+namespace Internal {
+
+class GdbServerProvider;
+class GdbServerProviderConfigWidget;
+class GdbServerProviderNode;
+
+class GdbServerProviderModel : public QAbstractItemModel
+{
+ Q_OBJECT
+
+public:
+ explicit GdbServerProviderModel(QObject *parent = 0);
+ ~GdbServerProviderModel();
+
+ QModelIndex index(int row, int column,
+ const QModelIndex &parent = QModelIndex()) const;
+
+ QModelIndex index(const QModelIndex &topIdx, const GdbServerProvider *) const;
+ QModelIndex parent(const QModelIndex &index) const;
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ int columnCount(const QModelIndex &parent = QModelIndex()) const;
+
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ Qt::ItemFlags flags(const QModelIndex &index) const;
+
+ QVariant headerData(int section, Qt::Orientation orientation,
+ int role = Qt::DisplayRole) const;
+
+ GdbServerProvider *provider(const QModelIndex &) const;
+
+ GdbServerProviderConfigWidget *widget(const QModelIndex &) const;
+
+ bool isDirty() const;
+ bool isDirty(GdbServerProvider *) const;
+
+ void apply();
+
+ void markForRemoval(GdbServerProvider *);
+ void markForAddition(GdbServerProvider *);
+
+signals:
+ void providerStateChanged();
+
+private slots:
+ void addProvider(GdbServerProvider *);
+ void removeProvider(GdbServerProvider *);
+ void setDirty();
+
+private:
+ enum ColumnIndex { NameIndex = 0, TypeIndex, ColumnsCount };
+
+ QModelIndex index(GdbServerProviderNode *, int column = 0) const;
+
+ GdbServerProviderNode *createNode(GdbServerProviderNode *parent,
+ GdbServerProvider *, bool changed);
+
+ GdbServerProviderNode *nodeFromIndex(const QModelIndex &) const;
+
+ static GdbServerProviderNode *findNode(
+ const QList<GdbServerProviderNode *> &container,
+ const GdbServerProvider *);
+
+ GdbServerProviderNode *m_root;
+ QList<GdbServerProviderNode *> m_toAddNodes;
+ QList<GdbServerProviderNode *> m_toRemoveNodes;
+};
+
+class GdbServerProvidersSettingsPage : public Core::IOptionsPage
+{
+ Q_OBJECT
+
+public:
+ explicit GdbServerProvidersSettingsPage(QObject *parent = 0);
+
+ QWidget *widget();
+ void apply();
+ void finish();
+
+private slots:
+ void providerSelectionChanged();
+ void createProvider(QObject *);
+ void removeProvider();
+ void updateState();
+
+private:
+ QModelIndex currentIndex() const;
+
+ QPointer<QWidget> m_configWidget;
+
+ QPointer<GdbServerProviderModel> m_model;
+ QPointer<QItemSelectionModel> m_selectionModel;
+ QPointer<QTreeView> m_providerView;
+ QPointer<Utils::DetailsWidget> m_container;
+ QPointer<QPushButton> m_addButton;
+ QPointer<QPushButton> m_cloneButton;
+ QPointer<QPushButton> m_delButton;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // GDBSERVERPROVIDERSSETTINGSPAGE_H
diff --git a/src/plugins/baremetal/images/QtBareMetal.png b/src/plugins/baremetal/images/QtBareMetal.png
new file mode 100644
index 00000000000..969916316a8
--- /dev/null
+++ b/src/plugins/baremetal/images/QtBareMetal.png
Binary files differ
diff --git a/src/plugins/baremetal/openocdgdbserverprovider.cpp b/src/plugins/baremetal/openocdgdbserverprovider.cpp
new file mode 100644
index 00000000000..f3f47404a9f
--- /dev/null
+++ b/src/plugins/baremetal/openocdgdbserverprovider.cpp
@@ -0,0 +1,371 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "openocdgdbserverprovider.h"
+#include "baremetalconstants.h"
+#include "gdbserverprovidermanager.h"
+
+#include <utils/pathchooser.h>
+#include <utils/qtcassert.h>
+#include <utils/fileutils.h>
+
+#include <coreplugin/variablechooser.h>
+
+#include <QString>
+#include <QFileInfo>
+
+#include <QFormLayout>
+#include <QLineEdit>
+#include <QComboBox>
+#include <QPlainTextEdit>
+
+namespace BareMetal {
+namespace Internal {
+
+const char hostKeyC[] = "BareMetal.OpenOcdGdbServerProvider.Host";
+const char portKeyC[] = "BareMetal.OpenOcdGdbServerProvider.Port";
+const char executableFileKeyC[] = "BareMetal.OpenOcdGdbServerProvider.ExecutableFile";
+const char rootScriptsDirKeyC[] = "BareMetal.OpenOcdGdbServerProvider.RootScriptsDir";
+const char configurationFileKeyC[] = "BareMetal.OpenOcdGdbServerProvider.ConfigurationPath";
+const char additionalArgumentsKeyC[] = "BareMetal.OpenOcdGdbServerProvider.AdditionalArguments";
+
+OpenOcdGdbServerProvider::OpenOcdGdbServerProvider()
+ : GdbServerProvider(QLatin1String(Constants::OPENOCD_PROVIDER_ID))
+ , m_host(QLatin1String("localhost"))
+ , m_port(3333)
+ , m_executableFile(QLatin1String("openocd"))
+{
+ setInitCommands(defaultInitCommands());
+ setResetCommands(defaultResetCommands());
+}
+
+OpenOcdGdbServerProvider::OpenOcdGdbServerProvider(
+ const OpenOcdGdbServerProvider &other)
+ : GdbServerProvider(other)
+ , m_host(other.m_host)
+ , m_port(other.m_port)
+ , m_executableFile(other.m_executableFile)
+ , m_rootScriptsDir(other.m_rootScriptsDir)
+ , m_configurationFile(other.m_configurationFile)
+ , m_additionalArguments(other.m_additionalArguments)
+{
+}
+
+QString OpenOcdGdbServerProvider::defaultInitCommands()
+{
+ return QLatin1String("set remote hardware-breakpoint-limit 6\n"
+ "set remote hardware-watchpoint-limit 4\n"
+ "monitor reset halt\n"
+ "load\n"
+ "monitor reset halt\n");
+}
+
+QString OpenOcdGdbServerProvider::defaultResetCommands()
+{
+ return QLatin1String("monitor reset halt\n");
+}
+
+QString OpenOcdGdbServerProvider::typeDisplayName() const
+{
+ return OpenOcdGdbServerProviderFactory::tr("OpenOCD");
+}
+
+QString OpenOcdGdbServerProvider::channel() const
+{
+ switch (startupMode()) {
+ case NoStartup:
+ // fallback
+ case StartupOnNetwork:
+ // Just return as "host:port" form.
+ return m_host + QLatin1Char(':') + QString::number(m_port);
+ case StartupOnPipe: {
+ QStringList args;
+ // In the pipe mode need to add quotes to each item of arguments;
+ // otherwise running will be stuck.
+ foreach (const QString &a, arguments()) {
+ if (a.startsWith(QLatin1Char('\"')) && a.endsWith(QLatin1Char('\"')))
+ continue;
+ args << (QLatin1Char('\"') + a + QLatin1Char('\"'));
+ }
+ args.prepend(executable());
+ args.prepend(QLatin1String("|"));
+ return args.join(QLatin1Char(' '));
+ }
+ default: // wrong
+ return QString();
+ }
+}
+
+QString OpenOcdGdbServerProvider::executable() const
+{
+ return m_executableFile;
+}
+
+QStringList OpenOcdGdbServerProvider::arguments() const
+{
+ QStringList args;
+
+ args << QLatin1String("-c");
+ if (startupMode() == StartupOnPipe)
+ args << QLatin1String("gdb_port pipe");
+ else
+ args << (QLatin1String("gdb_port ") + QString::number(m_port));
+
+ if (!m_rootScriptsDir.isEmpty())
+ args << QLatin1String("-s") << m_rootScriptsDir;
+
+ if (!m_configurationFile.isEmpty())
+ args << QLatin1String("-f") << m_configurationFile;
+
+ if (!m_additionalArguments.isEmpty())
+ args << m_additionalArguments;
+
+ return args;
+}
+
+bool OpenOcdGdbServerProvider::canStartupMode(StartupMode m) const
+{
+ return m == NoStartup || m == StartupOnNetwork || m == StartupOnPipe;
+}
+
+bool OpenOcdGdbServerProvider::isValid() const
+{
+ if (!GdbServerProvider::isValid())
+ return false;
+
+ const StartupMode m = startupMode();
+
+ if (m == NoStartup || m == StartupOnNetwork) {
+ if (m_host.isEmpty())
+ return false;
+ }
+
+ if (m == StartupOnNetwork || m == StartupOnPipe) {
+ if (m_executableFile.isEmpty() || m_configurationFile.isEmpty())
+ return false;
+ }
+
+ return true;
+}
+
+GdbServerProvider *OpenOcdGdbServerProvider::clone() const
+{
+ return new OpenOcdGdbServerProvider(*this);
+}
+
+QVariantMap OpenOcdGdbServerProvider::toMap() const
+{
+ QVariantMap data = GdbServerProvider::toMap();
+ data.insert(QLatin1String(hostKeyC), m_host);
+ data.insert(QLatin1String(portKeyC), m_port);
+ data.insert(QLatin1String(executableFileKeyC), m_executableFile);
+ data.insert(QLatin1String(rootScriptsDirKeyC), m_rootScriptsDir);
+ data.insert(QLatin1String(configurationFileKeyC), m_configurationFile);
+ data.insert(QLatin1String(additionalArgumentsKeyC), m_additionalArguments);
+ return data;
+}
+
+bool OpenOcdGdbServerProvider::fromMap(const QVariantMap &data)
+{
+ if (!GdbServerProvider::fromMap(data))
+ return false;
+
+ m_host = data.value(QLatin1String(hostKeyC)).toString();
+ m_port = data.value(QLatin1String(portKeyC)).toInt();
+ m_executableFile = data.value(QLatin1String(executableFileKeyC)).toString();
+ m_rootScriptsDir = data.value(QLatin1String(rootScriptsDirKeyC)).toString();
+ m_configurationFile = data.value(QLatin1String(configurationFileKeyC)).toString();
+ m_additionalArguments = data.value(QLatin1String(additionalArgumentsKeyC)).toString();
+ return true;
+}
+
+bool OpenOcdGdbServerProvider::operator==(const GdbServerProvider &other) const
+{
+ if (!GdbServerProvider::operator==(other))
+ return false;
+
+ const auto p = static_cast<const OpenOcdGdbServerProvider *>(&other);
+ return m_host == p->m_host
+ && m_port == p->m_port
+ && m_executableFile == p->m_executableFile
+ && m_rootScriptsDir == p->m_rootScriptsDir
+ && m_configurationFile == p->m_configurationFile
+ && m_additionalArguments == p->m_additionalArguments;
+}
+
+GdbServerProviderConfigWidget *OpenOcdGdbServerProvider::configurationWidget()
+{
+ return new OpenOcdGdbServerProviderConfigWidget(this);
+}
+
+OpenOcdGdbServerProviderFactory::OpenOcdGdbServerProviderFactory()
+{
+ setId(QLatin1String(Constants::OPENOCD_PROVIDER_ID));
+ setDisplayName(tr("OpenOCD"));
+}
+
+GdbServerProvider *OpenOcdGdbServerProviderFactory::create()
+{
+ return new OpenOcdGdbServerProvider;
+}
+
+bool OpenOcdGdbServerProviderFactory::canRestore(const QVariantMap &data)
+{
+ const QString id = idFromMap(data);
+ return id.startsWith(QLatin1String(Constants::OPENOCD_PROVIDER_ID)
+ + QLatin1Char(':'));
+}
+
+GdbServerProvider *OpenOcdGdbServerProviderFactory::restore(const QVariantMap &data)
+{
+ auto p = new OpenOcdGdbServerProvider;
+ auto updated = data;
+ if (p->fromMap(updated))
+ return p;
+ delete p;
+ return 0;
+}
+
+OpenOcdGdbServerProviderConfigWidget::OpenOcdGdbServerProviderConfigWidget(
+ OpenOcdGdbServerProvider *p)
+ : GdbServerProviderConfigWidget(p)
+{
+ Q_ASSERT(p);
+
+ m_hostWidget = new HostWidget(this);
+ m_mainLayout->addRow(tr("Host:"), m_hostWidget);
+
+ m_executableFileChooser = new Utils::PathChooser;
+ m_executableFileChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
+ m_executableFileChooser->setCommandVersionArguments(QStringList(QLatin1String("--version")));
+ m_mainLayout->addRow(tr("Executable file:"), m_executableFileChooser);
+
+ m_rootScriptsDirChooser = new Utils::PathChooser;
+ m_rootScriptsDirChooser->setExpectedKind(Utils::PathChooser::Directory);
+ m_mainLayout->addRow(tr("Root scripts directory:"), m_rootScriptsDirChooser);
+
+ m_configurationFileChooser = new Utils::PathChooser;
+ m_configurationFileChooser->setExpectedKind(Utils::PathChooser::File);
+ m_configurationFileChooser->setPromptDialogFilter(QLatin1String("*.cfg"));
+ m_mainLayout->addRow(tr("Configuration file:"), m_configurationFileChooser);
+
+ m_additionalArgumentsLineEdit = new QLineEdit(this);
+ m_mainLayout->addRow(tr("Additional arguments:"), m_additionalArgumentsLineEdit);
+
+ m_initCommandsTextEdit = new QPlainTextEdit(this);
+ m_initCommandsTextEdit->setToolTip(defaultInitCommandsTooltip());
+ m_mainLayout->addRow(tr("Init commands:"), m_initCommandsTextEdit);
+ m_resetCommandsTextEdit = new QPlainTextEdit(this);
+ m_resetCommandsTextEdit->setToolTip(defaultResetCommandsTooltip());
+ m_mainLayout->addRow(tr("Reset commands:"), m_resetCommandsTextEdit);
+
+ addErrorLabel();
+ setFromProvider();
+
+ auto chooser = new Core::VariableChooser(this);
+ chooser->addSupportedWidget(m_initCommandsTextEdit.data());
+ chooser->addSupportedWidget(m_resetCommandsTextEdit.data());
+
+ connect(m_hostWidget.data(), &HostWidget::dataChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_executableFileChooser.data(), &Utils::PathChooser::changed,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_rootScriptsDirChooser.data(), &Utils::PathChooser::changed,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_configurationFileChooser.data(), &Utils::PathChooser::changed,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_additionalArgumentsLineEdit.data(), &QLineEdit::textChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_initCommandsTextEdit.data(), &QPlainTextEdit::textChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_resetCommandsTextEdit.data(), &QPlainTextEdit::textChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+
+ connect(m_startupModeComboBox, SIGNAL(currentIndexChanged(int)),
+ SLOT(startupModeChanged()));
+}
+
+void OpenOcdGdbServerProviderConfigWidget::startupModeChanged()
+{
+ const GdbServerProvider::StartupMode m = startupMode();
+ const bool isStartup = m != GdbServerProvider::NoStartup;
+ m_executableFileChooser->setVisible(isStartup);
+ m_mainLayout->labelForField(m_executableFileChooser)->setVisible(isStartup);
+ m_rootScriptsDirChooser->setVisible(isStartup);
+ m_mainLayout->labelForField(m_rootScriptsDirChooser)->setVisible(isStartup);
+ m_configurationFileChooser->setVisible(isStartup);
+ m_mainLayout->labelForField(m_configurationFileChooser)->setVisible(isStartup);
+ m_additionalArgumentsLineEdit->setVisible(isStartup);
+ m_mainLayout->labelForField(m_additionalArgumentsLineEdit)->setVisible(isStartup);
+ const bool isNetwork = m != GdbServerProvider::StartupOnPipe;
+ m_hostWidget->setVisible(isNetwork);
+ m_mainLayout->labelForField(m_hostWidget)->setVisible(isNetwork);
+}
+
+void OpenOcdGdbServerProviderConfigWidget::applyImpl()
+{
+ auto p = static_cast<OpenOcdGdbServerProvider *>(provider());
+ Q_ASSERT(p);
+
+ p->m_host = m_hostWidget->host();
+ p->m_port = m_hostWidget->port();
+ p->m_executableFile = m_executableFileChooser->fileName().toString();
+ p->m_rootScriptsDir = m_rootScriptsDirChooser->fileName().toString();
+ p->m_configurationFile = m_configurationFileChooser->fileName().toString();
+ p->m_additionalArguments = m_additionalArgumentsLineEdit->text();
+ p->setInitCommands(m_initCommandsTextEdit->toPlainText());
+ p->setResetCommands(m_resetCommandsTextEdit->toPlainText());
+}
+
+void OpenOcdGdbServerProviderConfigWidget::discardImpl()
+{
+ setFromProvider();
+}
+
+void OpenOcdGdbServerProviderConfigWidget::setFromProvider()
+{
+ const auto p = static_cast<OpenOcdGdbServerProvider *>(provider());
+ Q_ASSERT(p);
+
+ const bool b = blockSignals(true);
+ startupModeChanged();
+ m_hostWidget->setHost(p->m_host);
+ m_hostWidget->setPort(p->m_port);
+ m_executableFileChooser->setFileName(Utils::FileName::fromString(p->m_executableFile));
+ m_rootScriptsDirChooser->setFileName(Utils::FileName::fromString(p->m_rootScriptsDir));
+ m_configurationFileChooser->setFileName(Utils::FileName::fromString(p->m_configurationFile));
+ m_additionalArgumentsLineEdit->setText(p->m_additionalArguments);
+ m_initCommandsTextEdit->setPlainText(p->initCommands());
+ m_resetCommandsTextEdit->setPlainText(p->resetCommands());
+ blockSignals(b);
+}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/baremetal/openocdgdbserverprovider.h b/src/plugins/baremetal/openocdgdbserverprovider.h
new file mode 100644
index 00000000000..3239756741b
--- /dev/null
+++ b/src/plugins/baremetal/openocdgdbserverprovider.h
@@ -0,0 +1,125 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 OPENOCDGDBSERVERPROVIDER_H
+#define OPENOCDGDBSERVERPROVIDER_H
+
+#include "gdbserverprovider.h"
+
+namespace Utils { class PathChooser; }
+
+namespace BareMetal {
+namespace Internal {
+
+class OpenOcdGdbServerProviderConfigWidget;
+class OpenOcdGdbServerProviderFactory;
+
+class OpenOcdGdbServerProvider : public GdbServerProvider
+{
+public:
+ QString typeDisplayName() const;
+
+ QVariantMap toMap() const;
+ bool fromMap(const QVariantMap &data);
+
+ bool operator==(const GdbServerProvider &) const;
+
+ GdbServerProviderConfigWidget *configurationWidget();
+ GdbServerProvider *clone() const;
+
+ QString channel() const;
+ QString executable() const;
+ QStringList arguments() const;
+
+ bool canStartupMode(StartupMode mode) const;
+ bool isValid() const;
+
+private:
+ explicit OpenOcdGdbServerProvider();
+ explicit OpenOcdGdbServerProvider(const OpenOcdGdbServerProvider &);
+
+ static QString defaultInitCommands();
+ static QString defaultResetCommands();
+
+ QString m_host;
+ quint16 m_port;
+ QString m_executableFile;
+ QString m_rootScriptsDir;
+ QString m_configurationFile;
+ QString m_additionalArguments;
+
+ friend class OpenOcdGdbServerProviderConfigWidget;
+ friend class OpenOcdGdbServerProviderFactory;
+};
+
+class OpenOcdGdbServerProviderFactory : public GdbServerProviderFactory
+{
+ Q_OBJECT
+
+public:
+ explicit OpenOcdGdbServerProviderFactory();
+
+ GdbServerProvider *create();
+
+ bool canRestore(const QVariantMap &data);
+ GdbServerProvider *restore(const QVariantMap &data);
+
+ GdbServerProviderConfigWidget *configurationWidget(GdbServerProvider *);
+};
+
+class OpenOcdGdbServerProviderConfigWidget : public GdbServerProviderConfigWidget
+{
+ Q_OBJECT
+
+public:
+ explicit OpenOcdGdbServerProviderConfigWidget(OpenOcdGdbServerProvider *);
+
+private slots:
+ void startupModeChanged();
+
+private:
+ void applyImpl();
+ void discardImpl();
+
+ void setFromProvider();
+
+ QPointer<HostWidget> m_hostWidget;
+ QPointer<Utils::PathChooser> m_executableFileChooser;
+ QPointer<Utils::PathChooser> m_rootScriptsDirChooser;
+ QPointer<Utils::PathChooser> m_configurationFileChooser;
+ QPointer<QLineEdit> m_additionalArgumentsLineEdit;
+ QPointer<QPlainTextEdit> m_initCommandsTextEdit;
+ QPointer<QPlainTextEdit> m_resetCommandsTextEdit;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // OPENOCDGDBSERVERPROVIDER_H
diff --git a/src/plugins/baremetal/stlinkutilgdbserverprovider.cpp b/src/plugins/baremetal/stlinkutilgdbserverprovider.cpp
new file mode 100644
index 00000000000..daf70f6d672
--- /dev/null
+++ b/src/plugins/baremetal/stlinkutilgdbserverprovider.cpp
@@ -0,0 +1,407 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "stlinkutilgdbserverprovider.h"
+#include "baremetalconstants.h"
+#include "gdbserverprovidermanager.h"
+
+#include <utils/pathchooser.h>
+#include <utils/qtcassert.h>
+#include <utils/fileutils.h>
+
+#include <coreplugin/variablechooser.h>
+
+#include <QString>
+#include <QFileInfo>
+
+#include <QFormLayout>
+#include <QLineEdit>
+#include <QComboBox>
+#include <QSpinBox>
+#include <QCheckBox>
+#include <QPlainTextEdit>
+
+namespace BareMetal {
+namespace Internal {
+
+const char hostKeyC[] = "BareMetal.StLinkUtilGdbServerProvider.Host";
+const char portKeyC[] = "BareMetal.StLinkUtilGdbServerProvider.Port";
+const char executableFileKeyC[] = "BareMetal.StLinkUtilGdbServerProvider.ExecutableFile";
+const char verboseLevelKeyC[] = "BareMetal.StLinkUtilGdbServerProvider.VerboseLevel";
+const char extendedModeKeyC[] = "BareMetal.StLinkUtilGdbServerProvider.ExtendedMode";
+const char resetBoardKeyC[] = "BareMetal.StLinkUtilGdbServerProvider.ResetBoard";
+const char transportLayerKeyC[] = "BareMetal.StLinkUtilGdbServerProvider.TransportLayer";
+
+StLinkUtilGdbServerProvider::StLinkUtilGdbServerProvider()
+ : GdbServerProvider(QLatin1String(Constants::STLINK_UTIL_PROVIDER_ID))
+ , m_host(QLatin1String("localhost"))
+ , m_port(4242)
+ , m_executableFile(QLatin1String("st-util"))
+ , m_verboseLevel(0)
+ , m_extendedMode(false)
+ , m_resetBoard(true)
+ , m_transport(RawUsb)
+{
+ setInitCommands(defaultInitCommands());
+ setResetCommands(defaultResetCommands());
+}
+
+StLinkUtilGdbServerProvider::StLinkUtilGdbServerProvider(
+ const StLinkUtilGdbServerProvider &other)
+ : GdbServerProvider(other)
+ , m_host(other.m_host)
+ , m_port(other.m_port)
+ , m_executableFile(other.m_executableFile)
+ , m_verboseLevel(0)
+ , m_extendedMode(false)
+ , m_resetBoard(true)
+ , m_transport(RawUsb)
+{
+}
+
+QString StLinkUtilGdbServerProvider::defaultInitCommands()
+{
+ return QLatin1String("load\n");
+}
+
+QString StLinkUtilGdbServerProvider::defaultResetCommands()
+{
+ return QLatin1String("");
+}
+
+QString StLinkUtilGdbServerProvider::typeDisplayName() const
+{
+ return StLinkUtilGdbServerProviderFactory::tr("STLink-Util");
+}
+
+QString StLinkUtilGdbServerProvider::channel() const
+{
+ switch (startupMode()) {
+ case NoStartup:
+ // fallback
+ case StartupOnNetwork:
+ // Just return as "host:port" form.
+ return m_host + QLatin1Char(':') + QString::number(m_port);
+ case StartupOnPipe:
+ // Unsupported mode
+ return QString();
+ default: // wrong
+ return QString();
+ }
+}
+
+QString StLinkUtilGdbServerProvider::executable() const
+{
+ return m_executableFile;
+}
+
+QStringList StLinkUtilGdbServerProvider::arguments() const
+{
+ QStringList args;
+
+ if (m_extendedMode)
+ args << QLatin1String("--multi");
+
+ if (!m_resetBoard)
+ args << QLatin1String("--no-reset");
+
+ args << (QLatin1String("--stlink_version=") + QString::number(m_transport));
+ args << (QLatin1String("--listen_port=") + QString::number(m_port));
+ args << (QLatin1String("--verbose=") + QString::number(m_verboseLevel));
+
+ return args;
+}
+
+bool StLinkUtilGdbServerProvider::canStartupMode(StartupMode m) const
+{
+ return m == NoStartup || m == StartupOnNetwork;
+}
+
+bool StLinkUtilGdbServerProvider::isValid() const
+{
+ if (!GdbServerProvider::isValid())
+ return false;
+
+ const StartupMode m = startupMode();
+
+ if (m == NoStartup || m == StartupOnNetwork) {
+ if (m_host.isEmpty())
+ return false;
+ }
+
+ if (m == StartupOnNetwork) {
+ if (m_executableFile.isEmpty())
+ return false;
+ }
+
+ return true;
+}
+
+GdbServerProvider *StLinkUtilGdbServerProvider::clone() const
+{
+ return new StLinkUtilGdbServerProvider(*this);
+}
+
+QVariantMap StLinkUtilGdbServerProvider::toMap() const
+{
+ QVariantMap data = GdbServerProvider::toMap();
+ data.insert(QLatin1String(hostKeyC), m_host);
+ data.insert(QLatin1String(portKeyC), m_port);
+ data.insert(QLatin1String(executableFileKeyC), m_executableFile);
+ data.insert(QLatin1String(verboseLevelKeyC), m_verboseLevel);
+ data.insert(QLatin1String(extendedModeKeyC), m_extendedMode);
+ data.insert(QLatin1String(resetBoardKeyC), m_resetBoard);
+ data.insert(QLatin1String(transportLayerKeyC), m_transport);
+ return data;
+}
+
+bool StLinkUtilGdbServerProvider::fromMap(const QVariantMap &data)
+{
+ if (!GdbServerProvider::fromMap(data))
+ return false;
+
+ m_host = data.value(QLatin1String(hostKeyC)).toString();
+ m_port = data.value(QLatin1String(portKeyC)).toInt();
+ m_executableFile = data.value(QLatin1String(executableFileKeyC)).toString();
+ m_verboseLevel = data.value(QLatin1String(verboseLevelKeyC)).toInt();
+ m_extendedMode = data.value(QLatin1String(extendedModeKeyC)).toBool();
+ m_resetBoard = data.value(QLatin1String(resetBoardKeyC)).toBool();
+ m_transport = static_cast<TransportLayer>(
+ data.value(QLatin1String(transportLayerKeyC)).toInt());
+ return true;
+}
+
+bool StLinkUtilGdbServerProvider::operator==(const GdbServerProvider &other) const
+{
+ if (!GdbServerProvider::operator==(other))
+ return false;
+
+ const auto p = static_cast<const StLinkUtilGdbServerProvider *>(&other);
+ return m_host == p->m_host
+ && m_port == p->m_port
+ && m_executableFile == p->m_executableFile
+ && m_verboseLevel == p->m_verboseLevel
+ && m_extendedMode == p->m_extendedMode
+ && m_resetBoard == p->m_resetBoard
+ && m_transport == p->m_transport;
+}
+
+GdbServerProviderConfigWidget *StLinkUtilGdbServerProvider::configurationWidget()
+{
+ return new StLinkUtilGdbServerProviderConfigWidget(this);
+}
+
+StLinkUtilGdbServerProviderFactory::StLinkUtilGdbServerProviderFactory()
+{
+ setId(QLatin1String(Constants::STLINK_UTIL_PROVIDER_ID));
+ setDisplayName(tr("STLink-Util"));
+}
+
+GdbServerProvider *StLinkUtilGdbServerProviderFactory::create()
+{
+ return new StLinkUtilGdbServerProvider;
+}
+
+bool StLinkUtilGdbServerProviderFactory::canRestore(const QVariantMap &data)
+{
+ const QString id = idFromMap(data);
+ return id.startsWith(QLatin1String(Constants::STLINK_UTIL_PROVIDER_ID)
+ + QLatin1Char(':'));
+}
+
+GdbServerProvider *StLinkUtilGdbServerProviderFactory::restore(const QVariantMap &data)
+{
+ auto p = new StLinkUtilGdbServerProvider;
+ auto updated = data;
+ if (p->fromMap(updated))
+ return p;
+ delete p;
+ return 0;
+}
+
+StLinkUtilGdbServerProviderConfigWidget::StLinkUtilGdbServerProviderConfigWidget(
+ StLinkUtilGdbServerProvider *p)
+ : GdbServerProviderConfigWidget(p)
+{
+ Q_ASSERT(p);
+
+ m_hostWidget = new HostWidget(this);
+ m_mainLayout->addRow(tr("Host:"), m_hostWidget);
+
+ m_executableFileChooser = new Utils::PathChooser;
+ m_executableFileChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
+ m_mainLayout->addRow(tr("Executable file:"), m_executableFileChooser);
+
+ m_verboseLevelSpinBox = new QSpinBox;
+ m_verboseLevelSpinBox->setRange(0, 99);
+ m_verboseLevelSpinBox->setToolTip(tr("Specify the verbosity level (0..99)."));
+ m_mainLayout->addRow(tr("Verbosity level:"), m_verboseLevelSpinBox);
+
+ m_extendedModeCheckBox = new QCheckBox;
+ m_extendedModeCheckBox->setToolTip(tr("Continue listening for connections "
+ "after disconnect."));
+ m_mainLayout->addRow(tr("Extended mode:"), m_extendedModeCheckBox);
+
+ m_resetBoardCheckBox = new QCheckBox;
+ m_resetBoardCheckBox->setToolTip(tr("Reset board on connection."));
+ m_mainLayout->addRow(tr("Reset on connection:"), m_resetBoardCheckBox);
+
+ m_transportLayerComboBox = new QComboBox;
+ m_transportLayerComboBox->setToolTip(tr("Transport layer type."));
+ m_mainLayout->addRow(tr("Version:"), m_transportLayerComboBox);
+
+ m_initCommandsTextEdit = new QPlainTextEdit(this);
+ m_initCommandsTextEdit->setToolTip(defaultInitCommandsTooltip());
+ m_mainLayout->addRow(tr("Init commands:"), m_initCommandsTextEdit);
+ m_resetCommandsTextEdit = new QPlainTextEdit(this);
+ m_resetCommandsTextEdit->setToolTip(defaultResetCommandsTooltip());
+ m_mainLayout->addRow(tr("Reset commands:"), m_resetCommandsTextEdit);
+
+ populateTransportLayers();
+ addErrorLabel();
+ setFromProvider();
+
+ auto chooser = new Core::VariableChooser(this);
+ chooser->addSupportedWidget(m_initCommandsTextEdit.data());
+ chooser->addSupportedWidget(m_resetCommandsTextEdit.data());
+
+ connect(m_hostWidget.data(), &HostWidget::dataChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_executableFileChooser.data(), &Utils::PathChooser::changed,
+ this, &GdbServerProviderConfigWidget::dirty);
+
+ connect(m_verboseLevelSpinBox, SIGNAL(valueChanged(int)), SIGNAL(dirty()));
+ connect(m_extendedModeCheckBox, SIGNAL(clicked()), SIGNAL(dirty()));
+ connect(m_resetBoardCheckBox, SIGNAL(clicked()), SIGNAL(dirty()));
+ connect(m_transportLayerComboBox, SIGNAL(currentIndexChanged(int)), SIGNAL(dirty()));
+
+ connect(m_initCommandsTextEdit.data(), &QPlainTextEdit::textChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+ connect(m_resetCommandsTextEdit.data(), &QPlainTextEdit::textChanged,
+ this, &GdbServerProviderConfigWidget::dirty);
+
+ connect(m_startupModeComboBox, SIGNAL(currentIndexChanged(int)),
+ SLOT(startupModeChanged()));
+}
+
+
+void StLinkUtilGdbServerProviderConfigWidget::startupModeChanged()
+{
+ const GdbServerProvider::StartupMode m = startupMode();
+ const bool isStartup = m != GdbServerProvider::NoStartup;
+ m_executableFileChooser->setVisible(isStartup);
+ m_mainLayout->labelForField(m_executableFileChooser)->setVisible(isStartup);
+ m_verboseLevelSpinBox->setVisible(isStartup);
+ m_mainLayout->labelForField(m_verboseLevelSpinBox)->setVisible(isStartup);
+ m_extendedModeCheckBox->setVisible(isStartup);
+ m_mainLayout->labelForField(m_extendedModeCheckBox)->setVisible(isStartup);
+ m_resetBoardCheckBox->setVisible(isStartup);
+ m_mainLayout->labelForField(m_resetBoardCheckBox)->setVisible(isStartup);
+ m_transportLayerComboBox->setVisible(isStartup);
+ m_mainLayout->labelForField(m_transportLayerComboBox)->setVisible(isStartup);
+}
+
+void StLinkUtilGdbServerProviderConfigWidget::applyImpl()
+{
+ auto p = static_cast<StLinkUtilGdbServerProvider *>(provider());
+ Q_ASSERT(p);
+
+ p->m_host = m_hostWidget->host();
+ p->m_port = m_hostWidget->port();
+ p->m_executableFile = m_executableFileChooser->fileName().toString();
+ p->m_verboseLevel = m_verboseLevelSpinBox->value();
+ p->m_extendedMode = m_extendedModeCheckBox->isChecked();
+ p->m_resetBoard = m_resetBoardCheckBox->isChecked();
+ p->m_transport = transportLayer();
+ p->setInitCommands(m_initCommandsTextEdit->toPlainText());
+ p->setResetCommands(m_resetCommandsTextEdit->toPlainText());
+}
+
+void StLinkUtilGdbServerProviderConfigWidget::discardImpl()
+{
+ setFromProvider();
+}
+
+StLinkUtilGdbServerProvider::TransportLayer
+StLinkUtilGdbServerProviderConfigWidget::transportLayerFromIndex(int idx) const
+{
+ return static_cast<StLinkUtilGdbServerProvider::TransportLayer>(
+ m_transportLayerComboBox->itemData(idx).toInt());
+}
+
+StLinkUtilGdbServerProvider::TransportLayer
+StLinkUtilGdbServerProviderConfigWidget::transportLayer() const
+{
+ const int idx = m_transportLayerComboBox->currentIndex();
+ return transportLayerFromIndex(idx);
+}
+
+void StLinkUtilGdbServerProviderConfigWidget::setTransportLayer(
+ StLinkUtilGdbServerProvider::TransportLayer tl)
+{
+ for (int idx = 0; idx < m_transportLayerComboBox->count(); ++idx) {
+ if (tl == transportLayerFromIndex(idx)) {
+ m_transportLayerComboBox->setCurrentIndex(idx);
+ break;
+ }
+ }
+}
+
+void StLinkUtilGdbServerProviderConfigWidget::populateTransportLayers()
+{
+ m_transportLayerComboBox->insertItem(
+ m_transportLayerComboBox->count(), tr("STLINKv1"),
+ StLinkUtilGdbServerProvider::ScsiOverUsb);
+ m_transportLayerComboBox->insertItem(
+ m_transportLayerComboBox->count(), tr("STLINKv2"),
+ StLinkUtilGdbServerProvider::RawUsb);
+}
+
+void StLinkUtilGdbServerProviderConfigWidget::setFromProvider()
+{
+ const auto p = static_cast<StLinkUtilGdbServerProvider *>(provider());
+ Q_ASSERT(p);
+
+ const bool b = blockSignals(true);
+ startupModeChanged();
+ m_hostWidget->setHost(p->m_host);
+ m_hostWidget->setPort(p->m_port);
+ m_executableFileChooser->setFileName(Utils::FileName::fromString(p->m_executableFile));
+ m_verboseLevelSpinBox->setValue(p->m_verboseLevel);
+ m_extendedModeCheckBox->setChecked(p->m_extendedMode);
+ m_resetBoardCheckBox->setChecked(p->m_resetBoard);
+ setTransportLayer(p->m_transport);
+ m_initCommandsTextEdit->setPlainText(p->initCommands());
+ m_resetCommandsTextEdit->setPlainText(p->resetCommands());
+ blockSignals(b);
+}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/baremetal/stlinkutilgdbserverprovider.h b/src/plugins/baremetal/stlinkutilgdbserverprovider.h
new file mode 100644
index 00000000000..9b742c3b548
--- /dev/null
+++ b/src/plugins/baremetal/stlinkutilgdbserverprovider.h
@@ -0,0 +1,137 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Denis Shienkov <denis.shienkov@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://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 STLINKUTILGDBSERVERPROVIDER_H
+#define STLINKUTILGDBSERVERPROVIDER_H
+
+#include "gdbserverprovider.h"
+
+QT_BEGIN_NAMESPACE
+class QCheckBox;
+QT_END_NAMESPACE
+
+namespace Utils { class PathChooser; }
+
+namespace BareMetal {
+namespace Internal {
+
+class StLinkUtilGdbServerProviderConfigWidget;
+class StLinkUtilGdbServerProviderFactory;
+
+class StLinkUtilGdbServerProvider : public GdbServerProvider
+{
+public:
+ enum TransportLayer { ScsiOverUsb = 1, RawUsb = 2 };
+ QString typeDisplayName() const;
+
+ QVariantMap toMap() const;
+ bool fromMap(const QVariantMap &data);
+
+ bool operator==(const GdbServerProvider &) const;
+
+ GdbServerProviderConfigWidget *configurationWidget();
+ GdbServerProvider *clone() const;
+
+ QString channel() const;
+ QString executable() const;
+ QStringList arguments() const;
+
+ bool canStartupMode(StartupMode mode) const;
+ bool isValid() const;
+
+private:
+ explicit StLinkUtilGdbServerProvider();
+ explicit StLinkUtilGdbServerProvider(const StLinkUtilGdbServerProvider &);
+
+ static QString defaultInitCommands();
+ static QString defaultResetCommands();
+
+ QString m_host;
+ quint16 m_port;
+ QString m_executableFile;
+ int m_verboseLevel; // 0..99
+ bool m_extendedMode; // Listening for connections after disconnect
+ bool m_resetBoard;
+ TransportLayer m_transport;
+
+ friend class StLinkUtilGdbServerProviderConfigWidget;
+ friend class StLinkUtilGdbServerProviderFactory;
+};
+
+class StLinkUtilGdbServerProviderFactory : public GdbServerProviderFactory
+{
+ Q_OBJECT
+
+public:
+ explicit StLinkUtilGdbServerProviderFactory();
+
+ GdbServerProvider *create();
+
+ bool canRestore(const QVariantMap &data);
+ GdbServerProvider *restore(const QVariantMap &data);
+
+ GdbServerProviderConfigWidget *configurationWidget(GdbServerProvider *);
+};
+
+class StLinkUtilGdbServerProviderConfigWidget : public GdbServerProviderConfigWidget
+{
+ Q_OBJECT
+
+public:
+ explicit StLinkUtilGdbServerProviderConfigWidget(StLinkUtilGdbServerProvider *);
+
+private slots:
+ void startupModeChanged();
+
+private:
+ void applyImpl();
+ void discardImpl();
+
+ StLinkUtilGdbServerProvider::TransportLayer transportLayerFromIndex(int idx) const;
+ StLinkUtilGdbServerProvider::TransportLayer transportLayer() const;
+ void setTransportLayer(StLinkUtilGdbServerProvider::TransportLayer);
+
+ void populateTransportLayers();
+ void setFromProvider();
+
+ QPointer<HostWidget> m_hostWidget;
+ QPointer<Utils::PathChooser> m_executableFileChooser;
+ QPointer<QSpinBox> m_verboseLevelSpinBox;
+ QPointer<QCheckBox> m_extendedModeCheckBox;
+ QPointer<QCheckBox> m_resetBoardCheckBox;
+ QPointer<QComboBox> m_transportLayerComboBox;
+ QPointer<QPlainTextEdit> m_initCommandsTextEdit;
+ QPointer<QPlainTextEdit> m_resetCommandsTextEdit;
+};
+
+} // namespace Internal
+} // namespace BareMetal
+
+#endif // STLINKUTILGDBSERVERPROVIDER_H
diff --git a/src/plugins/bazaar/bazaarclient.cpp b/src/plugins/bazaar/bazaarclient.cpp
index 05ce368d2cd..75de80ea9d9 100644
--- a/src/plugins/bazaar/bazaarclient.cpp
+++ b/src/plugins/bazaar/bazaarclient.cpp
@@ -61,9 +61,66 @@ SynchronousProcessResponse::Result BazaarDiffExitCodeInterpreter::interpretExitC
return SynchronousProcessResponse::Finished;
}
+// Parameter widget controlling whitespace diff mode, associated with a parameter
+class BazaarDiffParameterWidget : public VcsBaseEditorParameterWidget
+{
+ Q_OBJECT
+public:
+ BazaarDiffParameterWidget(BazaarSettings *settings, QWidget *parent = 0) :
+ VcsBaseEditorParameterWidget(parent)
+ {
+ mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace")),
+ settings->boolPointer(BazaarSettings::diffIgnoreWhiteSpaceKey));
+ mapSetting(addToggleButton(QLatin1String("-B"), tr("Ignore Blank Lines")),
+ settings->boolPointer(BazaarSettings::diffIgnoreBlankLinesKey));
+ }
+
+ QStringList arguments() const
+ {
+ QStringList args;
+ // Bazaar wants "--diff-options=-w -B.."
+ const QStringList formatArguments = VcsBaseEditorParameterWidget::arguments();
+ if (!formatArguments.isEmpty()) {
+ const QString a = QLatin1String("--diff-options=")
+ + formatArguments.join(QString(QLatin1Char(' ')));
+ args.append(a);
+ }
+ return args;
+ }
+};
+
+class BazaarLogParameterWidget : public VcsBaseEditorParameterWidget
+{
+ Q_OBJECT
+public:
+ BazaarLogParameterWidget(BazaarSettings *settings, QWidget *parent = 0) :
+ VcsBaseEditorParameterWidget(parent)
+ {
+ mapSetting(addToggleButton(QLatin1String("--verbose"), tr("Verbose"),
+ tr("Show files changed in each revision")),
+ settings->boolPointer(BazaarSettings::logVerboseKey));
+ mapSetting(addToggleButton(QLatin1String("--forward"), tr("Forward"),
+ tr("Show from oldest to newest")),
+ settings->boolPointer(BazaarSettings::logForwardKey));
+ mapSetting(addToggleButton(QLatin1String("--include-merges"), tr("Include merges"),
+ tr("Show merged revisions")),
+ settings->boolPointer(BazaarSettings::logIncludeMergesKey));
+
+ QList<ComboBoxItem> logChoices;
+ logChoices << ComboBoxItem(tr("Detailed"), QLatin1String("long"))
+ << ComboBoxItem(tr("Moderately short"), QLatin1String("short"))
+ << ComboBoxItem(tr("One line"), QLatin1String("line"))
+ << ComboBoxItem(tr("GNU ChangeLog"), QLatin1String("gnu-changelog"));
+ mapSetting(addComboBox(QStringList(QLatin1String("--log-format=%1")), logChoices),
+ settings->stringPointer(BazaarSettings::logFormatKey));
+ }
+};
+
BazaarClient::BazaarClient(BazaarSettings *settings) :
VcsBaseClient(settings)
{
+ setDiffParameterWidgetCreator([=] { return new BazaarDiffParameterWidget(settings); });
+ setLogParameterWidgetCreator([=] { return new BazaarLogParameterWidget(settings); });
}
BazaarSettings *BazaarClient::settings() const
@@ -83,7 +140,7 @@ bool BazaarClient::synchronousSetUserId()
BranchInfo BazaarClient::synchronousBranchQuery(const QString &repositoryRoot) const
{
- QFile branchConfFile(repositoryRoot + QDir::separator() +
+ QFile branchConfFile(repositoryRoot + QLatin1Char('/') +
QLatin1String(Constants::BAZAARREPO) +
QLatin1String("/branch/branch.conf"));
if (!branchConfFile.open(QIODevice::ReadOnly))
@@ -253,112 +310,6 @@ BazaarClient::StatusItem BazaarClient::parseStatusLine(const QString &line) cons
return item;
}
-// Collect all parameters required for a diff or log to be able to associate
-// them with an editor and re-run the command with parameters.
-struct BazaarCommandParameters
-{
- BazaarCommandParameters(const QString &workDir,
- const QStringList &inFiles,
- const QStringList &options) :
- workingDir(workDir), files(inFiles), extraOptions(options)
- {
- }
-
- QString workingDir;
- QStringList files;
- QStringList extraOptions;
-};
-
-// Parameter widget controlling whitespace diff mode, associated with a parameter
-class BazaarDiffParameterWidget : public VcsBaseEditorParameterWidget
-{
- Q_OBJECT
-public:
- BazaarDiffParameterWidget(BazaarClient *client,
- const BazaarCommandParameters &p, QWidget *parent = 0) :
- VcsBaseEditorParameterWidget(parent), m_client(client), m_params(p)
- {
- mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace")),
- client->settings()->boolPointer(BazaarSettings::diffIgnoreWhiteSpaceKey));
- mapSetting(addToggleButton(QLatin1String("-B"), tr("Ignore Blank Lines")),
- client->settings()->boolPointer(BazaarSettings::diffIgnoreBlankLinesKey));
- }
-
- QStringList arguments() const
- {
- QStringList args;
- // Bazaar wants "--diff-options=-w -B.."
- const QStringList formatArguments = VcsBaseEditorParameterWidget::arguments();
- if (!formatArguments.isEmpty()) {
- const QString a = QLatin1String("--diff-options=")
- + formatArguments.join(QString(QLatin1Char(' ')));
- args.append(a);
- }
- return args;
- }
-
- void executeCommand()
- {
- m_client->diff(m_params.workingDir, m_params.files, m_params.extraOptions);
- }
-
-private:
- BazaarClient *m_client;
- const BazaarCommandParameters m_params;
-};
-
-VcsBaseEditorParameterWidget *BazaarClient::createDiffEditor(
- const QString &workingDir, const QStringList &files, const QStringList &extraOptions)
-{
- const BazaarCommandParameters parameters(workingDir, files, extraOptions);
- return new BazaarDiffParameterWidget(this, parameters);
-}
-
-class BazaarLogParameterWidget : public VcsBaseEditorParameterWidget
-{
- Q_OBJECT
-public:
- BazaarLogParameterWidget(BazaarClient *client,
- const BazaarCommandParameters &p, QWidget *parent = 0) :
- VcsBaseEditorParameterWidget(parent), m_client(client), m_params(p)
- {
- BazaarSettings *settings = m_client->settings();
- mapSetting(addToggleButton(QLatin1String("--verbose"), tr("Verbose"),
- tr("Show files changed in each revision")),
- settings->boolPointer(BazaarSettings::logVerboseKey));
- mapSetting(addToggleButton(QLatin1String("--forward"), tr("Forward"),
- tr("Show from oldest to newest")),
- settings->boolPointer(BazaarSettings::logForwardKey));
- mapSetting(addToggleButton(QLatin1String("--include-merges"), tr("Include merges"),
- tr("Show merged revisions")),
- settings->boolPointer(BazaarSettings::logIncludeMergesKey));
-
- QList<ComboBoxItem> logChoices;
- logChoices << ComboBoxItem(tr("Detailed"), QLatin1String("long"))
- << ComboBoxItem(tr("Moderately short"), QLatin1String("short"))
- << ComboBoxItem(tr("One line"), QLatin1String("line"))
- << ComboBoxItem(tr("GNU ChangeLog"), QLatin1String("gnu-changelog"));
- mapSetting(addComboBox(QStringList(QLatin1String("--log-format=%1")), logChoices),
- settings->stringPointer(BazaarSettings::logFormatKey));
- }
-
- void executeCommand()
- {
- m_client->log(m_params.workingDir, m_params.files, m_params.extraOptions);
- }
-
-private:
- BazaarClient *m_client;
- const BazaarCommandParameters m_params;
-};
-
-VcsBaseEditorParameterWidget *BazaarClient::createLogEditor(
- const QString &workingDir, const QStringList &files, const QStringList &extraOptions)
-{
- const BazaarCommandParameters parameters(workingDir, files, extraOptions);
- return new BazaarLogParameterWidget(this, parameters);
-}
-
} // namespace Internal
} // namespace Bazaar
diff --git a/src/plugins/bazaar/bazaarclient.h b/src/plugins/bazaar/bazaarclient.h
index a2f7c9baeef..acee6ba1f43 100644
--- a/src/plugins/bazaar/bazaarclient.h
+++ b/src/plugins/bazaar/bazaarclient.h
@@ -68,12 +68,6 @@ protected:
QString vcsCommandString(VcsCommandTag cmd) const;
Utils::ExitCodeInterpreter *exitCodeInterpreter(VcsCommandTag cmd, QObject *parent) const;
QStringList revisionSpec(const QString &revision) const;
- VcsBase::VcsBaseEditorParameterWidget *createDiffEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions);
- VcsBase::VcsBaseEditorParameterWidget *createLogEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions);
StatusItem parseStatusLine(const QString &line) const;
private:
diff --git a/src/plugins/bazaar/bazaarcontrol.cpp b/src/plugins/bazaar/bazaarcontrol.cpp
index 8e80f92ca84..aff54e5814d 100644
--- a/src/plugins/bazaar/bazaarcontrol.cpp
+++ b/src/plugins/bazaar/bazaarcontrol.cpp
@@ -86,9 +86,7 @@ bool BazaarControl::supportsOperation(Operation operation) const
case Core::IVersionControl::MoveOperation:
case Core::IVersionControl::CreateRepositoryOperation:
case Core::IVersionControl::AnnotateOperation:
- case Core::IVersionControl::GetRepositoryRootOperation:
break;
- case Core::IVersionControl::CheckoutOperation:
case Core::IVersionControl::SnapshotOperations:
supported = false;
break;
@@ -135,20 +133,6 @@ bool BazaarControl::vcsAnnotate(const QString &file, int line)
return true;
}
-bool BazaarControl::vcsCheckout(const QString &directory, const QByteArray &url)
-{
- Q_UNUSED(directory);
- Q_UNUSED(url);
- return false;
-}
-
-QString BazaarControl::vcsGetRepositoryURL(const QString &directory)
-{
- const QString repositoryRoot = m_bazaarClient->findTopLevelForFile(directory);
- const BranchInfo branchInfo = m_bazaarClient->synchronousBranchQuery(repositoryRoot);
- return branchInfo.isBoundToBranch ? branchInfo.branchLocation : QString();
-}
-
void BazaarControl::changed(const QVariant &v)
{
switch (v.type()) {
diff --git a/src/plugins/bazaar/bazaarcontrol.h b/src/plugins/bazaar/bazaarcontrol.h
index d12aa1be3e8..0313e4fb879 100644
--- a/src/plugins/bazaar/bazaarcontrol.h
+++ b/src/plugins/bazaar/bazaarcontrol.h
@@ -62,8 +62,6 @@ public:
bool vcsDelete(const QString &filename);
bool vcsMove(const QString &from, const QString &to);
bool vcsCreateRepository(const QString &directory);
- bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
bool vcsAnnotate(const QString &file, int line);
public slots:
diff --git a/src/plugins/bazaar/bazaarplugin.cpp b/src/plugins/bazaar/bazaarplugin.cpp
index 20440873fdf..7e7d5dac576 100644
--- a/src/plugins/bazaar/bazaarplugin.cpp
+++ b/src/plugins/bazaar/bazaarplugin.cpp
@@ -250,18 +250,16 @@ void BazaarPlugin::createMenu(const Context &context)
void BazaarPlugin::createFileActions(const Context &context)
{
- Core::Command *command;
-
m_annotateFile = new ParameterAction(tr("Annotate Current File"), tr("Annotate \"%1\""), ParameterAction::EnabledWithParameter, this);
- command = ActionManager::registerAction(m_annotateFile, ANNOTATE, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ Command *command = ActionManager::registerAction(m_annotateFile, ANNOTATE, context);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_annotateFile, SIGNAL(triggered()), this, SLOT(annotateCurrentFile()));
m_bazaarContainer->addAction(command);
m_commandLocator->appendCommand(command);
m_diffFile = new ParameterAction(tr("Diff Current File"), tr("Diff \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_diffFile, DIFF, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+Z,Meta+D") : tr("ALT+Z,Alt+D")));
connect(m_diffFile, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
m_bazaarContainer->addAction(command);
@@ -269,7 +267,7 @@ void BazaarPlugin::createFileActions(const Context &context)
m_logFile = new ParameterAction(tr("Log Current File"), tr("Log \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_logFile, LOG, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+Z,Meta+L") : tr("ALT+Z,Alt+L")));
connect(m_logFile, SIGNAL(triggered()), this, SLOT(logCurrentFile()));
m_bazaarContainer->addAction(command);
@@ -277,7 +275,7 @@ void BazaarPlugin::createFileActions(const Context &context)
m_statusFile = new ParameterAction(tr("Status Current File"), tr("Status \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_statusFile, STATUS, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+Z,Meta+S") : tr("ALT+Z,Alt+S")));
connect(m_statusFile, SIGNAL(triggered()), this, SLOT(statusCurrentFile()));
m_bazaarContainer->addAction(command);
@@ -287,21 +285,21 @@ void BazaarPlugin::createFileActions(const Context &context)
m_addAction = new ParameterAction(tr("Add"), tr("Add \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_addAction, ADD, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_addAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
m_bazaarContainer->addAction(command);
m_commandLocator->appendCommand(command);
m_deleteAction = new ParameterAction(tr("Delete..."), tr("Delete \"%1\"..."), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_deleteAction, DELETE, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_deleteAction, SIGNAL(triggered()), this, SLOT(promptToDeleteCurrentFile()));
m_bazaarContainer->addAction(command);
m_commandLocator->appendCommand(command);
m_revertFile = new ParameterAction(tr("Revert Current File..."), tr("Revert \"%1\"..."), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_revertFile, REVERT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_revertFile, SIGNAL(triggered()), this, SLOT(revertCurrentFile()));
m_bazaarContainer->addAction(command);
m_commandLocator->appendCommand(command);
@@ -360,12 +358,9 @@ void BazaarPlugin::statusCurrentFile()
void BazaarPlugin::createDirectoryActions(const Context &context)
{
- QAction *action;
- Core::Command *command;
-
- action = new QAction(tr("Diff"), this);
+ auto action = new QAction(tr("Diff"), this);
m_repositoryActionList.append(action);
- command = ActionManager::registerAction(action, DIFFMULTI, context);
+ Command *command = ActionManager::registerAction(action, DIFFMULTI, context);
connect(action, SIGNAL(triggered()), this, SLOT(diffRepository()));
m_bazaarContainer->addAction(command);
m_commandLocator->appendCommand(command);
@@ -431,12 +426,9 @@ void BazaarPlugin::statusMulti()
void BazaarPlugin::createRepositoryActions(const Context &context)
{
- QAction *action = 0;
- Core::Command *command = 0;
-
- action = new QAction(tr("Pull..."), this);
+ auto action = new QAction(tr("Pull..."), this);
m_repositoryActionList.append(action);
- command = ActionManager::registerAction(action, PULL, context);
+ Command *command = ActionManager::registerAction(action, PULL, context);
connect(action, SIGNAL(triggered()), this, SLOT(pull()));
m_bazaarContainer->addAction(command);
m_commandLocator->appendCommand(command);
@@ -470,7 +462,7 @@ void BazaarPlugin::createRepositoryActions(const Context &context)
m_bazaarContainer->addAction(command);
m_commandLocator->appendCommand(command);
- QAction *createRepositoryAction = new QAction(tr("Create Repository..."), this);
+ auto createRepositoryAction = new QAction(tr("Create Repository..."), this);
command = ActionManager::registerAction(createRepositoryAction, CREATE_REPOSITORY, context);
connect(createRepositoryAction, SIGNAL(triggered()), this, SLOT(createRepository()));
m_bazaarContainer->addAction(command);
@@ -535,11 +527,11 @@ void BazaarPlugin::update()
void BazaarPlugin::createSubmitEditorActions()
{
Context context(COMMIT_ID);
- Core::Command *command;
+ Command *command;
m_editorCommit = new QAction(VcsBaseSubmitEditor::submitIcon(), tr("Commit"), this);
command = ActionManager::registerAction(m_editorCommit, COMMIT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_editorCommit, SIGNAL(triggered()), this, SLOT(commitFromEditor()));
m_editorDiff = new QAction(VcsBaseSubmitEditor::diffIcon(), tr("Diff &Selected Files"), this);
@@ -562,8 +554,8 @@ void BazaarPlugin::commit()
m_submitRepository = state.topLevel();
- connect(m_client, SIGNAL(parsedStatus(QList<VcsBaseClient::StatusItem>)),
- this, SLOT(showCommitWidget(QList<VcsBaseClient::StatusItem>)));
+ QObject::connect(m_client, &VcsBaseClient::parsedStatus,
+ this, &BazaarPlugin::showCommitWidget);
// The "--short" option allows to easily parse status output
m_client->emitParsedStatus(m_submitRepository, QStringList(QLatin1String("--short")));
}
@@ -571,8 +563,8 @@ void BazaarPlugin::commit()
void BazaarPlugin::showCommitWidget(const QList<VcsBaseClient::StatusItem> &status)
{
//Once we receive our data release the connection so it can be reused elsewhere
- disconnect(m_client, SIGNAL(parsedStatus(QList<VcsBaseClient::StatusItem>)),
- this, SLOT(showCommitWidget(QList<VcsBaseClient::StatusItem>)));
+ QObject::disconnect(m_client, &VcsBaseClient::parsedStatus,
+ this, &BazaarPlugin::showCommitWidget);
if (status.isEmpty()) {
VcsOutputWindow::appendError(tr("There are no changes to commit."));
@@ -746,12 +738,12 @@ bool BazaarPlugin::submitEditorAboutToClose()
// Whether local commit or not
if (commitWidget->isLocalOptionEnabled())
extraOptions += QLatin1String("--local");
- m_client->commit(m_submitRepository, files, editorDocument->filePath(), extraOptions);
+ m_client->commit(m_submitRepository, files, editorDocument->filePath().toString(), extraOptions);
}
return true;
}
-void BazaarPlugin::updateActions(VcsBase::VcsBasePlugin::ActionState as)
+void BazaarPlugin::updateActions(VcsBasePlugin::ActionState as)
{
if (!enableMenuAction(as, m_menuAction)) {
m_commandLocator->setEnabled(false);
diff --git a/src/plugins/bazaar/clonewizard.cpp b/src/plugins/bazaar/clonewizard.cpp
index 428a7723355..29a743927d7 100644
--- a/src/plugins/bazaar/clonewizard.cpp
+++ b/src/plugins/bazaar/clonewizard.cpp
@@ -38,7 +38,7 @@
#include <coreplugin/iversioncontrol.h>
#include <vcsbase/vcscommand.h>
#include <vcsbase/vcsbaseconstants.h>
-#include <vcsbase/vcsconfigurationpage.h>
+#include <vcsbase/wizard/vcsconfigurationpage.h>
#include <QDebug>
@@ -58,9 +58,12 @@ CloneWizard::CloneWizard(const Utils::FileName &path, QWidget *parent) :
setStartedStatus(tr("Cloning started..."));
const Core::IVersionControl *vc = BazaarPlugin::instance()->versionControl();
- if (!vc->isConfigured())
- addPage(new VcsConfigurationPage(vc));
- CloneWizardPage *page = new CloneWizardPage;
+ if (!vc->isConfigured()) {
+ auto configPage = new VcsConfigurationPage;
+ configPage->setVersionControl(vc);
+ addPage(configPage);
+ }
+ auto page = new CloneWizardPage;
page->setPath(path.toString());
addPage(page);
}
@@ -102,8 +105,8 @@ VcsCommand *CloneWizard::createCommand(Utils::FileName *checkoutDir)
args << client->vcsCommandString(BazaarClient::CloneCommand)
<< extraOptions << cwp->repository() << cwp->directory();
- VcsCommand *command = new VcsCommand(settings.binaryPath(), cwp->path(),
- client->processEnvironment());
+ auto command = new VcsCommand(settings.binaryPath(), cwp->path(),
+ client->processEnvironment());
command->addJob(args, -1);
return command;
}
diff --git a/src/plugins/bazaar/uncommitdialog.cpp b/src/plugins/bazaar/uncommitdialog.cpp
index 0936f703b89..c63de8de54c 100644
--- a/src/plugins/bazaar/uncommitdialog.cpp
+++ b/src/plugins/bazaar/uncommitdialog.cpp
@@ -45,10 +45,10 @@ UnCommitDialog::UnCommitDialog(QWidget *parent)
{
m_ui->setupUi(this);
- QPushButton* dryRunBtn = new QPushButton(tr("Dry Run"));
+ auto dryRunBtn = new QPushButton(tr("Dry Run"));
dryRunBtn->setToolTip(tr("Test the outcome of removing the last committed revision, without actually removing anything."));
m_ui->buttonBox->addButton(dryRunBtn, QDialogButtonBox::ApplyRole);
- connect(dryRunBtn, SIGNAL(clicked()), this, SLOT(dryRun()));
+ connect(dryRunBtn, &QPushButton::clicked, this, &UnCommitDialog::dryRun);
}
UnCommitDialog::~UnCommitDialog()
diff --git a/src/plugins/beautifier/artisticstyle/artisticstyle.cpp b/src/plugins/beautifier/artisticstyle/artisticstyle.cpp
index df1012020c6..af81a9726d9 100644
--- a/src/plugins/beautifier/artisticstyle/artisticstyle.cpp
+++ b/src/plugins/beautifier/artisticstyle/artisticstyle.cpp
@@ -49,7 +49,7 @@
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <cppeditor/cppeditorconstants.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
@@ -84,7 +84,7 @@ bool ArtisticStyle::initialize()
Constants::ArtisticStyle::ACTION_FORMATFILE,
Core::Context(Core::Constants::C_GLOBAL));
menu->addAction(cmd);
- connect(m_formatFile, SIGNAL(triggered()), this, SLOT(formatFile()));
+ connect(m_formatFile, &QAction::triggered, this, &ArtisticStyle::formatFile);
Core::ActionManager::actionContainer(Constants::MENU_ID)->addMenu(menu);
@@ -108,7 +108,7 @@ void ArtisticStyle::formatFile()
if (m_settings->useOtherFiles()) {
if (const ProjectExplorer::Project *project
- = ProjectExplorer::ProjectExplorerPlugin::currentProject()) {
+ = ProjectExplorer::ProjectTree::currentProject()) {
const QStringList files = project->files(ProjectExplorer::Project::AllFiles);
for (int i = 0, total = files.size(); i < total; ++i) {
const QString &file = files.at(i);
diff --git a/src/plugins/beautifier/beautifierplugin.cpp b/src/plugins/beautifier/beautifierplugin.cpp
index 3e387763857..bc10838bfde 100644
--- a/src/plugins/beautifier/beautifierplugin.cpp
+++ b/src/plugins/beautifier/beautifierplugin.cpp
@@ -74,7 +74,7 @@ BeautifierPlugin::BeautifierPlugin() :
{
connect(m_asyncFormatMapper, SIGNAL(mapped(QObject*)),
this, SLOT(formatCurrentFileContinue(QObject*)));
- connect(this, SIGNAL(pipeError(QString)), this, SLOT(showError(QString)));
+ connect(this, &BeautifierPlugin::pipeError, this, &BeautifierPlugin::showError);
}
BeautifierPlugin::~BeautifierPlugin()
@@ -220,25 +220,22 @@ QString BeautifierPlugin::format(const QString &text, const Command &command,
void BeautifierPlugin::formatCurrentFile(const Command &command)
{
- QPlainTextEdit *textEditor = 0;
- QString filePath;
- if (BaseTextEditor *editor = BaseTextEditor::currentTextEditor()) {
- textEditor = editor->editorWidget();
- filePath = editor->document()->filePath();
- }
- if (!textEditor)
+ TextEditorWidget *widget = TextEditorWidget::currentTextEditorWidget();
+ if (!widget)
return;
- const QString sourceData = textEditor->toPlainText();
+ const QString sourceData = widget->toPlainText();
if (sourceData.isEmpty())
return;
QFutureWatcher<FormatTask> *watcher = new QFutureWatcher<FormatTask>;
- connect(textEditor->document(), SIGNAL(contentsChanged()), watcher, SLOT(cancel()));
+ connect(widget->textDocument(), &TextDocument::contentsChanged,
+ watcher, &QFutureWatcher<FormatTask>::cancel);
connect(watcher, SIGNAL(finished()), m_asyncFormatMapper, SLOT(map()));
m_asyncFormatMapper->setMapping(watcher, watcher);
+ const QString filePath = widget->textDocument()->filePath().toString();
watcher->setFuture(QtConcurrent::run(&BeautifierPlugin::formatAsync, this,
- FormatTask(textEditor, filePath, sourceData, command)));
+ FormatTask(widget, filePath, sourceData, command)));
}
void BeautifierPlugin::formatAsync(QFutureInterface<FormatTask> &future, FormatTask task)
diff --git a/src/plugins/beautifier/clangformat/clangformat.cpp b/src/plugins/beautifier/clangformat/clangformat.cpp
index 5cb89f082b3..206b49b4df1 100644
--- a/src/plugins/beautifier/clangformat/clangformat.cpp
+++ b/src/plugins/beautifier/clangformat/clangformat.cpp
@@ -80,14 +80,14 @@ bool ClangFormat::initialize()
Constants::ClangFormat::ACTION_FORMATFILE,
Core::Context(Core::Constants::C_GLOBAL));
menu->addAction(cmd);
- connect(m_formatFile, SIGNAL(triggered()), this, SLOT(formatFile()));
+ connect(m_formatFile, &QAction::triggered, this, &ClangFormat::formatFile);
m_formatRange = new QAction(BeautifierPlugin::msgFormatSelectedText(), this);
cmd = Core::ActionManager::registerAction(m_formatRange,
Constants::ClangFormat::ACTION_FORMATSELECTED,
Core::Context(Core::Constants::C_GLOBAL));
menu->addAction(cmd);
- connect(m_formatRange, SIGNAL(triggered()), this, SLOT(formatSelectedText()));
+ connect(m_formatRange, &QAction::triggered, this, &ClangFormat::formatSelectedText);
Core::ActionManager::actionContainer(Constants::MENU_ID)->addMenu(menu);
@@ -114,11 +114,11 @@ void ClangFormat::formatFile()
void ClangFormat::formatSelectedText()
{
- TextEditor::BaseTextEditor *editor = TextEditor::BaseTextEditor::currentTextEditor();
- if (!editor)
+ TextEditor::TextEditorWidget *widget = TextEditor::TextEditorWidget::currentTextEditorWidget();
+ if (!widget)
return;
- QTextCursor tc = editor->textCursor();
+ QTextCursor tc = widget->textCursor();
if (tc.hasSelection()) {
const int offset = tc.selectionStart();
const int length = tc.selectionEnd() - offset;
diff --git a/src/plugins/beautifier/configurationdialog.cpp b/src/plugins/beautifier/configurationdialog.cpp
index f3e8eb7fb00..1edb17cf840 100644
--- a/src/plugins/beautifier/configurationdialog.cpp
+++ b/src/plugins/beautifier/configurationdialog.cpp
@@ -55,7 +55,7 @@ ConfigurationDialog::ConfigurationDialog(QWidget *parent) :
ui->name->setValidator(fileNameValidator);
updateDocumentation();
- connect(ui->name, SIGNAL(textChanged(QString)), this, SLOT(updateOkButton()));
+ connect(ui->name, &QLineEdit::textChanged, this, &ConfigurationDialog::updateOkButton);
updateOkButton(); // force initial test.
connect(ui->editor, SIGNAL(documentationChanged(QString,QString)),
this, SLOT(updateDocumentation(QString,QString)));
diff --git a/src/plugins/beautifier/configurationeditor.cpp b/src/plugins/beautifier/configurationeditor.cpp
index 7fa8634382e..f435409cfa7 100644
--- a/src/plugins/beautifier/configurationeditor.cpp
+++ b/src/plugins/beautifier/configurationeditor.cpp
@@ -112,13 +112,15 @@ ConfigurationEditor::ConfigurationEditor(QWidget *parent)
m_completer->setCaseSensitivity(Qt::CaseInsensitive);
m_completer->popup()->installEventFilter(this);
- connect(m_completer, SIGNAL(activated(QString)), this, SLOT(insertCompleterText(QString)));
- connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(updateDocumentation()));
+ connect(m_completer, static_cast<void (QCompleter::*)(const QString &)>(&QCompleter::activated),
+ this, &ConfigurationEditor::insertCompleterText);
+ connect(this, &ConfigurationEditor::cursorPositionChanged,
+ this, &ConfigurationEditor::updateDocumentation);
}
void ConfigurationEditor::setSettings(AbstractSettings *settings)
{
- QTC_CHECK(settings);
+ QTC_ASSERT(settings, return);
m_settings = settings;
QStringList keywords = m_settings->options();
diff --git a/src/plugins/beautifier/configurationpanel.cpp b/src/plugins/beautifier/configurationpanel.cpp
index c79cde95cc6..cd8a148aca0 100644
--- a/src/plugins/beautifier/configurationpanel.cpp
+++ b/src/plugins/beautifier/configurationpanel.cpp
@@ -45,10 +45,11 @@ ConfigurationPanel::ConfigurationPanel(QWidget *parent) :
m_settings(0)
{
ui->setupUi(this);
- connect(ui->add, SIGNAL(clicked()), this, SLOT(add()));
- connect(ui->edit, SIGNAL(clicked()), this, SLOT(edit()));
- connect(ui->remove, SIGNAL(clicked()), this, SLOT(remove()));
- connect(ui->configurations, SIGNAL(currentIndexChanged(int)), this, SLOT(updateButtons()));
+ connect(ui->add, &QPushButton::clicked, this, &ConfigurationPanel::add);
+ connect(ui->edit, &QPushButton::clicked, this, &ConfigurationPanel::edit);
+ connect(ui->remove, &QPushButton::clicked, this, &ConfigurationPanel::remove);
+ connect(ui->configurations, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &ConfigurationPanel::updateButtons);
}
ConfigurationPanel::~ConfigurationPanel()
diff --git a/src/plugins/beautifier/uncrustify/uncrustify.cpp b/src/plugins/beautifier/uncrustify/uncrustify.cpp
index 21cf9e415ab..656974fbabd 100644
--- a/src/plugins/beautifier/uncrustify/uncrustify.cpp
+++ b/src/plugins/beautifier/uncrustify/uncrustify.cpp
@@ -49,7 +49,7 @@
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <cppeditor/cppeditorconstants.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <utils/fileutils.h>
@@ -83,7 +83,7 @@ bool Uncrustify::initialize()
Constants::Uncrustify::ACTION_FORMATFILE,
Core::Context(Core::Constants::C_GLOBAL));
menu->addAction(cmd);
- connect(m_formatFile, SIGNAL(triggered()), this, SLOT(formatFile()));
+ connect(m_formatFile, &QAction::triggered, this, &Uncrustify::formatFile);
Core::ActionManager::actionContainer(Constants::MENU_ID)->addMenu(menu);
@@ -107,7 +107,7 @@ void Uncrustify::formatFile()
if (m_settings->useOtherFiles()) {
if (const ProjectExplorer::Project *project
- = ProjectExplorer::ProjectExplorerPlugin::currentProject()) {
+ = ProjectExplorer::ProjectTree::currentProject()) {
const QStringList files = project->files(ProjectExplorer::Project::AllFiles);
for (int i = 0, total = files.size(); i < total; ++i) {
const QString &file = files.at(i);
diff --git a/src/plugins/bineditor/bineditor.cpp b/src/plugins/bineditor/bineditor.cpp
index 339fd4f1c1a..e1ee3f2fb2a 100644
--- a/src/plugins/bineditor/bineditor.cpp
+++ b/src/plugins/bineditor/bineditor.cpp
@@ -1380,8 +1380,9 @@ void BinEditorWidget::copy(bool raw)
tr("You cannot copy more than 4 MB of binary data."));
return;
}
- const QByteArray &data = dataMid(selStart, selectionLength);
+ QByteArray data = dataMid(selStart, selectionLength);
if (raw) {
+ data.replace(0, ' ');
QApplication::clipboard()->setText(QString::fromLatin1(data));
return;
}
diff --git a/src/plugins/bineditor/bineditorplugin.cpp b/src/plugins/bineditor/bineditorplugin.cpp
index 2b1782cea0b..d8b0bfdac12 100644
--- a/src/plugins/bineditor/bineditorplugin.cpp
+++ b/src/plugins/bineditor/bineditorplugin.cpp
@@ -61,6 +61,7 @@
#include <utils/reloadpromptutils.h>
#include <utils/qtcassert.h>
+using namespace Utils;
using namespace Core;
namespace BinEditor {
@@ -90,7 +91,7 @@ public:
namespace Internal {
-class BinEditorFind : public Core::IFindSupport
+class BinEditorFind : public IFindSupport
{
Q_OBJECT
@@ -106,7 +107,7 @@ public:
QString currentFindString() const { return QString(); }
QString completedFindString() const { return QString(); }
- Core::FindFlags supportedFindFlags() const
+ FindFlags supportedFindFlags() const
{
return FindBackward | FindCaseSensitively;
}
@@ -117,7 +118,7 @@ public:
m_incrementalWrappedState = false;
}
- virtual void highlightAll(const QString &txt, Core::FindFlags findFlags)
+ virtual void highlightAll(const QString &txt, FindFlags findFlags)
{
m_widget->highlightSearchResults(txt.toLatin1(), textDocumentFlagsForFindFlags(findFlags));
}
@@ -127,7 +128,7 @@ public:
m_widget->highlightSearchResults(QByteArray());
}
- int find(const QByteArray &pattern, int pos, Core::FindFlags findFlags, bool *wrapped)
+ int find(const QByteArray &pattern, int pos, FindFlags findFlags, bool *wrapped)
{
if (wrapped)
*wrapped = false;
@@ -148,7 +149,7 @@ public:
return res;
}
- Result findIncremental(const QString &txt, Core::FindFlags findFlags) {
+ Result findIncremental(const QString &txt, FindFlags findFlags) {
QByteArray pattern = txt.toLatin1();
if (pattern != m_lastPattern)
resetIncrementalSearch(); // Because we don't search for nibbles.
@@ -183,7 +184,7 @@ public:
return result;
}
- Result findStep(const QString &txt, Core::FindFlags findFlags) {
+ Result findStep(const QString &txt, FindFlags findFlags) {
QByteArray pattern = txt.toLatin1();
bool wasReset = (m_incrementalStartPos < 0);
if (m_contPos == -1) {
@@ -223,12 +224,12 @@ private:
};
-class BinEditorDocument : public Core::IDocument
+class BinEditorDocument : public IDocument
{
Q_OBJECT
public:
BinEditorDocument(BinEditorWidget *parent) :
- Core::IDocument(parent)
+ IDocument(parent)
{
setId(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID);
setMimeType(QLatin1String(BinEditor::Constants::C_BINEDITOR_MIMETYPE));
@@ -256,9 +257,8 @@ public:
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
- = fn.isEmpty() ? filePath() : fn;
- if (m_widget->save(errorString, filePath(), fileNameToUse)) {
+ const FileName fileNameToUse = fn.isEmpty() ? filePath() : FileName::fromString(fn);
+ if (m_widget->save(errorString, filePath().toString(), fileNameToUse.toString())) {
setFilePath(fileNameToUse);
return true;
} else {
@@ -274,14 +274,14 @@ public:
if (errorString)
*errorString = msg;
else
- QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"), msg);
+ QMessageBox::critical(ICore::mainWindow(), tr("File Error"), msg);
return false;
}
if (offset >= size)
return false;
if (file.open(QIODevice::ReadOnly)) {
file.close();
- setFilePath(fileName);
+ setFilePath(FileName::fromString(fileName));
m_widget->setSizes(offset, file.size());
return true;
}
@@ -290,17 +290,17 @@ public:
if (errorString)
*errorString = errStr;
else
- QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"), errStr);
+ QMessageBox::critical(ICore::mainWindow(), tr("File Error"), errStr);
return false;
}
private slots:
void provideData(quint64 block)
{
- const QString fn = filePath();
+ const FileName fn = filePath();
if (fn.isEmpty())
return;
- QFile file(fn);
+ QFile file(fn.toString());
if (file.open(QIODevice::ReadOnly)) {
int blockSize = m_widget->dataBlockSize();
file.seek(block * blockSize);
@@ -311,15 +311,15 @@ private slots:
data += QByteArray(blockSize - dataSize, 0);
m_widget->addData(block, data);
} else {
- QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"),
+ QMessageBox::critical(ICore::mainWindow(), tr("File Error"),
tr("Cannot open %1: %2").arg(
- QDir::toNativeSeparators(fn), file.errorString()));
+ fn.toUserOutput(), file.errorString()));
}
}
void provideNewRange(quint64 offset)
{
- open(0, filePath(), offset);
+ open(0, filePath().toString(), offset);
}
public:
@@ -332,11 +332,10 @@ public:
: m_widget->isModified(); }
bool isFileReadOnly() const {
- const QString fn = filePath();
+ const FileName fn = filePath();
if (fn.isEmpty())
return false;
- const QFileInfo fi(fn);
- return !fi.isWritable();
+ return !fn.toFileInfo().isWritable();
}
bool isSaveAsAllowed() const { return true; }
@@ -350,7 +349,7 @@ public:
emit aboutToReload();
int cPos = m_widget->cursorPosition();
m_widget->clear();
- const bool success = open(errorString, filePath());
+ const bool success = open(errorString, filePath().toString());
m_widget->setCursorPosition(cPos);
emit reloadFinished(success);
return success;
@@ -362,7 +361,7 @@ private:
BinEditorWidget *m_widget;
};
-class BinEditor : public Core::IEditor
+class BinEditor : public IEditor
{
Q_OBJECT
public:
@@ -407,7 +406,7 @@ public:
QTC_ASSERT(fileName == realFileName, return false); // The bineditor can do no autosaving
return m_file->open(errorString, fileName);
}
- Core::IDocument *document() { return m_file; }
+ IDocument *document() { return m_file; }
QWidget *toolBar() { return m_toolBar; }
@@ -446,7 +445,7 @@ BinEditorFactory::BinEditorFactory(BinEditorPlugin *owner) :
addMimeType(Constants::C_BINEDITOR_MIMETYPE);
}
-Core::IEditor *BinEditorFactory::createEditor()
+IEditor *BinEditorFactory::createEditor()
{
BinEditorWidget *widget = new BinEditorWidget();
BinEditor *editor = new BinEditor(widget);
@@ -467,14 +466,14 @@ BinEditorPlugin::~BinEditorPlugin()
{
}
-QAction *BinEditorPlugin::registerNewAction(Core::Id id, const QString &title)
+QAction *BinEditorPlugin::registerNewAction(Id id, const QString &title)
{
QAction *result = new QAction(title, this);
- Core::ActionManager::registerAction(result, id, m_context);
+ ActionManager::registerAction(result, id, m_context);
return result;
}
-QAction *BinEditorPlugin::registerNewAction(Core::Id id,
+QAction *BinEditorPlugin::registerNewAction(Id id,
QObject *receiver,
const char *slot,
const QString &title)
@@ -523,7 +522,7 @@ void BinEditorPlugin::extensionsInitialized()
{
}
-void BinEditorPlugin::updateCurrentEditor(Core::IEditor *editor)
+void BinEditorPlugin::updateCurrentEditor(IEditor *editor)
{
BinEditorWidget *binEditor = 0;
if (editor)
diff --git a/src/plugins/bookmarks/bookmarkmanager.cpp b/src/plugins/bookmarks/bookmarkmanager.cpp
index 5c53842dae5..fbca8c0a726 100644
--- a/src/plugins/bookmarks/bookmarkmanager.cpp
+++ b/src/plugins/bookmarks/bookmarkmanager.cpp
@@ -42,7 +42,6 @@
#include <projectexplorer/session.h>
#include <texteditor/texteditor.h>
#include <utils/tooltip/tooltip.h>
-#include <utils/tooltip/tipcontents.h>
#include <utils/qtcassert.h>
#include <utils/checkablemessagebox.h>
@@ -210,17 +209,17 @@ void BookmarkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti
}
BookmarkView::BookmarkView(BookmarkManager *manager) :
- m_bookmarkContext(new Core::IContext(this)),
+ m_bookmarkContext(new IContext(this)),
m_manager(manager)
{
setWindowTitle(tr("Bookmarks"));
m_bookmarkContext->setWidget(this);
- m_bookmarkContext->setContext(Core::Context(Constants::BOOKMARKS_CONTEXT));
+ m_bookmarkContext->setContext(Context(Constants::BOOKMARKS_CONTEXT));
ICore::addContextObject(m_bookmarkContext);
- Utils::ListView::setModel(manager);
+ ListView::setModel(manager);
setItemDelegate(new BookmarkDelegate(this));
setFrameStyle(QFrame::NoFrame);
@@ -290,12 +289,12 @@ void BookmarkView::keyPressEvent(QKeyEvent *event)
event->accept();
return;
}
- Utils::ListView::keyPressEvent(event);
+ ListView::keyPressEvent(event);
}
void BookmarkView::removeAll()
{
- if (Utils::CheckableMessageBox::doNotAskAgainQuestion(this,
+ if (CheckableMessageBox::doNotAskAgainQuestion(this,
tr("Remove All Bookmarks"),
tr("Are you sure you want to remove all bookmarks from all files in the current session?"),
ICore::settings(),
@@ -324,7 +323,7 @@ BookmarkManager::BookmarkManager() :
m_bookmarkIcon(QLatin1String(":/bookmarks/images/bookmark.png")),
m_selectionModel(new QItemSelectionModel(this, this))
{
- connect(Core::ICore::instance(), &ICore::contextChanged,
+ connect(ICore::instance(), &ICore::contextChanged,
this, &BookmarkManager::updateActionStatus);
connect(SessionManager::instance(), &SessionManager::sessionLoaded,
@@ -389,7 +388,7 @@ QVariant BookmarkManager::data(const QModelIndex &index, int role) const
Bookmark *bookMark = m_bookmarksList.at(index.row());
if (role == BookmarkManager::Filename)
- return QFileInfo(bookMark->fileName()).fileName();
+ return FileName::fromString(bookMark->fileName()).fileName();
if (role == BookmarkManager::LineNumber)
return bookMark->lineNumber();
if (role == BookmarkManager::Directory)
@@ -422,7 +421,7 @@ QStringList BookmarkManager::mimeTypes() const
QMimeData *BookmarkManager::mimeData(const QModelIndexList &indexes) const
{
- auto data = new Utils::FileDropMimeData;
+ auto data = new FileDropMimeData;
foreach (const QModelIndex &index, indexes) {
if (!index.isValid() || index.column() != 0 || index.row() < 0 || index.row() >= m_bookmarksList.count())
continue;
@@ -438,7 +437,7 @@ void BookmarkManager::toggleBookmark(bool)
if (!editor)
return;
- toggleBookmark(editor->document()->filePath(), editor->currentLine());
+ toggleBookmark(editor->document()->filePath().toString(), editor->currentLine());
}
void BookmarkManager::toggleBookmark(const QString &fileName, int lineNumber)
@@ -556,7 +555,7 @@ void BookmarkManager::documentPrevNext(bool next)
if (editorLine <= 0)
return;
- QFileInfo fi(editor->document()->filePath());
+ const QFileInfo fi = editor->document()->filePath().toFileInfo();
if (!m_bookmarksMap.contains(fi.path()))
return;
@@ -647,7 +646,7 @@ BookmarkManager::State BookmarkManager::state() const
if (!editor)
return HasBookMarks;
- const QFileInfo fi(editor->document()->filePath());
+ const QFileInfo fi = editor->document()->filePath().toFileInfo();
const DirectoryFileBookmarksMap::const_iterator dit = m_bookmarksMap.constFind(fi.path());
if (dit == m_bookmarksMap.constEnd())
@@ -834,7 +833,7 @@ void BookmarkManager::operateTooltip(QWidget *widget, const QPoint &pos, Bookmar
if (mark->note().isEmpty())
ToolTip::hide();
else
- ToolTip::show(pos, TextContent(mark->note()), widget);
+ ToolTip::show(pos, mark->note(), widget);
}
/* Loads the bookmarks from the session settings. */
@@ -850,7 +849,7 @@ void BookmarkManager::loadBookmarks()
void BookmarkManager::handleBookmarkTooltipRequest(IEditor *editor, const QPoint &pos, int line)
{
- Bookmark *mark = findBookmark(editor->document()->filePath(), line);
+ Bookmark *mark = findBookmark(editor->document()->filePath().toString(), line);
operateTooltip(editor->widget(), pos, mark);
}
@@ -862,7 +861,7 @@ BookmarkViewFactory::BookmarkViewFactory(BookmarkManager *bm)
setDisplayName(BookmarkView::tr("Bookmarks"));
setPriority(300);
setId("Bookmarks");
- setActivationSequence(QKeySequence(Core::UseMacShortcuts ? tr("Alt+Meta+M") : tr("Alt+M")));
+ setActivationSequence(QKeySequence(UseMacShortcuts ? tr("Alt+Meta+M") : tr("Alt+M")));
}
NavigationView BookmarkViewFactory::createWidget()
diff --git a/src/plugins/bookmarks/bookmarksplugin.cpp b/src/plugins/bookmarks/bookmarksplugin.cpp
index bf9eb155067..968861d6f9c 100644
--- a/src/plugins/bookmarks/bookmarksplugin.cpp
+++ b/src/plugins/bookmarks/bookmarksplugin.cpp
@@ -110,7 +110,7 @@ bool BookmarksPlugin::initialize(const QStringList & /*arguments*/, QString *)
connect(m_toggleAction, &QAction::triggered, [this]() {
if (BaseTextEditor *editor = BaseTextEditor::currentTextEditor())
- m_bookmarkManager->toggleBookmark(editor->document()->filePath(), editor->currentLine());
+ m_bookmarkManager->toggleBookmark(editor->document()->filePath().toString(), editor->currentLine());
});
connect(m_prevAction, &QAction::triggered, m_bookmarkManager, &BookmarkManager::prev);
@@ -165,7 +165,7 @@ void BookmarksPlugin::editorOpened(IEditor *editor)
connect(widget, &TextEditorWidget::markRequested, m_bookmarkManager,
[this, editor](TextEditorWidget *, int line, TextMarkRequestKind kind) {
if (kind == BookmarkRequest && editor->document())
- m_bookmarkManager->toggleBookmark(editor->document()->filePath(), line);
+ m_bookmarkManager->toggleBookmark(editor->document()->filePath().toString(), line);
});
@@ -196,7 +196,7 @@ void BookmarksPlugin::requestContextMenu(TextEditorWidget *widget,
return;
m_bookmarkMarginActionLineNumber = lineNumber;
- m_bookmarkMarginActionFileName = widget->textDocument()->filePath();
+ m_bookmarkMarginActionFileName = widget->textDocument()->filePath().toString();
menu->addAction(m_bookmarkMarginAction);
if (m_bookmarkManager->hasBookmarkInPosition(m_bookmarkMarginActionFileName, m_bookmarkMarginActionLineNumber))
diff --git a/src/plugins/clangcodemodel/clangcodemodelplugin.cpp b/src/plugins/clangcodemodel/clangcodemodelplugin.cpp
index 04878f94082..7028365e890 100644
--- a/src/plugins/clangcodemodel/clangcodemodelplugin.cpp
+++ b/src/plugins/clangcodemodel/clangcodemodelplugin.cpp
@@ -29,24 +29,17 @@
****************************************************************************/
#include "clangcodemodelplugin.h"
+
#include "clangprojectsettingspropertiespage.h"
#include "pchmanager.h"
#include "utils.h"
-#include <coreplugin/coreconstants.h>
-#include <coreplugin/icore.h>
-#include <coreplugin/imode.h>
-#include <coreplugin/modemanager.h>
-#include <coreplugin/id.h>
-
#include <cpptools/cppmodelmanager.h>
#include <projectexplorer/projectpanelfactory.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
-#include <QtPlugin>
-
namespace ClangCodeModel {
namespace Internal {
@@ -55,32 +48,34 @@ bool ClangCodeModelPlugin::initialize(const QStringList &arguments, QString *err
Q_UNUSED(arguments)
Q_UNUSED(errorMessage)
+ // Register widget for project panel
auto panelFactory = new ProjectExplorer::ProjectPanelFactory();
panelFactory->setPriority(60);
panelFactory->setDisplayName(ClangProjectSettingsWidget::tr("Clang Settings"));
panelFactory->setSimpleCreateWidgetFunction<ClangProjectSettingsWidget>(QIcon());
-
ProjectExplorer::ProjectPanelFactory::registerFactory(panelFactory);
+ // Initialize Clang
ClangCodeModel::Internal::initializeClang();
- PchManager *pchManager = new PchManager(this);
-
+ // Set up Indexer
+ auto cppModelManager = CppTools::CppModelManager::instance();
#ifdef CLANG_INDEXING
m_indexer.reset(new ClangIndexer);
- CppTools::CppModelManager::instance()->setIndexingSupport(m_indexer->indexingSupport());
+ cppModelManager->setIndexingSupport(m_indexer->indexingSupport());
#endif // CLANG_INDEXING
- // wire up the pch manager
- QObject *session = ProjectExplorer::SessionManager::instance();
- connect(session, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
- pchManager, SLOT(onAboutToRemoveProject(ProjectExplorer::Project*)));
- connect(CppTools::CppModelManager::instance(), SIGNAL(projectPartsUpdated(ProjectExplorer::Project*)),
- pchManager, SLOT(onProjectPartsUpdated(ProjectExplorer::Project*)));
+ // Set up PchManager
+ PchManager *pchManager = new PchManager(this);
+ ProjectExplorer::SessionManager *sessionManager = ProjectExplorer::SessionManager::instance();
+ connect(sessionManager, &ProjectExplorer::SessionManager::aboutToRemoveProject,
+ pchManager, &PchManager::onAboutToRemoveProject);
+ connect(cppModelManager, &CppTools::CppModelManager::projectPartsUpdated,
+ pchManager, &PchManager::onProjectPartsUpdated);
+ // Register ModelManagerSupport
m_modelManagerSupport.reset(new ModelManagerSupport);
- CppTools::CppModelManager::instance()->addModelManagerSupport(
- m_modelManagerSupport.data());
+ cppModelManager->addModelManagerSupport(m_modelManagerSupport.data());
return true;
}
diff --git a/src/plugins/clangcodemodel/clangcodemodelplugin.h b/src/plugins/clangcodemodel/clangcodemodelplugin.h
index f2873c21bac..a30c328bead 100644
--- a/src/plugins/clangcodemodel/clangcodemodelplugin.h
+++ b/src/plugins/clangcodemodel/clangcodemodelplugin.h
@@ -28,8 +28,8 @@
**
****************************************************************************/
-#ifndef CLANGPLUGIN_H
-#define CLANGPLUGIN_H
+#ifndef CLANGCODEMODELPLUGIN_H
+#define CLANGCODEMODELPLUGIN_H
#include "clangmodelmanagersupport.h"
@@ -39,6 +39,8 @@
#include <extensionsystem/iplugin.h>
+#include <QScopedPointer>
+
namespace ClangCodeModel {
namespace Internal {
@@ -49,7 +51,6 @@ class ClangCodeModelPlugin: public ExtensionSystem::IPlugin
public:
bool initialize(const QStringList &arguments, QString *errorMessage);
-
void extensionsInitialized();
private:
@@ -72,4 +73,4 @@ private slots:
} // namespace Internal
} // namespace Clang
-#endif // CLANGPLUGIN_H
+#endif // CLANGCODEMODELPLUGIN_H
diff --git a/src/plugins/clangcodemodel/clangcompleter.cpp b/src/plugins/clangcodemodel/clangcompleter.cpp
index 0ab51518b78..2f67bffc8ef 100644
--- a/src/plugins/clangcodemodel/clangcompleter.cpp
+++ b/src/plugins/clangcodemodel/clangcompleter.cpp
@@ -46,12 +46,16 @@
//#define TIME_COMPLETION
-class ClangCodeModel::ClangCompleter::PrivateData
+using namespace ClangCodeModel::Internal;
+
+namespace ClangCodeModel {
+
+class ClangCompleter::PrivateData
{
public:
PrivateData()
: m_mutex(QMutex::Recursive)
- , m_unit(Internal::Unit::create())
+ , m_unit(Unit::create())
, m_isSignalSlotCompletion(false)
{
}
@@ -60,7 +64,7 @@ public:
{
}
- bool parseFromFile(const Internal::UnsavedFiles &unsavedFiles)
+ bool parseFromFile(const UnsavedFiles &unsavedFiles)
{
Q_ASSERT(!m_unit->isLoaded());
if (m_unit->fileName().isEmpty())
@@ -80,13 +84,10 @@ public:
public:
QMutex m_mutex;
- Internal::Unit::Ptr m_unit;
+ Unit::Ptr m_unit;
bool m_isSignalSlotCompletion;
};
-using namespace ClangCodeModel;
-using namespace ClangCodeModel::Internal;
-
/**
* @brief Constructs with highest possible priority
*/
@@ -127,7 +128,7 @@ QString ClangCompleter::fileName() const
void ClangCompleter::setFileName(const QString &fileName)
{
if (d->m_unit->fileName() != fileName) {
- d->m_unit = Internal::Unit::create(fileName);
+ d->m_unit = Unit::create(fileName);
}
}
@@ -208,3 +209,5 @@ QMutex *ClangCompleter::mutex() const
{
return &d->m_mutex;
}
+
+} // namespace ClangCodeModel
diff --git a/src/plugins/clangcodemodel/clangcompletion.cpp b/src/plugins/clangcodemodel/clangcompletion.cpp
index c7ee57f6c28..baa2bf95532 100644
--- a/src/plugins/clangcodemodel/clangcompletion.cpp
+++ b/src/plugins/clangcodemodel/clangcompletion.cpp
@@ -190,7 +190,7 @@ namespace Internal {
// ClangCompletionAssistProvider
// -----------------------------
ClangCompletionAssistProvider::ClangCompletionAssistProvider()
- : m_clangCompletionWrapper(new ClangCodeModel::ClangCompleter)
+ : m_clangCompletionWrapper(new ClangCompleter)
{
}
@@ -215,15 +215,15 @@ AssistInterface *ClangCompletionAssistProvider::createAssistInterface(
foreach (ProjectPart::Ptr part, parts) {
if (part.isNull())
continue;
- options = ClangCodeModel::Utils::createClangOptions(part, filePath);
+ options = Utils::createClangOptions(part, filePath);
pchInfo = PchManager::instance()->pchInfo(part);
if (!pchInfo.isNull())
- options.append(ClangCodeModel::Utils::createPCHInclusionOptions(pchInfo->fileName()));
+ options.append(Utils::createPCHInclusionOptions(pchInfo->fileName()));
headerPaths = part->headerPaths;
break;
}
- return new ClangCodeModel::ClangCompletionAssistInterface(
+ return new ClangCompletionAssistInterface(
m_clangCompletionWrapper,
document, position, filePath, reason,
options, headerPaths, pchInfo);
@@ -287,7 +287,7 @@ public:
virtual int activeArgument(const QString &prefix) const;
private:
- QList<ClangCodeModel::CodeCompletionResult> m_functionSymbols;
+ QList<CodeCompletionResult> m_functionSymbols;
mutable int m_currentArg;
};
@@ -323,7 +323,7 @@ int ClangFunctionHintModel::activeArgument(const QString &prefix) const
SimpleLexer tokenize;
Tokens tokens = tokenize(prefix);
for (int i = 0; i < tokens.count(); ++i) {
- const CPlusPlus::Token &tk = tokens.at(i);
+ const Token &tk = tokens.at(i);
if (tk.is(T_LPAREN))
++parcount;
else if (tk.is(T_RPAREN))
@@ -544,7 +544,7 @@ ClangCompletionAssistInterface::ClangCompletionAssistInterface(ClangCompleter::P
const QString &fileName,
AssistReason reason,
const QStringList &options,
- const QList<CppTools::ProjectPart::HeaderPath> &headerPaths,
+ const QList<ProjectPart::HeaderPath> &headerPaths,
const PchInfo::Ptr &pchInfo)
: AssistInterface(document, position, fileName, reason)
, m_clangWrapper(clangWrapper)
@@ -560,37 +560,7 @@ ClangCompletionAssistInterface::ClangCompletionAssistInterface(ClangCompleter::P
}
ClangCompletionAssistProcessor::ClangCompletionAssistProcessor()
- : m_preprocessorCompletions(QStringList()
- << QLatin1String("define")
- << QLatin1String("error")
- << QLatin1String("include")
- << QLatin1String("line")
- << QLatin1String("pragma")
- << QLatin1String("pragma once")
- << QLatin1String("pragma omp atomic")
- << QLatin1String("pragma omp parallel")
- << QLatin1String("pragma omp for")
- << QLatin1String("pragma omp ordered")
- << QLatin1String("pragma omp parallel for")
- << QLatin1String("pragma omp section")
- << QLatin1String("pragma omp sections")
- << QLatin1String("pragma omp parallel sections")
- << QLatin1String("pragma omp single")
- << QLatin1String("pragma omp master")
- << QLatin1String("pragma omp critical")
- << QLatin1String("pragma omp barrier")
- << QLatin1String("pragma omp flush")
- << QLatin1String("pragma omp threadprivate")
- << QLatin1String("undef")
- << QLatin1String("if")
- << QLatin1String("ifdef")
- << QLatin1String("ifndef")
- << QLatin1String("elif")
- << QLatin1String("else")
- << QLatin1String("endif"))
- , m_model(new ClangAssistProposalModel)
- , m_hintProposal(0)
-
+ : m_model(new ClangAssistProposalModel)
{
}
@@ -749,7 +719,7 @@ int ClangCompletionAssistProcessor::startOfOperator(int pos,
tokenize.setSkipComments(false);
const Tokens &tokens = tokenize(tc.block().text(), BackwardsScanner::previousBlockState(tc.block()));
const int tokenIdx = SimpleLexer::tokenBefore(tokens, qMax(0, tc.positionInBlock() - 1)); // get the token at the left of the cursor
- const CPlusPlus::Token tk = (tokenIdx == -1) ? CPlusPlus::Token() : tokens.at(tokenIdx);
+ const Token tk = (tokenIdx == -1) ? Token() : tokens.at(tokenIdx);
if (*kind == T_DOXY_COMMENT && !(tk.is(T_DOXY_COMMENT) || tk.is(T_CPP_DOXY_COMMENT))) {
*kind = T_EOF_SYMBOL;
@@ -770,7 +740,7 @@ int ClangCompletionAssistProcessor::startOfOperator(int pos,
}
else if (*kind == T_LPAREN) {
if (tokenIdx > 0) {
- const CPlusPlus::Token &previousToken = tokens.at(tokenIdx - 1); // look at the token at the left of T_LPAREN
+ const Token &previousToken = tokens.at(tokenIdx - 1); // look at the token at the left of T_LPAREN
switch (previousToken.kind()) {
case T_IDENTIFIER:
case T_GREATER:
@@ -791,7 +761,7 @@ int ClangCompletionAssistProcessor::startOfOperator(int pos,
if (tokens.size() >= 3) {
if (tokens.at(0).is(T_POUND) && tokens.at(1).is(T_IDENTIFIER) && (tokens.at(2).is(T_STRING_LITERAL) ||
tokens.at(2).is(T_ANGLE_STRING_LITERAL))) {
- const CPlusPlus::Token &directiveToken = tokens.at(1);
+ const Token &directiveToken = tokens.at(1);
QString directive = tc.block().text().mid(directiveToken.bytesBegin(),
directiveToken.bytes());
if (directive == QLatin1String("include") ||
@@ -860,7 +830,7 @@ bool ClangCompletionAssistProcessor::accepts() const
tokenize.setSkipComments(false);
const Tokens &tokens = tokenize(tc.block().text(), BackwardsScanner::previousBlockState(tc.block()));
const int tokenIdx = SimpleLexer::tokenBefore(tokens, qMax(0, tc.positionInBlock() - 1));
- const CPlusPlus::Token tk = (tokenIdx == -1) ? CPlusPlus::Token() : tokens.at(tokenIdx);
+ const Token tk = (tokenIdx == -1) ? Token() : tokens.at(tokenIdx);
if (!tk.isComment() && !tk.isLiteral()) {
return true;
@@ -869,7 +839,7 @@ bool ClangCompletionAssistProcessor::accepts() const
&& tokens.at(0).kind() == T_POUND
&& tokens.at(1).kind() == T_IDENTIFIER) {
const QString &line = tc.block().text();
- const CPlusPlus::Token &idToken = tokens.at(1);
+ const Token &idToken = tokens.at(1);
const QStringRef &identifier =
line.midRef(idToken.bytesBegin(),
idToken.bytesEnd() - idToken.bytesBegin());
diff --git a/src/plugins/clangcodemodel/clangcompletion.h b/src/plugins/clangcodemodel/clangcompletion.h
index 4ade75d867c..65274ff19ae 100644
--- a/src/plugins/clangcodemodel/clangcompletion.h
+++ b/src/plugins/clangcodemodel/clangcompletion.h
@@ -35,13 +35,13 @@
#include <cplusplus/Icons.h>
+#include <cpptools/cppcompletionassistprocessor.h>
#include <cpptools/cppcompletionassistprovider.h>
#include <cpptools/cppmodelmanager.h>
#include <texteditor/codeassist/assistproposalitem.h>
#include <texteditor/codeassist/completionassistprovider.h>
#include <texteditor/codeassist/assistinterface.h>
-#include <texteditor/codeassist/iassistprocessor.h>
#include <QStringList>
#include <QTextCursor>
@@ -102,7 +102,7 @@ private:
Internal::PchInfo::Ptr m_savedPchPointer;
};
-class CLANG_EXPORT ClangCompletionAssistProcessor : public TextEditor::IAssistProcessor
+class CLANG_EXPORT ClangCompletionAssistProcessor : public CppTools::CppCompletionAssistProcessor
{
Q_DECLARE_TR_FUNCTIONS(ClangCodeModel::Internal::ClangCompletionAssistProcessor)
@@ -132,13 +132,8 @@ private:
const QVariant &data = QVariant());
private:
- int m_startPosition;
QScopedPointer<const ClangCompletionAssistInterface> m_interface;
- QList<TextEditor::AssistProposalItem *> m_completions;
- CPlusPlus::Icons m_icons;
- QStringList m_preprocessorCompletions;
QScopedPointer<Internal::ClangAssistProposalModel> m_model;
- TextEditor::IAssistProposal *m_hintProposal;
};
} // namespace Clang
diff --git a/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp b/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp
index f02a1ac985d..ebf56b81a74 100644
--- a/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp
+++ b/src/plugins/clangcodemodel/clangeditordocumentprocessor.cpp
@@ -94,7 +94,7 @@ namespace ClangCodeModel {
ClangEditorDocumentProcessor::ClangEditorDocumentProcessor(TextEditor::TextDocument *document)
: BaseEditorDocumentProcessor(document)
- , m_parser(document->filePath())
+ , m_parser(document->filePath().toString())
, m_parserRevision(0)
, m_semanticHighlighter(document)
, m_builtinProcessor(document, /*enableSemanticHighlighter=*/ false)
@@ -112,7 +112,7 @@ ClangEditorDocumentProcessor::ClangEditorDocumentProcessor(TextEditor::TextDocum
const int lastLine = baseTextDocument()->document()->blockCount();
CreateMarkers *createMarkers = CreateMarkers::create(m_parser.semanticMarker(),
- baseTextDocument()->filePath(),
+ baseTextDocument()->filePath().toString(),
firstLine, lastLine);
return createMarkers->start();
});
diff --git a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp
index 28acc67d0bd..84c0ec59953 100644
--- a/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp
+++ b/src/plugins/clangcodemodel/clangmodelmanagersupport.cpp
@@ -66,5 +66,5 @@ CppTools::CppCompletionAssistProvider *ModelManagerSupport::completionAssistProv
CppTools::BaseEditorDocumentProcessor *ModelManagerSupport::editorDocumentProcessor(
TextEditor::TextDocument *baseTextDocument)
{
- return new ClangCodeModel::ClangEditorDocumentProcessor(baseTextDocument);
+ return new ClangEditorDocumentProcessor(baseTextDocument);
}
diff --git a/src/plugins/clangcodemodel/clangutils.cpp b/src/plugins/clangcodemodel/clangutils.cpp
index 466c037af24..8f2f6ddd4d8 100644
--- a/src/plugins/clangcodemodel/clangutils.cpp
+++ b/src/plugins/clangcodemodel/clangutils.cpp
@@ -74,17 +74,17 @@ UnsavedFiles createUnsavedFiles(WorkingCopy workingCopy)
// TODO: change the modelmanager to hold one working copy, and amend it every time we ask for one.
// TODO: Reason: the UnsavedFile needs a QByteArray.
- QSet<QString> modifiedFiles;
- foreach (IDocument *doc, Core::DocumentManager::modifiedDocuments())
+ QSet< ::Utils::FileName> modifiedFiles;
+ foreach (IDocument *doc, DocumentManager::modifiedDocuments())
modifiedFiles.insert(doc->filePath());
UnsavedFiles result;
- QHashIterator<QString, QPair<QByteArray, unsigned> > wcIter = workingCopy.iterator();
+ QHashIterator< ::Utils::FileName, QPair<QByteArray, unsigned> > wcIter = workingCopy.iterator();
while (wcIter.hasNext()) {
wcIter.next();
- const QString &fileName = wcIter.key();
- if (modifiedFiles.contains(fileName) && QFile(fileName).exists())
- result.insert(fileName, wcIter.value().first);
+ const ::Utils::FileName &fileName = wcIter.key();
+ if (modifiedFiles.contains(fileName) && QFile(fileName.toString()).exists())
+ result.insert(fileName.toString(), wcIter.value().first);
}
return result;
@@ -112,7 +112,7 @@ QStringList createClangOptions(const ProjectPart::Ptr &pPart, const QString &fil
static QString getResourceDir()
{
- QDir dir(Core::ICore::instance()->resourcePath() + QLatin1String("/cplusplus/clang/") +
+ QDir dir(ICore::instance()->resourcePath() + QLatin1String("/cplusplus/clang/") +
QLatin1String(CLANG_VERSION) + QLatin1String("/include"));
if (!dir.exists() || !QFileInfo(dir, QLatin1String("stdint.h")).exists())
dir = QDir(QLatin1String(CLANG_RESOURCE_DIR));
@@ -144,18 +144,17 @@ QStringList createClangOptions(const ProjectPart::Ptr &pPart, ProjectFile::Kind
result << QLatin1String("-v");
const bool objcExt = pPart->languageExtensions & ProjectPart::ObjectiveCExtensions;
- result << CppTools::CompilerOptionsBuilder::createLanguageOption(fileKind, objcExt);
- result << CppTools::CompilerOptionsBuilder::createOptionsForLanguage(
- pPart->languageVersion,
- pPart->languageExtensions,
- maybeIncludeBorlandExtensions());
- result << CppTools::CompilerOptionsBuilder::createDefineOptions(pPart->toolchainDefines);
- result << CppTools::CompilerOptionsBuilder::createDefineOptions(pPart->projectDefines);
- result << CppTools::CompilerOptionsBuilder::createHeaderPathOptions(pPart->headerPaths,
- isBlacklisted);
+ result << CompilerOptionsBuilder::createLanguageOption(fileKind, objcExt);
+ result << CompilerOptionsBuilder::createOptionsForLanguage(
+ pPart->languageVersion,
+ pPart->languageExtensions,
+ maybeIncludeBorlandExtensions());
+ result << CompilerOptionsBuilder::createDefineOptions(pPart->toolchainDefines);
+ result << CompilerOptionsBuilder::createDefineOptions(pPart->projectDefines);
+ result << CompilerOptionsBuilder::createHeaderPathOptions(pPart->headerPaths, isBlacklisted);
// Inject header file
- static const QString injectedHeader = Core::ICore::instance()->resourcePath()
+ static const QString injectedHeader = ICore::instance()->resourcePath()
+ QLatin1String("/cplusplus/qt%1-qobjectdefs-injected.h");
// if (qtVersion == ProjectPart::Qt4)
// opts << QLatin1String("-include") << injectedHeader.arg(QLatin1Char('4'));
diff --git a/src/plugins/clangcodemodel/indexer.cpp b/src/plugins/clangcodemodel/indexer.cpp
index 521a8dca77c..f44c51d4c1e 100644
--- a/src/plugins/clangcodemodel/indexer.cpp
+++ b/src/plugins/clangcodemodel/indexer.cpp
@@ -244,7 +244,7 @@ protected:
indexingResults.reserve(m_allFiles.size());
foreach (const QString &fn, m_allFiles.keys()) {
- QVector<ClangCodeModel::Symbol> symbols; unfoldSymbols(symbols, fn);
+ QVector<Symbol> symbols; unfoldSymbols(symbols, fn);
QSet<QString> processedFiles = QSet<QString>::fromList(m_allFiles.keys());
Unit::Ptr unit = Unit::create(fn);
IndexingResult indexingResult(symbols, processedFiles, unit, projectPart);
@@ -487,18 +487,18 @@ protected:
}
}
- void unfoldSymbols(QVector<ClangCodeModel::Symbol> &result, const QString &fileName) {
+ void unfoldSymbols(QVector<Symbol> &result, const QString &fileName) {
const QVector<Symbol *> symbolsForFile = file(fileName)->symbols();
foreach (const Symbol *s, symbolsForFile) {
unfoldSymbols(s, result);
}
}
- void unfoldSymbols(const Symbol *s, QVector<ClangCodeModel::Symbol> &result) {
+ void unfoldSymbols(const Symbol *s, QVector<Symbol> &result) {
if (!s->file)
return;
- ClangCodeModel::Symbol sym;
+ Symbol sym;
sym.m_name = s->spellingName;
sym.m_qualification = s->spellingName;
@@ -509,16 +509,16 @@ protected:
sym.m_location = SourceLocation(s->file->name(), s->line, s->column, s->offset);
switch (s->kind) {
- case CXCursor_EnumDecl: sym.m_kind = ClangCodeModel::Symbol::Enum; break;
+ case CXCursor_EnumDecl: sym.m_kind = Symbol::Enum; break;
case CXCursor_StructDecl:
- case CXCursor_ClassDecl: sym.m_kind = ClangCodeModel::Symbol::Class; break;
- case CXCursor_CXXMethod: sym.m_kind = ClangCodeModel::Symbol::Method; break;
+ case CXCursor_ClassDecl: sym.m_kind = Symbol::Class; break;
+ case CXCursor_CXXMethod: sym.m_kind = Symbol::Method; break;
case CXCursor_FunctionTemplate:
- case CXCursor_FunctionDecl: sym.m_kind = ClangCodeModel::Symbol::Function; break;
- case CXCursor_DeclStmt: sym.m_kind = ClangCodeModel::Symbol::Declaration; break;
- case CXCursor_Constructor: sym.m_kind = ClangCodeModel::Symbol::Constructor; break;
- case CXCursor_Destructor: sym.m_kind = ClangCodeModel::Symbol::Destructor; break;
- default: sym.m_kind = ClangCodeModel::Symbol::Unknown; break;
+ case CXCursor_FunctionDecl: sym.m_kind = Symbol::Function; break;
+ case CXCursor_DeclStmt: sym.m_kind = Symbol::Declaration; break;
+ case CXCursor_Constructor: sym.m_kind = Symbol::Constructor; break;
+ case CXCursor_Destructor: sym.m_kind = Symbol::Destructor; break;
+ default: sym.m_kind = Symbol::Unknown; break;
}
result.append(sym);
@@ -588,7 +588,7 @@ restart:
goto restart;
}
- QStringList opts = ClangCodeModel::Utils::createClangOptions(pPart, fd.m_fileName);
+ QStringList opts = Utils::createClangOptions(pPart, fd.m_fileName);
if (!pchInfo.isNull())
opts.append(Utils::createPCHInclusionOptions(pchInfo->fileName()));
@@ -705,7 +705,7 @@ void IndexerPrivate::runCore(const QHash<QString, FileData> & /*headers*/,
QList<Core::IDocument *> docs = Core::DocumentModel::openedDocuments();
QSet<QString> openDocs;
foreach (Core::IDocument *doc, docs)
- openDocs.insert(doc->filePath());
+ openDocs.insert(doc->filePath().toString());
for (FileContIt tit = impls.begin(), eit = impls.end(); tit != eit; ++tit) {
if (!tit->m_upToDate && openDocs.contains(tit.key())) {
diff --git a/src/plugins/classview/classviewmanager.cpp b/src/plugins/classview/classviewmanager.cpp
index 223811248b4..0a2e6150824 100644
--- a/src/plugins/classview/classviewmanager.cpp
+++ b/src/plugins/classview/classviewmanager.cpp
@@ -369,7 +369,7 @@ void Manager::onProjectListChanged()
\sa CppTools::Constants::TASK_INDEX
*/
-void Manager::onTaskStarted(Core::Id type)
+void Manager::onTaskStarted(Id type)
{
if (type != CppTools::Constants::TASK_INDEX)
return;
@@ -385,7 +385,7 @@ void Manager::onTaskStarted(Core::Id type)
\sa CppTools::Constants::TASK_INDEX
*/
-void Manager::onAllTasksFinished(Core::Id type)
+void Manager::onAllTasksFinished(Id type)
{
if (type != CppTools::Constants::TASK_INDEX)
return;
@@ -455,7 +455,7 @@ void Manager::gotoLocations(const QList<QVariant> &list)
auto textEditor = qobject_cast<TextEditor::BaseTextEditor *>(EditorManager::currentEditor());
if (textEditor) {
// check if current cursor position is a known location of the symbol
- const QString fileName = textEditor->document()->filePath();
+ const QString fileName = textEditor->document()->filePath().toString();
int line;
int column;
textEditor->convertPosition(textEditor->position(), &line, &column);
diff --git a/src/plugins/classview/classviewparser.cpp b/src/plugins/classview/classviewparser.cpp
index 079f6ce28e7..8e99eb14f3c 100644
--- a/src/plugins/classview/classviewparser.cpp
+++ b/src/plugins/classview/classviewparser.cpp
@@ -172,7 +172,7 @@ Parser::Parser(QObject *parent)
// connect signal/slots
// internal data reset
- connect(this, SIGNAL(resetDataDone()), SLOT(onResetDataDone()), Qt::QueuedConnection);
+ connect(this, &Parser::resetDataDone, this, &Parser::onResetDataDone, Qt::QueuedConnection);
// timer for emitting changes
connect(d->timer, SIGNAL(timeout()), SLOT(requestCurrentState()), Qt::QueuedConnection);
@@ -384,8 +384,8 @@ void Parser::addSymbol(const ParserTreeItem::Ptr &item, const CPlusPlus::Symbol
// prevent showing a content of the functions
if (!symbol->isFunction()) {
if (const CPlusPlus::Scope *scope = symbol->asScope()) {
- CPlusPlus::Scope::iterator cur = scope->firstMember();
- CPlusPlus::Scope::iterator last = scope->lastMember();
+ CPlusPlus::Scope::iterator cur = scope->memberBegin();
+ CPlusPlus::Scope::iterator last = scope->memberEnd();
while (cur != last) {
const CPlusPlus::Symbol *curSymbol = *cur;
++cur;
@@ -641,7 +641,7 @@ void Parser::resetData(const CPlusPlus::Snapshot &snapshot)
CPlusPlus::Snapshot::const_iterator cur = snapshot.begin();
CPlusPlus::Snapshot::const_iterator end = snapshot.end();
for (; cur != end; ++cur)
- d->documentList[cur.key()] = cur.value();
+ d->documentList[cur.key().toString()] = cur.value();
d->docLocker.unlock();
@@ -718,25 +718,24 @@ void Parser::emitCurrentTree()
Generates a project node file list for the root node \a node.
*/
-QStringList Parser::projectNodeFileList(const ProjectExplorer::FolderNode *node) const
+QStringList Parser::projectNodeFileList(const FolderNode *node) const
{
QStringList list;
if (!node)
return list;
- QList<ProjectExplorer::FileNode *> fileNodes = node->fileNodes();
- QList<ProjectExplorer::FolderNode *> subFolderNodes = node->subFolderNodes();
+ QList<FileNode *> fileNodes = node->fileNodes();
+ QList<FolderNode *> subFolderNodes = node->subFolderNodes();
- foreach (const ProjectExplorer::FileNode *file, fileNodes) {
+ foreach (const FileNode *file, fileNodes) {
if (file->isGenerated())
continue;
list << file->path();
}
- foreach (const ProjectExplorer::FolderNode *folder, subFolderNodes) {
- if (folder->nodeType() != ProjectExplorer::FolderNodeType
- && folder->nodeType() != ProjectExplorer::VirtualFolderNodeType)
+ foreach (const FolderNode *folder, subFolderNodes) {
+ if (folder->nodeType() != FolderNodeType && folder->nodeType() != VirtualFolderNodeType)
continue;
list << projectNodeFileList(folder);
}
@@ -751,8 +750,7 @@ QStringList Parser::projectNodeFileList(const ProjectExplorer::FolderNode *node)
Returns a list of projects which were added to the item.
*/
-QStringList Parser::addProjectNode(const ParserTreeItem::Ptr &item,
- const ProjectExplorer::ProjectNode *node)
+QStringList Parser::addProjectNode(const ParserTreeItem::Ptr &item, const ProjectNode *node)
{
QStringList projectList;
if (!node)
@@ -777,9 +775,9 @@ QStringList Parser::addProjectNode(const ParserTreeItem::Ptr &item,
}
// subnodes
- QList<ProjectExplorer::ProjectNode *> projectNodes = node->subProjectNodes();
+ QList<ProjectNode *> projectNodes = node->subProjectNodes();
- foreach (const ProjectExplorer::ProjectNode *project, projectNodes) {
+ foreach (const ProjectNode *project, projectNodes) {
ParserTreeItem::Ptr itemPrj(new ParserTreeItem());
SymbolInformation information(project->displayName(), project->path());
@@ -813,11 +811,10 @@ QStringList Parser::getAllFiles(const ProjectNode *node)
d->cachedPrjFileLists[nodePath] = fileList;
}
// subnodes
- QList<ProjectExplorer::ProjectNode *> projectNodes = node->subProjectNodes();
+ QList<ProjectNode *> projectNodes = node->subProjectNodes();
- foreach (const ProjectExplorer::ProjectNode *project, projectNodes) {
+ foreach (const ProjectNode *project, projectNodes)
fileList += getAllFiles(project);
- }
return fileList;
}
diff --git a/src/plugins/clearcase/activityselector.cpp b/src/plugins/clearcase/activityselector.cpp
index b906ba21340..78f4f189043 100644
--- a/src/plugins/clearcase/activityselector.cpp
+++ b/src/plugins/clearcase/activityselector.cpp
@@ -50,10 +50,10 @@ ActivitySelector::ActivitySelector(QWidget *parent) :
{
QTC_ASSERT(m_plugin->isUcm(), return);
- QHBoxLayout *hboxLayout = new QHBoxLayout(this);
+ auto hboxLayout = new QHBoxLayout(this);
hboxLayout->setContentsMargins(0, 0, 0, 0);
- QLabel *lblActivity = new QLabel(tr("Select &activity:"));
+ auto lblActivity = new QLabel(tr("Select &activity:"));
lblActivity->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
hboxLayout->addWidget(lblActivity);
@@ -64,16 +64,17 @@ ActivitySelector::ActivitySelector(QWidget *parent) :
QString addText = tr("Add");
if (!m_plugin->settings().autoAssignActivityName)
addText.append(QLatin1String("..."));
- QToolButton *btnAdd = new QToolButton;
+ auto btnAdd = new QToolButton;
btnAdd->setText(addText);
hboxLayout->addWidget(btnAdd);
lblActivity->setBuddy(m_cmbActivity);
- connect(btnAdd, SIGNAL(clicked()), this, SLOT(newActivity()));
+ connect(btnAdd, &QToolButton::clicked, this, &ActivitySelector::newActivity);
refresh();
- connect(m_cmbActivity, SIGNAL(currentIndexChanged(int)), this, SLOT(userChanged()));
+ connect(m_cmbActivity, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &ActivitySelector::userChanged);
}
void ActivitySelector::userChanged()
@@ -109,9 +110,11 @@ void ActivitySelector::setActivity(const QString &act)
{
int index = m_cmbActivity->findData(act);
if (index != -1) {
- disconnect(m_cmbActivity, SIGNAL(currentIndexChanged(int)), this, SLOT(userChanged()));
+ disconnect(m_cmbActivity, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &ActivitySelector::userChanged);
m_cmbActivity->setCurrentIndex(index);
- connect(m_cmbActivity, SIGNAL(currentIndexChanged(int)), this, SLOT(userChanged()));
+ connect(m_cmbActivity, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &ActivitySelector::userChanged);
}
}
diff --git a/src/plugins/clearcase/checkoutdialog.cpp b/src/plugins/clearcase/checkoutdialog.cpp
index 02366eda52c..b2c6ef56579 100644
--- a/src/plugins/clearcase/checkoutdialog.cpp
+++ b/src/plugins/clearcase/checkoutdialog.cpp
@@ -52,7 +52,7 @@ CheckOutDialog::CheckOutDialog(const QString &fileName, bool isUcm, QWidget *par
ui->verticalLayout->insertWidget(0, m_actSelector);
- QFrame *line = new QFrame(this);
+ auto line = new QFrame(this);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
diff --git a/src/plugins/clearcase/clearcasecontrol.cpp b/src/plugins/clearcase/clearcasecontrol.cpp
index a2e1dd5492d..686f782a92d 100644
--- a/src/plugins/clearcase/clearcasecontrol.cpp
+++ b/src/plugins/clearcase/clearcasecontrol.cpp
@@ -77,9 +77,7 @@ bool ClearCaseControl::supportsOperation(Operation operation) const
case DeleteOperation:
case MoveOperation:
case AnnotateOperation:
- case GetRepositoryRootOperation:
break;
- case CheckoutOperation:
case CreateRepositoryOperation:
case SnapshotOperations:
rc = false;
@@ -140,11 +138,6 @@ bool ClearCaseControl::vcsMove(const QString &from, const QString &to)
return m_plugin->vcsMove(ifrom.absolutePath(), ifrom.fileName(), ito.fileName());
}
-QString ClearCaseControl::vcsGetRepositoryURL(const QString &directory)
-{
- return m_plugin->vcsGetRepositoryURL(directory);
-}
-
bool ClearCaseControl::managesDirectory(const QString &directory, QString *topLevel) const
{
return m_plugin->managesDirectory(directory, topLevel);
@@ -194,11 +187,6 @@ void ClearCaseControl::emitConfigurationChanged()
emit configurationChanged();
}
-bool ClearCaseControl::vcsCheckout(const QString & /*directory*/, const QByteArray & /*url*/)
-{
- return false;
-}
-
bool ClearCaseControl::vcsCreateRepository(const QString &)
{
return false;
diff --git a/src/plugins/clearcase/clearcasecontrol.h b/src/plugins/clearcase/clearcasecontrol.h
index 57441ad9df4..43864917efc 100644
--- a/src/plugins/clearcase/clearcasecontrol.h
+++ b/src/plugins/clearcase/clearcasecontrol.h
@@ -61,8 +61,6 @@ public:
bool vcsDelete(const QString &filename);
bool vcsMove(const QString &from, const QString &to);
bool vcsCreateRepository(const QString &directory);
- bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
bool vcsAnnotate(const QString &file, int line);
diff --git a/src/plugins/clearcase/clearcaseplugin.cpp b/src/plugins/clearcase/clearcaseplugin.cpp
index 8875886ffa9..7217c6ae59e 100644
--- a/src/plugins/clearcase/clearcaseplugin.cpp
+++ b/src/plugins/clearcase/clearcaseplugin.cpp
@@ -55,7 +55,7 @@
#include <coreplugin/mimedatabase.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/locator/commandlocator.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <projectexplorer/iprojectmanager.h>
#include <utils/algorithm.h>
@@ -131,15 +131,15 @@ static const char CMD_ID_STATUS[] = "ClearCase.Status";
static const VcsBaseEditorParameters editorParameters[] = {
{
- VcsBase::LogOutput,
+ LogOutput,
"ClearCase File Log Editor", // id
QT_TRANSLATE_NOOP("VCS", "ClearCase File Log Editor"), // display_name
"text/vnd.qtcreator.clearcase.log"},
-{ VcsBase::AnnotateOutput,
+{ AnnotateOutput,
"ClearCase Annotation Editor", // id
QT_TRANSLATE_NOOP("VCS", "ClearCase Annotation Editor"), // display_name
"text/vnd.qtcreator.clearcase.annotation"},
-{ VcsBase::DiffOutput,
+{ DiffOutput,
"ClearCase Diff Editor", // id
QT_TRANSLATE_NOOP("VCS", "ClearCase Diff Editor"), // display_name
"text/x-patch"}
@@ -454,8 +454,8 @@ bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *er
m_settings.fromSettings(ICore::settings());
// update view name when changing active project
- connect(ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
- this, SLOT(projectChanged(ProjectExplorer::Project*)));
+ connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
+ this, &ClearCasePlugin::projectChanged);
addAutoReleasedObject(new SettingsPage);
@@ -633,7 +633,7 @@ bool ClearCasePlugin::submitEditorAboutToClose()
// Submit editor closing. Make it write out the check in message
// and retrieve files
- const QFileInfo editorFile(editorDocument->filePath());
+ const QFileInfo editorFile = editorDocument->filePath().toFileInfo();
const QFileInfo changeFile(m_checkInMessageFileName);
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
return true; // Oops?!
@@ -1198,11 +1198,11 @@ void ClearCasePlugin::startCheckInActivity()
QTC_ASSERT(state.hasProject(), return);
QDialog dlg;
- QVBoxLayout *layout = new QVBoxLayout(&dlg);
- ActivitySelector *actSelector = new ActivitySelector(&dlg);
- QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dlg);
- connect(buttonBox, SIGNAL(accepted()), &dlg, SLOT(accept()));
- connect(buttonBox, SIGNAL(rejected()), &dlg, SLOT(reject()));
+ auto layout = new QVBoxLayout(&dlg);
+ auto actSelector = new ActivitySelector(&dlg);
+ auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dlg);
+ connect(buttonBox, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
+ connect(buttonBox, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
layout->addWidget(actSelector);
layout->addWidget(buttonBox);
dlg.setWindowTitle(tr("Check In Activity"));
@@ -1327,8 +1327,9 @@ void ClearCasePlugin::viewStatus()
if (m_viewData.name.isEmpty())
m_viewData = ccGetView(m_topLevel);
QTC_ASSERT(!m_viewData.name.isEmpty() && !m_settings.disableIndexer, return);
- VcsOutputWindow::appendCommand(QLatin1String("Indexed files status (C=Checked Out, "
- "H=Hijacked, ?=Missing)"));
+ VcsOutputWindow::append(QLatin1String("Indexed files status (C=Checked Out, "
+ "H=Hijacked, ?=Missing)"),
+ VcsOutputWindow::Command, true);
bool anymod = false;
for (StatusMap::ConstIterator it = m_statusMap->constBegin();
it != m_statusMap->constEnd();
@@ -1482,11 +1483,11 @@ QString ClearCasePlugin::runCleartoolSync(const QString &workingDir,
}
ClearCaseResponse
- ClearCasePlugin::runCleartool(const QString &workingDir,
- const QStringList &arguments,
- int timeOut,
- unsigned flags,
- QTextCodec *outputCodec) const
+ClearCasePlugin::runCleartool(const QString &workingDir,
+ const QStringList &arguments,
+ int timeOut,
+ unsigned flags,
+ QTextCodec *outputCodec) const
{
const QString executable = m_settings.ccBinaryPath;
ClearCaseResponse response;
@@ -1734,27 +1735,23 @@ bool ClearCasePlugin::ccFileOp(const QString &workingDir, const QString &title,
{
const QString file = QDir::toNativeSeparators(fileName);
bool noCheckout = false;
- QVBoxLayout *verticalLayout;
ActivitySelector *actSelector = 0;
- QLabel *commentLabel;
- QTextEdit *commentEdit;
- QDialogButtonBox *buttonBox;
QDialog fileOpDlg;
fileOpDlg.setWindowTitle(title);
- verticalLayout = new QVBoxLayout(&fileOpDlg);
+ auto verticalLayout = new QVBoxLayout(&fileOpDlg);
if (m_viewData.isUcm) {
actSelector = new ActivitySelector;
verticalLayout->addWidget(actSelector);
}
- commentLabel = new QLabel(tr("Enter &comment:"));
+ auto commentLabel = new QLabel(tr("Enter &comment:"));
verticalLayout->addWidget(commentLabel);
- commentEdit = new QTextEdit;
+ auto commentEdit = new QTextEdit;
verticalLayout->addWidget(commentEdit);
- buttonBox = new QDialogButtonBox;
+ auto buttonBox = new QDialogButtonBox;
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
verticalLayout->addWidget(buttonBox);
@@ -1851,11 +1848,6 @@ bool ClearCasePlugin::vcsCheckout(const QString & /*directory*/, const QByteArra
return false;
}
-QString ClearCasePlugin::vcsGetRepositoryURL(const QString & /*directory*/)
-{
- return currentState().topLevel();
-}
-
///
/// Check if the directory is managed under ClearCase control.
///
@@ -2064,7 +2056,7 @@ void ClearCasePlugin::updateIndex()
{
QTC_ASSERT(currentState().hasTopLevel(), return);
ProgressManager::cancelTasks(ClearCase::Constants::TASK_INDEX);
- Project *project = ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
if (!project)
return;
m_checkInAllAction->setEnabled(false);
diff --git a/src/plugins/clearcase/clearcaseplugin.h b/src/plugins/clearcase/clearcaseplugin.h
index f3b94e5a691..16ba8ce87dd 100644
--- a/src/plugins/clearcase/clearcaseplugin.h
+++ b/src/plugins/clearcase/clearcaseplugin.h
@@ -144,7 +144,6 @@ public:
bool vcsSetActivity(const QString &workingDir, const QString &title, const QString &activity);
bool managesDirectory(const QString &directory, QString *topLevel = 0) const;
bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
static ClearCasePlugin *instance();
diff --git a/src/plugins/clearcase/clearcasesubmiteditor.cpp b/src/plugins/clearcase/clearcasesubmiteditor.cpp
index a1385049a8e..2b194ced05e 100644
--- a/src/plugins/clearcase/clearcasesubmiteditor.cpp
+++ b/src/plugins/clearcase/clearcasesubmiteditor.cpp
@@ -57,7 +57,7 @@ void ClearCaseSubmitEditor::setIsUcm(bool isUcm)
void ClearCaseSubmitEditor::setStatusList(const QStringList &statusOutput)
{
typedef QStringList::const_iterator ConstIterator;
- VcsBase::SubmitFileModel *model = new VcsBase::SubmitFileModel(this);
+ auto model = new VcsBase::SubmitFileModel(this);
const ConstIterator cend = statusOutput.constEnd();
for (ConstIterator it = statusOutput.constBegin(); it != cend; ++it)
diff --git a/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp b/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp
index 6b24f7b632a..45c5b70f5dc 100644
--- a/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp
+++ b/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp
@@ -44,7 +44,7 @@ ClearCaseSubmitEditorWidget::ClearCaseSubmitEditorWidget()
: m_actSelector(0)
{
setDescriptionMandatory(false);
- QWidget *checkInWidget = new QWidget(this);
+ auto checkInWidget = new QWidget(this);
m_verticalLayout = new QVBoxLayout(checkInWidget);
@@ -98,7 +98,7 @@ void ClearCaseSubmitEditorWidget::addActivitySelector(bool isUcm)
m_actSelector = new ActivitySelector;
m_verticalLayout->insertWidget(0, m_actSelector);
- QFrame* line = new QFrame;
+ auto line = new QFrame;
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
m_verticalLayout->insertWidget(1, line);
diff --git a/src/plugins/clearcase/settingspage.cpp b/src/plugins/clearcase/settingspage.cpp
index 18721459c4b..88e06e34806 100644
--- a/src/plugins/clearcase/settingspage.cpp
+++ b/src/plugins/clearcase/settingspage.cpp
@@ -82,7 +82,7 @@ void SettingsPageWidget::setSettings(const ClearCaseSettings &s)
m_ui.commandPathChooser->setPath(s.ccCommand);
m_ui.timeOutSpinBox->setValue(s.timeOutS);
m_ui.autoCheckOutCheckBox->setChecked(s.autoCheckOut);
- bool extDiffAvailable = !Utils::Environment::systemEnvironment().searchInPath(QLatin1String("diff")).isEmpty();
+ bool extDiffAvailable = !Environment::systemEnvironment().searchInPath(QLatin1String("diff")).isEmpty();
if (extDiffAvailable) {
m_ui.diffWarningLabel->setVisible(false);
} else {
diff --git a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
index 306d61cf327..87a523c6fc1 100644
--- a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
@@ -57,26 +57,25 @@ namespace Internal {
const char USE_NINJA_KEY[] = "CMakeProjectManager.CMakeBuildConfiguration.UseNinja";
-static QString shadowBuildDirectory(const QString &projectFilePath, const Kit *k, const QString &bcName)
+static FileName shadowBuildDirectory(const FileName &projectFilePath, const Kit *k, const QString &bcName)
{
if (projectFilePath.isEmpty())
- return QString();
- QFileInfo info(projectFilePath);
+ return FileName();
- const QString projectName = QFileInfo(info.absolutePath()).fileName();
+ const QString projectName = projectFilePath.fileName();
ProjectMacroExpander expander(projectName, k, bcName);
- QDir projectDir = QDir(Project::projectDirectory(FileName::fromString(projectFilePath)).toString());
+ QDir projectDir = QDir(Project::projectDirectory(projectFilePath).toString());
QString buildPath = expander.expand(Core::DocumentManager::buildDirectory());
- return QDir::cleanPath(projectDir.absoluteFilePath(buildPath));
+ return FileName::fromUserInput(projectDir.absoluteFilePath(buildPath));
}
CMakeBuildConfiguration::CMakeBuildConfiguration(ProjectExplorer::Target *parent) :
BuildConfiguration(parent, Core::Id(Constants::CMAKE_BC_ID)), m_useNinja(false)
{
CMakeProject *project = static_cast<CMakeProject *>(parent->project());
- setBuildDirectory(Utils::FileName::fromString(shadowBuildDirectory(project->projectFilePath().toString(),
- parent->kit(),
- displayName())));
+ setBuildDirectory(shadowBuildDirectory(project->projectFilePath(),
+ parent->kit(),
+ displayName()));
}
CMakeBuildConfiguration::CMakeBuildConfiguration(ProjectExplorer::Target *parent,
@@ -170,10 +169,11 @@ QList<ProjectExplorer::BuildInfo *> CMakeBuildConfigurationFactory::availableSet
const QString &projectPath) const
{
QList<ProjectExplorer::BuildInfo *> result;
- CMakeBuildInfo *info = createBuildInfo(k, ProjectExplorer::Project::projectDirectory(Utils::FileName::fromString(projectPath)).toString());
+ const FileName projectPathName = FileName::fromString(projectPath);
+ CMakeBuildInfo *info = createBuildInfo(k, ProjectExplorer::Project::projectDirectory(projectPathName).toString());
//: The name of the build configuration created by default for a cmake project.
info->displayName = tr("Default");
- info->buildDirectory = FileName::fromString(shadowBuildDirectory(projectPath, k, info->displayName));
+ info->buildDirectory = shadowBuildDirectory(projectPathName, k, info->displayName);
result << info;
return result;
}
@@ -188,10 +188,10 @@ ProjectExplorer::BuildConfiguration *CMakeBuildConfigurationFactory::create(Proj
CMakeBuildInfo copy(*static_cast<const CMakeBuildInfo *>(info));
CMakeProject *project = static_cast<CMakeProject *>(parent->project());
- if (copy.buildDirectory.isEmpty())
- copy.buildDirectory = FileName::fromString(shadowBuildDirectory(project->projectFilePath().toString(),
- parent->kit(),
- copy.displayName));
+ if (copy.buildDirectory.isEmpty()) {
+ copy.buildDirectory = shadowBuildDirectory(project->projectFilePath(), parent->kit(),
+ copy.displayName);
+ }
CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), project->projectManager(), CMakeOpenProjectWizard::ChangeDirectory, &copy);
if (copw.exec() != QDialog::Accepted)
@@ -212,7 +212,7 @@ ProjectExplorer::BuildConfiguration *CMakeBuildConfigurationFactory::create(Proj
cleanMakeStep->setAdditionalArguments(QLatin1String("clean"));
cleanMakeStep->setClean(true);
- bc->setBuildDirectory(Utils::FileName::fromString(copw.buildDirectory()));
+ bc->setBuildDirectory(FileName::fromString(copw.buildDirectory()));
bc->setUseNinja(copw.useNinja());
// Default to all
@@ -269,7 +269,7 @@ CMakeBuildInfo *CMakeBuildConfigurationFactory::createBuildInfo(const ProjectExp
CMakeBuildInfo *info = new CMakeBuildInfo(this);
info->typeName = tr("Build");
info->kitId = k->id();
- info->environment = Utils::Environment::systemEnvironment();
+ info->environment = Environment::systemEnvironment();
k->addToEnvironment(info->environment);
info->useNinja = false;
info->sourceDirectory = sourceDir;
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
index 6ef272b2f3f..a1195b0e269 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
@@ -85,7 +85,7 @@ void CMakeEditor::finalizeInitialization()
info.setCustomButtonInfo(tr("Build now"), [document]() {
foreach (Project *p, SessionManager::projects()) {
if (CMakeProject *cmakeProject = qobject_cast<CMakeProject *>(p)) {
- if (cmakeProject->isProjectFile(document->filePath())) {
+ if (cmakeProject->isProjectFile(document->filePath().toString())) {
ProjectExplorerPlugin::buildProject(cmakeProject);
break;
}
@@ -212,7 +212,7 @@ CMakeEditorWidget::Link CMakeEditorWidget::findLinkAt(const QTextCursor &cursor,
// TODO: Resolve variables
- QDir dir(QFileInfo(textDocument()->filePath()).absolutePath());
+ QDir dir(textDocument()->filePath().toFileInfo().absolutePath());
QString fileName = dir.filePath(buffer);
QFileInfo fi(fileName);
if (fi.exists()) {
@@ -252,14 +252,12 @@ CMakeDocument::CMakeDocument()
QString CMakeDocument::defaultPath() const
{
- QFileInfo fi(filePath());
- return fi.absolutePath();
+ return filePath().toFileInfo().absolutePath();
}
QString CMakeDocument::suggestedFileName() const
{
- QFileInfo fi(filePath());
- return fi.fileName();
+ return filePath().fileName();
}
//
diff --git a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
index 37f06a97b30..a5d909b6832 100644
--- a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
@@ -50,6 +50,7 @@ CMakeLocatorFilter::CMakeLocatorFilter()
setId("Build CMake target");
setDisplayName(tr("Build CMake target"));
setShortcutString(QLatin1String("cm"));
+ setPriority(High);
connect(SessionManager::instance(), SIGNAL(projectAdded(ProjectExplorer::Project*)),
this, SLOT(slotProjectListUpdated()));
diff --git a/src/plugins/cmakeprojectmanager/cmakeproject.cpp b/src/plugins/cmakeprojectmanager/cmakeproject.cpp
index 5bd7ebfe7f5..fac84253e11 100644
--- a/src/plugins/cmakeprojectmanager/cmakeproject.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeproject.cpp
@@ -71,6 +71,7 @@
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
using namespace ProjectExplorer;
+using namespace Utils;
// QtCreator CMake Generator wishlist:
// Which make targets we need to build to get all executables
@@ -171,7 +172,7 @@ void CMakeProject::activeTargetWasChanged(Target *target)
void CMakeProject::changeBuildDirectory(CMakeBuildConfiguration *bc, const QString &newBuildDirectory)
{
- bc->setBuildDirectory(Utils::FileName::fromString(newBuildDirectory));
+ bc->setBuildDirectory(FileName::fromString(newBuildDirectory));
parseCMakeLists();
}
@@ -233,7 +234,7 @@ bool CMakeProject::parseCMakeLists()
CMakeBuildConfiguration *activeBC = static_cast<CMakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
foreach (Core::IDocument *document, Core::DocumentModel::openedDocuments())
- if (isProjectFile(document->filePath()))
+ if (isProjectFile(document->filePath().toString()))
document->infoBar()->removeInfo("CMakeEditor.RunCMake");
// Find cbp file
@@ -314,9 +315,7 @@ bool CMakeProject::parseCMakeLists()
CppTools::CppModelManager *modelmanager =
CppTools::CppModelManager::instance();
if (modelmanager) {
- CppTools::ProjectInfo pinfo = modelmanager->projectInfo(this);
- pinfo.clearProjectParts();
-
+ CppTools::ProjectInfo pinfo = CppTools::ProjectInfo(this);
CppTools::ProjectPartBuilder ppBuilder(pinfo);
foreach (const CMakeBuildTarget &cbt, m_buildTargets) {
@@ -362,7 +361,7 @@ QStringList CMakeProject::buildTargetTitles(bool runnable) const
{
QStringList results;
foreach (const CMakeBuildTarget &ct, m_buildTargets) {
- if (runnable && (ct.executable.isEmpty() || ct.library))
+ if (runnable && (ct.executable.isEmpty() || ct.targetType != ExecutableType))
continue;
results << ct.title;
}
@@ -495,7 +494,7 @@ bool CMakeProject::fromMap(const QVariantMap &map)
bool hasUserFile = activeTarget();
if (!hasUserFile) {
- CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), m_manager, projectDirectory().toString(), Utils::Environment::systemEnvironment());
+ CMakeOpenProjectWizard copw(Core::ICore::mainWindow(), m_manager, projectDirectory().toString(), Environment::systemEnvironment());
if (copw.exec() != QDialog::Accepted)
return false;
Kit *k = copw.kit();
@@ -503,7 +502,7 @@ bool CMakeProject::fromMap(const QVariantMap &map)
CMakeBuildConfiguration *bc(new CMakeBuildConfiguration(t));
bc->setDefaultDisplayName(QLatin1String("all"));
bc->setUseNinja(copw.useNinja());
- bc->setBuildDirectory(Utils::FileName::fromString(copw.buildDirectory()));
+ bc->setBuildDirectory(FileName::fromString(copw.buildDirectory()));
ProjectExplorer::BuildStepList *buildSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
ProjectExplorer::BuildStepList *cleanSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_CLEAN);
@@ -580,17 +579,17 @@ CMakeBuildTarget CMakeProject::buildTargetForTitle(const QString &title)
QString CMakeProject::uiHeaderFile(const QString &uiFile)
{
QFileInfo fi(uiFile);
- Utils::FileName project = projectDirectory();
- Utils::FileName baseDirectory = Utils::FileName::fromString(fi.absolutePath());
+ FileName project = projectDirectory();
+ FileName baseDirectory = FileName::fromString(fi.absolutePath());
while (baseDirectory.isChildOf(project)) {
- Utils::FileName cmakeListsTxt = baseDirectory;
+ FileName cmakeListsTxt = baseDirectory;
cmakeListsTxt.appendPath(QLatin1String("CMakeLists.txt"));
if (cmakeListsTxt.exists())
break;
QDir dir(baseDirectory.toString());
dir.cdUp();
- baseDirectory = Utils::FileName::fromString(dir.absolutePath());
+ baseDirectory = FileName::fromString(dir.absolutePath());
}
QDir srcDirRoot = QDir(project.toString());
@@ -626,7 +625,7 @@ void CMakeProject::updateRunConfigurations(Target *t)
}
foreach (const CMakeBuildTarget &ct, buildTargets()) {
- if (ct.library)
+ if (ct.targetType != ExecutableType)
continue;
if (ct.executable.isEmpty())
continue;
@@ -674,10 +673,14 @@ void CMakeProject::updateApplicationAndDeploymentTargets()
QFile deploymentFile;
QTextStream deploymentStream;
QString deploymentPrefix;
- QDir sourceDir;
- sourceDir.setPath(t->project()->projectDirectory().toString());
+ QDir sourceDir(t->project()->projectDirectory().toString());
+ QDir buildDir(t->activeBuildConfiguration()->buildDirectory().toString());
+
deploymentFile.setFileName(sourceDir.filePath(QLatin1String("QtCreatorDeployment.txt")));
+ // If we don't have a global QtCreatorDeployment.txt check for one created by the active build configuration
+ if (!deploymentFile.exists())
+ deploymentFile.setFileName(buildDir.filePath(QLatin1String("QtCreatorDeployment.txt")));
if (deploymentFile.open(QFile::ReadOnly | QFile::Text)) {
deploymentStream.setDevice(&deploymentFile);
deploymentPrefix = deploymentStream.readLine();
@@ -687,17 +690,18 @@ void CMakeProject::updateApplicationAndDeploymentTargets()
BuildTargetInfoList appTargetList;
DeploymentData deploymentData;
- QDir buildDir(t->activeBuildConfiguration()->buildDirectory().toString());
+
foreach (const CMakeBuildTarget &ct, m_buildTargets) {
if (ct.executable.isEmpty())
continue;
- deploymentData.addFile(ct.executable, deploymentPrefix + buildDir.relativeFilePath(QFileInfo(ct.executable).dir().path()), DeployableFile::TypeExecutable);
- if (!ct.library) {
+ if (ct.targetType == ExecutableType || ct.targetType == DynamicLibraryType)
+ deploymentData.addFile(ct.executable, deploymentPrefix + buildDir.relativeFilePath(QFileInfo(ct.executable).dir().path()), DeployableFile::TypeExecutable);
+ if (ct.targetType == ExecutableType) {
// TODO: Put a path to corresponding .cbp file into projectFilePath?
appTargetList.list << BuildTargetInfo(ct.title,
- Utils::FileName::fromString(ct.executable),
- Utils::FileName::fromString(ct.executable));
+ FileName::fromString(ct.executable),
+ FileName::fromString(ct.executable));
}
}
@@ -738,7 +742,7 @@ CMakeFile::CMakeFile(CMakeProject *parent, QString fileName)
{
setId("Cmake.ProjectFile");
setMimeType(QLatin1String(Constants::CMAKEPROJECTMIMETYPE));
- setFilePath(fileName);
+ setFilePath(FileName::fromString(fileName));
}
bool CMakeFile::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -853,7 +857,7 @@ void CMakeBuildSettingsWidget::runCMake()
////
namespace {
-int distance(const QString &targetDirectory, const Utils::FileName &fileName)
+int distance(const QString &targetDirectory, const FileName &fileName)
{
const QString commonParent = Utils::commonPath(QStringList() << targetDirectory << fileName.toString());
return targetDirectory.mid(commonParent.size()).count(QLatin1Char('/'))
@@ -868,15 +872,15 @@ int distance(const QString &targetDirectory, const Utils::FileName &fileName)
void CMakeCbpParser::sortFiles()
{
QLoggingCategory log("qtc.cmakeprojectmanager.filetargetmapping");
- QList<Utils::FileName> fileNames = Utils::transform(m_fileList, [] (FileNode *node) {
- return Utils::FileName::fromString(node->path());
+ QList<FileName> fileNames = Utils::transform(m_fileList, [] (FileNode *node) {
+ return FileName::fromString(node->path());
});
Utils::sort(fileNames);
CMakeBuildTarget *last = 0;
- Utils::FileName parentDirectory;
+ FileName parentDirectory;
qCDebug(log) << "###############";
qCDebug(log) << "# Pre Dump #";
@@ -905,7 +909,7 @@ void CMakeCbpParser::sortFiles()
qCDebug(log) << "# Sorting #";
qCDebug(log) << "###############";
- foreach (const Utils::FileName &fileName, fileNames) {
+ foreach (const FileName &fileName, fileNames) {
qCDebug(log) << fileName;
if (fileName.parentDir() == parentDirectory && last) {
// easy case, same parent directory as last file
@@ -1051,13 +1055,31 @@ void CMakeCbpParser::parseBuildTargetOption()
} else if (attributes().hasAttribute(QLatin1String("type"))) {
const QStringRef value = attributes().value(QLatin1String("type"));
if (value == QLatin1String("2") || value == QLatin1String("3"))
- m_buildTarget.library = true;
+ m_buildTarget.targetType = TargetType(value.toInt());
} else if (attributes().hasAttribute(QLatin1String("working_dir"))) {
m_buildTarget.workingDirectory = attributes().value(QLatin1String("working_dir")).toString();
- QDir dir(m_buildDirectory);
- QString relative = dir.relativeFilePath(m_buildTarget.workingDirectory);
- m_buildTarget.sourceDirectory
- = Utils::FileName::fromString(m_sourceDirectory).appendPath(relative).toString();
+
+ QFile cmakeSourceInfoFile(m_buildTarget.workingDirectory
+ + QStringLiteral("/CMakeFiles/CMakeDirectoryInformation.cmake"));
+ if (cmakeSourceInfoFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ QTextStream stream(&cmakeSourceInfoFile);
+ const QLatin1String searchSource("SET(CMAKE_RELATIVE_PATH_TOP_SOURCE \"");
+ while (!stream.atEnd()) {
+ const QString lineTopSource = stream.readLine().trimmed();
+ if (lineTopSource.startsWith(searchSource)) {
+ m_buildTarget.sourceDirectory = lineTopSource.mid(searchSource.size());
+ m_buildTarget.sourceDirectory.chop(2); // cut off ")
+ break;
+ }
+ }
+ }
+
+ if (m_buildTarget.sourceDirectory.isEmpty()) {
+ QDir dir(m_buildDirectory);
+ const QString relative = dir.relativeFilePath(m_buildTarget.workingDirectory);
+ m_buildTarget.sourceDirectory
+ = FileName::fromString(m_sourceDirectory).appendPath(relative).toString();
+ }
}
while (!atEnd()) {
readNext();
@@ -1192,7 +1214,7 @@ void CMakeCbpParser::parseUnit()
m_cmakeFileList.append( new ProjectExplorer::FileNode(fileName, ProjectExplorer::ProjectFileType, false));
} else {
bool generated = false;
- QString onlyFileName = QFileInfo(fileName).fileName();
+ QString onlyFileName = FileName::fromString(fileName).fileName();
if ( (onlyFileName.startsWith(QLatin1String("moc_")) && onlyFileName.endsWith(QLatin1String(".cxx")))
|| (onlyFileName.startsWith(QLatin1String("ui_")) && onlyFileName.endsWith(QLatin1String(".h")))
|| (onlyFileName.startsWith(QLatin1String("qrc_")) && onlyFileName.endsWith(QLatin1String(".cxx"))))
@@ -1278,7 +1300,7 @@ void CMakeBuildTarget::clear()
workingDirectory.clear();
sourceDirectory.clear();
title.clear();
- library = false;
+ targetType = ExecutableType;
includeFiles.clear();
compilerOptions.clear();
defines.clear();
diff --git a/src/plugins/cmakeprojectmanager/cmakeproject.h b/src/plugins/cmakeprojectmanager/cmakeproject.h
index e9c262c1861..4c725daced8 100644
--- a/src/plugins/cmakeprojectmanager/cmakeproject.h
+++ b/src/plugins/cmakeprojectmanager/cmakeproject.h
@@ -61,11 +61,17 @@ namespace Internal {
class CMakeFile;
class CMakeBuildSettingsWidget;
+enum TargetType {
+ ExecutableType = 0,
+ StaticLibraryType = 2,
+ DynamicLibraryType = 3
+};
+
struct CMakeBuildTarget
{
QString title;
QString executable; // TODO: rename to output?
- bool library;
+ TargetType targetType;
QString workingDirectory;
QString sourceDirectory;
QString makeCommand;
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
index 66a43ae95e7..20051b8fc1b 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
@@ -40,7 +40,9 @@
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actioncontainer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projectexplorerconstants.h>
#include <QDateTime>
using namespace CMakeProjectManager::Internal;
@@ -48,8 +50,8 @@ using namespace CMakeProjectManager::Internal;
CMakeManager::CMakeManager(CMakeSettingsPage *cmakeSettingsPage)
: m_settingsPage(cmakeSettingsPage)
{
- ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
- connect(projectExplorer, &ProjectExplorer::ProjectExplorerPlugin::aboutToShowContextMenu,
+ ProjectExplorer::ProjectTree *tree = ProjectExplorer::ProjectTree::instance();
+ connect(tree, &ProjectExplorer::ProjectTree::aboutToShowContextMenu,
this, &CMakeManager::updateContextMenu);
Core::ActionContainer *mbuild =
@@ -67,7 +69,7 @@ CMakeManager::CMakeManager(CMakeSettingsPage *cmakeSettingsPage)
command->setAttribute(Core::Command::CA_Hide);
mbuild->addAction(command, ProjectExplorer::Constants::G_BUILD_DEPLOY);
connect(m_runCMakeAction, &QAction::triggered, [this]() {
- runCMake(ProjectExplorer::ProjectExplorerPlugin::currentProject());
+ runCMake(ProjectExplorer::ProjectTree::currentProject());
});
m_runCMakeActionContextMenu = new QAction(QIcon(), tr("Run CMake"), this);
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h b/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h
index e51a171b1c4..c564ae41983 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectnodes.h
@@ -38,7 +38,6 @@ namespace Internal {
class CMakeProjectNode : public ProjectExplorer::ProjectNode
{
- Q_OBJECT
friend class CMakeProject;
public:
CMakeProjectNode(const QString &fileName);
diff --git a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
index 061e6971084..a4406166be5 100644
--- a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
@@ -245,8 +245,7 @@ CMakeRunConfigurationWidget::CMakeRunConfigurationWidget(CMakeRunConfiguration *
fl->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
QLineEdit *argumentsLineEdit = new QLineEdit();
argumentsLineEdit->setText(cmakeRunConfiguration->commandLineArguments());
- connect(argumentsLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(setArguments(QString)));
+ connect(argumentsLineEdit, &QLineEdit::textChanged, this, &CMakeRunConfigurationWidget::setArguments);
fl->addRow(tr("Arguments:"), argumentsLineEdit);
m_workingDirectoryEdit = new Utils::PathChooser();
@@ -257,7 +256,8 @@ CMakeRunConfigurationWidget::CMakeRunConfigurationWidget(CMakeRunConfiguration *
EnvironmentAspect *aspect
= m_cmakeRunConfiguration->extraAspect<EnvironmentAspect>();
if (aspect) {
- connect(aspect, SIGNAL(environmentChanged()), this, SLOT(environmentWasChanged()));
+ connect(aspect, &EnvironmentAspect::environmentChanged,
+ this, &CMakeRunConfigurationWidget::environmentWasChanged);
environmentWasChanged();
}
m_workingDirectoryEdit->setPromptDialogTitle(tr("Select Working Directory"));
@@ -286,17 +286,17 @@ CMakeRunConfigurationWidget::CMakeRunConfigurationWidget(CMakeRunConfiguration *
vbx->setMargin(0);
vbx->addWidget(m_detailsContainer);
- connect(m_workingDirectoryEdit, SIGNAL(changed(QString)),
- this, SLOT(setWorkingDirectory()));
+ connect(m_workingDirectoryEdit, &Utils::PathChooser::changed,
+ this, &CMakeRunConfigurationWidget::setWorkingDirectory);
- connect(resetButton, SIGNAL(clicked()),
- this, SLOT(resetWorkingDirectory()));
+ connect(resetButton, &QToolButton::clicked,
+ this, &CMakeRunConfigurationWidget::resetWorkingDirectory);
- connect(runInTerminal, SIGNAL(toggled(bool)),
- this, SLOT(runInTerminalToggled(bool)));
+ connect(runInTerminal, &QCheckBox::toggled,
+ this, &CMakeRunConfigurationWidget::runInTerminalToggled);
- connect(m_cmakeRunConfiguration, SIGNAL(baseWorkingDirectoryChanged(QString)),
- this, SLOT(workingDirectoryChanged(QString)));
+ connect(m_cmakeRunConfiguration, &CMakeRunConfiguration::baseWorkingDirectoryChanged,
+ this, &CMakeRunConfigurationWidget::workingDirectoryChanged);
setEnabled(m_cmakeRunConfiguration->isEnabled());
}
diff --git a/src/plugins/cmakeprojectmanager/cmaketool.cpp b/src/plugins/cmakeprojectmanager/cmaketool.cpp
index 378a3e632f6..70206d46bf6 100644
--- a/src/plugins/cmakeprojectmanager/cmaketool.cpp
+++ b/src/plugins/cmakeprojectmanager/cmaketool.cpp
@@ -64,8 +64,7 @@ void CMakeTool::setCMakeExecutable(const QString &executable)
{
cancel();
m_process = new QProcess();
- connect(m_process, SIGNAL(finished(int)),
- this, SLOT(finished(int)));
+ connect(m_process, static_cast<void (QProcess::*)(int)>(&QProcess::finished), this, &CMakeTool::finished);
m_executable = executable;
QFileInfo fi(m_executable);
diff --git a/src/plugins/coreplugin/actionmanager/actioncontainer.cpp b/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
index 8431fa0d0a3..99c738064e2 100644
--- a/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
+++ b/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
@@ -44,8 +44,8 @@
Q_DECLARE_METATYPE(Core::Internal::MenuActionContainer*)
-using namespace Core;
-using namespace Core::Internal;
+namespace Core {
+namespace Internal {
/*!
\class ActionContainer
@@ -381,14 +381,16 @@ void ActionContainerPrivate::update()
*/
MenuActionContainer::MenuActionContainer(Id id)
- : ActionContainerPrivate(id), m_menu(0)
+ : ActionContainerPrivate(id),
+ m_menu(new QMenu)
{
+ m_menu->setObjectName(id.toString());
setOnAllDisabledBehavior(Disable);
}
-void MenuActionContainer::setMenu(QMenu *menu)
+MenuActionContainer::~MenuActionContainer()
{
- m_menu = menu;
+ delete m_menu;
}
QMenu *MenuActionContainer::menu() const
@@ -565,3 +567,5 @@ bool MenuBarActionContainer::canBeAddedToMenu() const
return false;
}
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/actionmanager/actioncontainer_p.h b/src/plugins/coreplugin/actionmanager/actioncontainer_p.h
index 03586ab246c..2fc1681a31f 100644
--- a/src/plugins/coreplugin/actionmanager/actioncontainer_p.h
+++ b/src/plugins/coreplugin/actionmanager/actioncontainer_p.h
@@ -46,7 +46,7 @@ struct Group
QList<QObject *> items; // Command * or ActionContainer *
};
-class ActionContainerPrivate : public Core::ActionContainer
+class ActionContainerPrivate : public ActionContainer
{
Q_OBJECT
@@ -105,8 +105,8 @@ class MenuActionContainer : public ActionContainerPrivate
{
public:
explicit MenuActionContainer(Id id);
+ ~MenuActionContainer();
- void setMenu(QMenu *menu);
QMenu *menu() const;
void insertAction(QAction *before, QAction *action);
@@ -120,7 +120,7 @@ protected:
bool updateInternal();
private:
- QMenu *m_menu;
+ QPointer<QMenu> m_menu;
};
class MenuBarActionContainer : public ActionContainerPrivate
diff --git a/src/plugins/coreplugin/actionmanager/actionmanager.cpp b/src/plugins/coreplugin/actionmanager/actionmanager.cpp
index ac3910856c3..f45645e877f 100644
--- a/src/plugins/coreplugin/actionmanager/actionmanager.cpp
+++ b/src/plugins/coreplugin/actionmanager/actionmanager.cpp
@@ -32,17 +32,19 @@
#include "actionmanager_p.h"
#include "actioncontainer_p.h"
#include "command_p.h"
-#include <coreplugin/id.h>
-#include <coreplugin/mainwindow.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/id.h>
+#include <utils/fadingindicator.h>
#include <utils/qtcassert.h>
+#include <QAction>
+#include <QApplication>
#include <QDebug>
-#include <QSettings>
-#include <QLabel>
+#include <QDesktopWidget>
#include <QMenu>
-#include <QAction>
#include <QMenuBar>
+#include <QSettings>
namespace {
enum { warnAboutFindFailures = 0 };
@@ -99,9 +101,9 @@ using namespace Core::Internal;
put the following in your plugin's IPlugin::initialize function:
\code
QAction *myAction = new QAction(tr("My Action"), this);
- Core::Command *cmd = Core::ActionManager::registerAction(myAction,
+ Command *cmd = ActionManager::registerAction(myAction,
"myplugin.myaction",
- Core::Context(C_GLOBAL));
+ Context(C_GLOBAL));
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Alt+u")));
connect(myAction, SIGNAL(triggered()), this, SLOT(performMyAction()));
\endcode
@@ -123,7 +125,7 @@ using namespace Core::Internal;
Following the example adding "My Action" to the "Tools" menu would be done by
\code
- Core::ActionManager::actionContainer(Core::M_TOOLS)->addAction(cmd);
+ ActionManager::actionContainer(M_TOOLS)->addAction(cmd);
\endcode
\section1 Important Guidelines:
@@ -200,11 +202,7 @@ ActionContainer *ActionManager::createMenu(Id id)
if (it != d->m_idContainerMap.constEnd())
return it.value();
- QMenu *m = new QMenu(ICore::mainWindow());
- m->setObjectName(QLatin1String(id.name()));
-
MenuActionContainer *mc = new MenuActionContainer(id);
- mc->setMenu(m);
d->m_idContainerMap.insert(id, mc);
connect(mc, SIGNAL(destroyed()), d, SLOT(containerDestroyed()));
@@ -327,8 +325,8 @@ void ActionManager::unregisterAction(QAction *action, Id id)
a->removeOverrideAction(action);
if (a->isEmpty()) {
// clean up
- // ActionContainers listen to the commands' destroyed signals
ICore::mainWindow()->removeAction(a->action());
+ // ActionContainers listen to the commands' destroyed signals
delete a->action();
d->m_idCmdMap.remove(id);
delete a;
@@ -356,30 +354,17 @@ void ActionManager::setPresentationModeEnabled(bool enabled)
}
}
- // The label for the shortcuts:
- if (!d->m_presentationLabel) {
- d->m_presentationLabel = new QLabel(0, Qt::ToolTip | Qt::WindowStaysOnTopHint);
- QFont font = d->m_presentationLabel->font();
- font.setPixelSize(45);
- d->m_presentationLabel->setFont(font);
- d->m_presentationLabel->setAlignment(Qt::AlignCenter);
- d->m_presentationLabel->setMargin(5);
-
- connect(&d->m_presentationLabelTimer, SIGNAL(timeout()), d->m_presentationLabel, SLOT(hide()));
- } else {
- d->m_presentationLabelTimer.stop();
- delete d->m_presentationLabel;
- d->m_presentationLabel = 0;
- }
+ d->m_presentationModeEnabled = enabled;
}
bool ActionManager::isPresentationModeEnabled()
{
- return d->m_presentationLabel;
+ return d->m_presentationModeEnabled;
}
-void ActionManager::initialize()
+void ActionManager::initialize(QObject *parent)
{
+ new ActionManager(parent);
d->initialize();
}
@@ -400,9 +385,8 @@ void ActionManager::setContext(const Context &context)
*/
ActionManagerPrivate::ActionManagerPrivate()
- : m_presentationLabel(0)
+ : m_presentationModeEnabled(false)
{
- m_presentationLabelTimer.setInterval(1000);
}
ActionManagerPrivate::~ActionManagerPrivate()
@@ -460,15 +444,18 @@ void ActionManagerPrivate::showShortcutPopup(const QString &shortcut)
if (shortcut.isEmpty() || !ActionManager::isPresentationModeEnabled())
return;
- m_presentationLabel->setText(shortcut);
- m_presentationLabel->adjustSize();
-
- QPoint p = ICore::mainWindow()->mapToGlobal(ICore::mainWindow()->rect().center() - m_presentationLabel->rect().center());
- m_presentationLabel->move(p);
+ QWidget *window = QApplication::activeWindow();
+ if (!window) {
+ if (!QApplication::topLevelWidgets().isEmpty()) {
+ window = QApplication::topLevelWidgets().first();
+ } else {
+ QTC_ASSERT(QApplication::desktop(), return);
+ window = QApplication::desktop()->screen();
+ QTC_ASSERT(window, return);
+ }
+ }
- m_presentationLabel->show();
- m_presentationLabel->raise();
- m_presentationLabelTimer.start();
+ Utils::FadingIndicator::showText(window, shortcut);
}
Action *ActionManagerPrivate::overridableAction(Id id)
@@ -492,7 +479,7 @@ Action *ActionManagerPrivate::overridableAction(Id id)
void ActionManagerPrivate::readUserSettings(Id id, Action *cmd)
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String(kKeyboardSettingsKey));
if (settings->contains(id.toString()))
cmd->setKeySequence(QKeySequence(settings->value(id.toString()).toString()));
@@ -511,7 +498,7 @@ void ActionManagerPrivate::initialize()
// settings->contains(QLatin1String(kKeyboardSettingsKey) + QLatin1Char('/')
// + QLatin1String(kKeyboardSettingsTransferredKey))
// check if settings in old style (pre 3.1) exist
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
if (settings->contains(QLatin1String(kKeyboardSettingsKey) + QLatin1Char('/')
+ QLatin1String(kKeyboardSettingsTransferredKey))) {
return;
diff --git a/src/plugins/coreplugin/actionmanager/actionmanager.h b/src/plugins/coreplugin/actionmanager/actionmanager.h
index 661b7c56bb1..eeab8fba9b7 100644
--- a/src/plugins/coreplugin/actionmanager/actionmanager.h
+++ b/src/plugins/coreplugin/actionmanager/actionmanager.h
@@ -48,7 +48,10 @@ namespace Core {
class ActionContainer;
-namespace Internal { class MainWindow; }
+namespace Internal {
+class CorePlugin;
+class MainWindow;
+} // Internal
class CORE_EXPORT ActionManager : public QObject
{
@@ -78,11 +81,12 @@ signals:
private:
ActionManager(QObject *parent = 0);
~ActionManager();
- static void initialize();
- void saveSettings(QSettings *settings);
- void setContext(const Context &context);
+ static void initialize(QObject *parent);
+ static void saveSettings(QSettings *settings);
+ static void setContext(const Context &context);
- friend class Core::Internal::MainWindow;
+ friend class Core::Internal::CorePlugin; // initialization
+ friend class Core::Internal::MainWindow; // saving settings and setting context
};
} // namespace Core
diff --git a/src/plugins/coreplugin/actionmanager/actionmanager_p.h b/src/plugins/coreplugin/actionmanager/actionmanager_p.h
index 9460c0ca1de..337cbe135b3 100644
--- a/src/plugins/coreplugin/actionmanager/actionmanager_p.h
+++ b/src/plugins/coreplugin/actionmanager/actionmanager_p.h
@@ -58,8 +58,8 @@ class ActionManagerPrivate : public QObject
Q_OBJECT
public:
- typedef QHash<Core::Id, Action *> IdCmdMap;
- typedef QHash<Core::Id, ActionContainerPrivate *> IdContainerMap;
+ typedef QHash<Id, Action *> IdCmdMap;
+ typedef QHash<Id, ActionContainerPrivate *> IdContainerMap;
explicit ActionManagerPrivate();
~ActionManagerPrivate();
@@ -89,6 +89,7 @@ public:
Context m_context;
+ bool m_presentationModeEnabled;
QLabel *m_presentationLabel;
QTimer m_presentationLabelTimer;
};
diff --git a/src/plugins/coreplugin/actionmanager/command.cpp b/src/plugins/coreplugin/actionmanager/command.cpp
index 64dc2b14c59..e81e4f6c1b6 100644
--- a/src/plugins/coreplugin/actionmanager/command.cpp
+++ b/src/plugins/coreplugin/actionmanager/command.cpp
@@ -194,8 +194,8 @@
interact with it.
*/
-using namespace Core;
-using namespace Core::Internal;
+namespace Core {
+namespace Internal {
/*!
\class Action
@@ -275,7 +275,7 @@ QString Action::description() const
return id().toString();
}
-void Action::setCurrentContext(const Core::Context &context)
+void Action::setCurrentContext(const Context &context)
{
m_context = context;
@@ -309,7 +309,7 @@ static QString msgActionWarning(QAction *newAction, Id id, QAction *oldAction)
return msg;
}
-void Action::addOverrideAction(QAction *action, const Core::Context &context, bool scriptable)
+void Action::addOverrideAction(QAction *action, const Context &context, bool scriptable)
{
if (Utils::HostOsInfo::isMacHost())
action->setIconVisibleInMenu(false);
@@ -369,7 +369,7 @@ bool Action::isScriptable() const
return m_scriptableMap.values().contains(true);
}
-bool Action::isScriptable(const Core::Context &context) const
+bool Action::isScriptable(const Context &context) const
{
if (context == m_context && m_scriptableMap.contains(m_action->action()))
return m_scriptableMap.value(m_action->action());
@@ -387,16 +387,16 @@ void Action::setAttribute(CommandAttribute attr)
{
m_attributes |= attr;
switch (attr) {
- case Core::Command::CA_Hide:
+ case Command::CA_Hide:
m_action->setAttribute(Utils::ProxyAction::Hide);
break;
- case Core::Command::CA_UpdateText:
+ case Command::CA_UpdateText:
m_action->setAttribute(Utils::ProxyAction::UpdateText);
break;
- case Core::Command::CA_UpdateIcon:
+ case Command::CA_UpdateIcon:
m_action->setAttribute(Utils::ProxyAction::UpdateIcon);
break;
- case Core::Command::CA_NonConfigurable:
+ case Command::CA_NonConfigurable:
break;
}
}
@@ -405,16 +405,16 @@ void Action::removeAttribute(CommandAttribute attr)
{
m_attributes &= ~attr;
switch (attr) {
- case Core::Command::CA_Hide:
+ case Command::CA_Hide:
m_action->removeAttribute(Utils::ProxyAction::Hide);
break;
- case Core::Command::CA_UpdateText:
+ case Command::CA_UpdateText:
m_action->removeAttribute(Utils::ProxyAction::UpdateText);
break;
- case Core::Command::CA_UpdateIcon:
+ case Command::CA_UpdateIcon:
m_action->removeAttribute(Utils::ProxyAction::UpdateIcon);
break;
- case Core::Command::CA_NonConfigurable:
+ case Command::CA_NonConfigurable:
break;
}
}
@@ -424,11 +424,12 @@ bool Action::hasAttribute(Command::CommandAttribute attr) const
return (m_attributes & attr);
}
+} // namespace Internal
void Command::augmentActionWithShortcutToolTip(QAction *a) const
{
a->setToolTip(stringWithAppendedShortcut(a->text()));
- QObject::connect(this, &Core::Command::keySequenceChanged, a, [this, a]() {
+ QObject::connect(this, &Command::keySequenceChanged, a, [this, a]() {
a->setToolTip(stringWithAppendedShortcut(a->text()));
});
QObject::connect(a, &QAction::changed, this, [this, a]() {
@@ -444,3 +445,5 @@ QToolButton *Command::toolButtonWithAppendedShortcut(QAction *action, Command *c
cmd->augmentActionWithShortcutToolTip(action);
return button;
}
+
+} // namespace Core
diff --git a/src/plugins/coreplugin/actionmanager/command_p.h b/src/plugins/coreplugin/actionmanager/command_p.h
index cc4b1104d35..de2611c56b1 100644
--- a/src/plugins/coreplugin/actionmanager/command_p.h
+++ b/src/plugins/coreplugin/actionmanager/command_p.h
@@ -47,7 +47,7 @@
namespace Core {
namespace Internal {
-class Action : public Core::Command
+class Action : public Command
{
Q_OBJECT
public:
diff --git a/src/plugins/coreplugin/actionmanager/commandbutton.h b/src/plugins/coreplugin/actionmanager/commandbutton.h
index e5873c62ba7..bf0afef4383 100644
--- a/src/plugins/coreplugin/actionmanager/commandbutton.h
+++ b/src/plugins/coreplugin/actionmanager/commandbutton.h
@@ -57,7 +57,7 @@ private slots:
void updateToolTip();
private:
- QPointer<Core::Command> m_command;
+ QPointer<Command> m_command;
QString m_toolTipBase;
};
diff --git a/src/plugins/coreplugin/actionmanager/commandmappings.h b/src/plugins/coreplugin/actionmanager/commandmappings.h
index 7885557992e..8fbb3951719 100644
--- a/src/plugins/coreplugin/actionmanager/commandmappings.h
+++ b/src/plugins/coreplugin/actionmanager/commandmappings.h
@@ -47,7 +47,7 @@ namespace Core {
namespace Internal { class CommandMappingsPrivate; }
-class CORE_EXPORT CommandMappings : public Core::IOptionsPage
+class CORE_EXPORT CommandMappings : public IOptionsPage
{
Q_OBJECT
diff --git a/src/plugins/coreplugin/actionmanager/commandsfile.cpp b/src/plugins/coreplugin/actionmanager/commandsfile.cpp
index fe9aea09c94..edd865aea3d 100644
--- a/src/plugins/coreplugin/actionmanager/commandsfile.cpp
+++ b/src/plugins/coreplugin/actionmanager/commandsfile.cpp
@@ -141,7 +141,7 @@ bool CommandsFile::exportCommands(const QList<ShortcutItem *> &items)
w.writeStartDocument();
w.writeDTD(QLatin1String("<!DOCTYPE KeyboardMappingScheme>"));
w.writeComment(QString::fromLatin1(" Written by Qt Creator %1, %2. ").
- arg(QLatin1String(Core::Constants::IDE_VERSION_LONG),
+ arg(QLatin1String(Constants::IDE_VERSION_LONG),
QDateTime::currentDateTime().toString(Qt::ISODate)));
w.writeStartElement(ctx.mappingElement);
foreach (const ShortcutItem *item, items) {
diff --git a/src/plugins/coreplugin/basefilewizardfactory.cpp b/src/plugins/coreplugin/basefilewizardfactory.cpp
index 7aaafffe5f3..c11912334c9 100644
--- a/src/plugins/coreplugin/basefilewizardfactory.cpp
+++ b/src/plugins/coreplugin/basefilewizardfactory.cpp
@@ -31,6 +31,7 @@
#include "basefilewizardfactory.h"
#include "basefilewizard.h"
+#include "icontext.h"
#include "icore.h"
#include "ifilewizardextension.h"
#include "mimedatabase.h"
@@ -220,6 +221,7 @@ void BaseFileWizardFactory::runWizard(const QString &path, QWidget *parent, cons
dialogParameterFlags,
extraValues)));
QTC_ASSERT(!wizard.isNull(), return);
+ ICore::registerWindow(wizard.data(), Context("Core.NewWizard"));
GeneratedFiles files;
// Run the wizard: Call generate files on switching to the first extension
@@ -452,8 +454,9 @@ QString BaseFileWizardFactory::buildFileName(const QString &path,
const QString &extension)
{
QString rc = path;
- if (!rc.isEmpty() && !rc.endsWith(QDir::separator()))
- rc += QDir::separator();
+ const QChar slash = QLatin1Char('/');
+ if (!rc.isEmpty() && !rc.endsWith(slash))
+ rc += slash;
rc += baseName;
// Add extension unless user specified something else
const QChar dot = QLatin1Char('.');
diff --git a/src/plugins/coreplugin/basefilewizardfactory.h b/src/plugins/coreplugin/basefilewizardfactory.h
index fa21c2d29c7..44f3d64248b 100644
--- a/src/plugins/coreplugin/basefilewizardfactory.h
+++ b/src/plugins/coreplugin/basefilewizardfactory.h
@@ -66,7 +66,7 @@ public:
Q_DECLARE_FLAGS(DialogParameterFlags, DialogParameterEnum)
explicit WizardDialogParameters(const QString &defaultPath, const WizardPageList &extensionPages,
- const QString &platform, const Core::FeatureSet &requiredFeatures,
+ const QString &platform, const FeatureSet &requiredFeatures,
DialogParameterFlags flags,
QVariantMap extraValues)
: m_defaultPath(defaultPath),
@@ -86,7 +86,7 @@ public:
QString selectedPlatform() const
{ return m_selectedPlatform; }
- Core::FeatureSet requiredFeatures() const
+ FeatureSet requiredFeatures() const
{ return m_requiredFeatures; }
DialogParameterFlags flags() const
@@ -99,7 +99,7 @@ private:
QString m_defaultPath;
WizardPageList m_extensionPages;
QString m_selectedPlatform;
- Core::FeatureSet m_requiredFeatures;
+ FeatureSet m_requiredFeatures;
DialogParameterFlags m_parameterFlags;
QVariantMap m_extraValues;
};
diff --git a/src/plugins/coreplugin/corejsextensions.cpp b/src/plugins/coreplugin/corejsextensions.cpp
index 30dd2b2082d..2bc1d746d37 100644
--- a/src/plugins/coreplugin/corejsextensions.cpp
+++ b/src/plugins/coreplugin/corejsextensions.cpp
@@ -90,7 +90,7 @@ QString UtilsJsExtension::absoluteFilePath(const QString &in) const
QString UtilsJsExtension::preferredSuffix(const QString &mimetype) const
{
- return Core::MimeDatabase::preferredSuffixByType(mimetype);
+ return MimeDatabase::preferredSuffixByType(mimetype);
}
QString UtilsJsExtension::fileName(const QString &path, const QString &extension) const
diff --git a/src/plugins/coreplugin/coreplugin.cpp b/src/plugins/coreplugin/coreplugin.cpp
index 0477ab05ab6..fe4abb94481 100644
--- a/src/plugins/coreplugin/coreplugin.cpp
+++ b/src/plugins/coreplugin/coreplugin.cpp
@@ -66,7 +66,7 @@ CorePlugin::CorePlugin()
, m_findPlugin(0)
, m_locator(0)
{
- qRegisterMetaType<Core::Id>();
+ qRegisterMetaType<Id>();
}
CorePlugin::~CorePlugin()
@@ -142,7 +142,7 @@ void CorePlugin::parseArguments(const QStringList &arguments)
themeName = defaultTheme;
themeURI = QStringLiteral("%1/themes/%2.creatortheme").arg(ICore::resourcePath()).arg(themeName);
if (themeURI.isEmpty()) {
- qCritical("%s", qPrintable(QCoreApplication::translate("Application", "No valid theme '%1'")
+ qCritical("%s", qPrintable(QCoreApplication::translate("Application", "No valid theme \"%1\"")
.arg(themeName)));
}
}
@@ -167,6 +167,7 @@ void CorePlugin::parseArguments(const QStringList &arguments)
bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
+ ActionManager::initialize(this);
Theme::initialPalette(); // Initialize palette before setting it
qsrand(QDateTime::currentDateTime().toTime_t());
parseArguments(arguments);
@@ -180,12 +181,12 @@ bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage)
}
// Make sure we respect the process's umask when creating new files
- Utils::SaveFile::initializeUmask();
+ SaveFile::initializeUmask();
m_findPlugin->initialize(arguments, errorMessage);
m_locator->initialize(this, arguments, errorMessage);
- Utils::MacroExpander *expander = Utils::globalMacroExpander();
+ MacroExpander *expander = Utils::globalMacroExpander();
expander->registerVariable("CurrentDate:ISO", tr("The current date (ISO)."),
[]() { return QDate::currentDate().toString(Qt::ISODate); });
expander->registerVariable("CurrentTime:ISO", tr("The current time (ISO)."),
@@ -198,9 +199,9 @@ bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage)
[]() { return QDate::currentDate().toString(Qt::DefaultLocaleShortDate); });
expander->registerVariable("CurrentTime:Locale", tr("The current time (Locale)."),
[]() { return QTime::currentTime().toString(Qt::DefaultLocaleShortDate); });
- expander->registerPrefix("CurrentDate:", tr("The current date (QDate formatstring)"),
+ expander->registerPrefix("CurrentDate:", tr("The current date (QDate formatstring)."),
[](const QString &fmt) { return QDate::currentDate().toString(fmt); });
- expander->registerPrefix("CurrentTime:", tr("The current time (QTime formatstring)"),
+ expander->registerPrefix("CurrentTime:", tr("The current time (QTime formatstring)."),
[](const QString &fmt) { return QTime::currentTime().toString(fmt); });
return success;
diff --git a/src/plugins/coreplugin/coreplugin.pro b/src/plugins/coreplugin/coreplugin.pro
index 8d43fb816b5..1ecac8020a8 100644
--- a/src/plugins/coreplugin/coreplugin.pro
+++ b/src/plugins/coreplugin/coreplugin.pro
@@ -6,7 +6,6 @@ QT += help \
sql
include(../../qtcreatorplugin.pri)
-include(../../shared/scriptwrapper/scriptwrapper.pri)
win32-msvc*:QMAKE_CXXFLAGS += -wd4251 -wd4290 -wd4250
SOURCES += corejsextensions.cpp \
mainwindow.cpp \
@@ -111,7 +110,10 @@ SOURCES += corejsextensions.cpp \
themeeditor/colorrole.cpp \
themeeditor/themesettingstablemodel.cpp \
themeeditor/sectionedtablemodel.cpp \
- themeeditor/themesettingsitemdelegate.cpp
+ themeeditor/themesettingsitemdelegate.cpp \
+ messagebox.cpp \
+ iwelcomepage.cpp \
+ externaltoolmanager.cpp
HEADERS += corejsextensions.h \
mainwindow.h \
@@ -227,6 +229,8 @@ HEADERS += corejsextensions.h \
themeeditor/themesettingstablemodel.h \
themeeditor/sectionedtablemodel.h \
themeeditor/themesettingsitemdelegate.h \
+ messagebox.h \
+ iwelcomepage.h
FORMS += dialogs/newdialog.ui \
dialogs/saveitemsdialog.ui \
diff --git a/src/plugins/coreplugin/coreplugin.qbs b/src/plugins/coreplugin/coreplugin.qbs
index cd7c2bd9c65..26c5a0bfc09 100644
--- a/src/plugins/coreplugin/coreplugin.qbs
+++ b/src/plugins/coreplugin/coreplugin.qbs
@@ -45,7 +45,7 @@ QtcPlugin {
"editmode.cpp", "editmode.h",
"editortoolbar.cpp", "editortoolbar.h",
"externaltool.cpp", "externaltool.h",
- "externaltoolmanager.h",
+ "externaltoolmanager.cpp", "externaltoolmanager.h",
"fancyactionbar.cpp", "fancyactionbar.h", "fancyactionbar.qrc",
"fancytabwidget.cpp", "fancytabwidget.h",
"featureprovider.cpp", "featureprovider.h",
@@ -67,10 +67,12 @@ QtcPlugin {
"infobar.cpp", "infobar.h",
"ioutputpane.cpp", "ioutputpane.h",
"iversioncontrol.cpp", "iversioncontrol.h",
+ "iwelcomepage.cpp", "iwelcomepage.h",
"iwizardfactory.cpp", "iwizardfactory.h",
"jsexpander.cpp", "jsexpander.h",
"mainwindow.cpp", "mainwindow.h",
"manhattanstyle.cpp", "manhattanstyle.h",
+ "messagebox.cpp", "messagebox.h",
"messagemanager.cpp", "messagemanager.h",
"messageoutputwindow.cpp", "messageoutputwindow.h",
"mimedatabase.cpp", "mimedatabase.h",
@@ -278,9 +280,9 @@ QtcPlugin {
"locatorwidget.h",
"opendocumentsfilter.cpp",
"opendocumentsfilter.h",
- "settingspage.cpp",
- "settingspage.h",
- "settingspage.ui",
+ "locatorsettingspage.cpp",
+ "locatorsettingspage.h",
+ "locatorsettingspage.ui",
"images/locator.png",
"images/reload.png",
]
diff --git a/src/plugins/coreplugin/designmode.cpp b/src/plugins/coreplugin/designmode.cpp
index 78ef2d10d61..fe5dd3556f7 100644
--- a/src/plugins/coreplugin/designmode.cpp
+++ b/src/plugins/coreplugin/designmode.cpp
@@ -56,7 +56,7 @@ enum {
namespace Internal {
-class DesignModeCoreListener : public Core::ICoreListener
+class DesignModeCoreListener : public ICoreListener
{
public:
DesignModeCoreListener(DesignMode* mode);
@@ -93,7 +93,7 @@ public:
public:
Internal::DesignModeCoreListener *m_coreListener;
- QPointer<Core::IEditor> m_currentEditor;
+ QPointer<IEditor> m_currentEditor;
bool m_isActive;
bool m_isRequired;
QList<DesignEditorInfo*> m_editors;
@@ -124,11 +124,11 @@ DesignMode::DesignMode()
ExtensionSystem::PluginManager::addObject(d->m_coreListener);
- connect(EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
- this, SLOT(currentEditorChanged(Core::IEditor*)));
+ connect(EditorManager::instance(), &EditorManager::currentEditorChanged,
+ this, &DesignMode::currentEditorChanged);
- connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*,Core::IMode*)),
- this, SLOT(updateContext(Core::IMode*,Core::IMode*)));
+ connect(ModeManager::instance(), &ModeManager::currentModeChanged,
+ this, &DesignMode::updateContext);
}
DesignMode::~DesignMode()
@@ -196,7 +196,7 @@ void DesignMode::unregisterDesignWidget(QWidget *widget)
}
// if editor changes, check if we have valid mimetype registered.
-void DesignMode::currentEditorChanged(Core::IEditor *editor)
+void DesignMode::currentEditorChanged(IEditor *editor)
{
if (editor && (d->m_currentEditor.data() == editor))
return;
@@ -227,7 +227,7 @@ void DesignMode::currentEditorChanged(Core::IEditor *editor)
if (!mimeEditorAvailable) {
setActiveContext(Context());
if (ModeManager::currentMode() == this)
- ModeManager::activateMode(Core::Constants::MODE_EDIT);
+ ModeManager::activateMode(Constants::MODE_EDIT);
setEnabled(false);
d->m_currentEditor = 0;
emit actionsUpdated(d->m_currentEditor.data());
@@ -246,7 +246,7 @@ void DesignMode::updateActions()
emit actionsUpdated(d->m_currentEditor.data());
}
-void DesignMode::updateContext(Core::IMode *newMode, Core::IMode *oldMode)
+void DesignMode::updateContext(IMode *newMode, IMode *oldMode)
{
if (newMode == this)
ICore::addAdditionalContext(d->m_activeContext);
@@ -260,7 +260,7 @@ void DesignMode::setActiveContext(const Context &context)
return;
if (ModeManager::currentMode() == this)
- Core::ICore::updateAdditionalContexts(d->m_activeContext, context);
+ ICore::updateAdditionalContexts(d->m_activeContext, context);
d->m_activeContext = context;
}
diff --git a/src/plugins/coreplugin/designmode.h b/src/plugins/coreplugin/designmode.h
index 04957cb33d4..723585f8cb6 100644
--- a/src/plugins/coreplugin/designmode.h
+++ b/src/plugins/coreplugin/designmode.h
@@ -47,7 +47,7 @@ namespace Internal { class DesignModeCoreListener; }
class DesignModePrivate;
-class CORE_EXPORT DesignMode : public Core::IMode
+class CORE_EXPORT DesignMode : public IMode
{
Q_OBJECT
@@ -71,11 +71,11 @@ signals:
void actionsUpdated(Core::IEditor *editor);
private slots:
- void currentEditorChanged(Core::IEditor *editor);
void updateActions();
- void updateContext(Core::IMode *newMode, Core::IMode *oldMode);
private:
+ void currentEditorChanged(IEditor *editor);
+ void updateContext(IMode *newMode, IMode *oldMode);
void setActiveContext(const Context &context);
DesignModePrivate *d;
diff --git a/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp b/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp
index 763d704b257..93073a76a42 100644
--- a/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp
+++ b/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp
@@ -41,9 +41,11 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/variablechooser.h>
+#include <QDialogButtonBox>
#include <QTextStream>
#include <QMimeData>
#include <QMenu>
+#include <QPlainTextEdit>
using namespace Core;
using namespace Core::Internal;
@@ -396,6 +398,44 @@ void ExternalToolModel::removeTool(const QModelIndex &modelIndex)
delete tool;
}
+EnvironmentChangesDialog::EnvironmentChangesDialog(QWidget *parent) :
+ QDialog(parent),
+ m_editor(0)
+{
+ setWindowTitle(tr("Edit Environment Changes"));
+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
+ setModal(true);
+
+ QVBoxLayout *layout = new QVBoxLayout(this);
+ QLabel *label = new QLabel(this);
+ label->setText(tr("Change system environment by assigning one environment variable per line:"));
+ layout->addWidget(label);
+
+ m_editor = new QPlainTextEdit(this);
+ if (Utils::HostOsInfo::isWindowsHost())
+ m_editor->setPlaceholderText(tr("PATH=C:\\dev\\bin;${PATH}"));
+ else
+ m_editor->setPlaceholderText(tr("PATH=/opt/bin:${PATH}"));
+
+ QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
+
+ layout->addWidget(m_editor);
+ layout->addWidget(buttons);
+
+ connect(buttons, &QDialogButtonBox::accepted, this, &EnvironmentChangesDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, this, &EnvironmentChangesDialog::reject);
+}
+
+QStringList EnvironmentChangesDialog::changes() const
+{
+ return m_editor->toPlainText().split(QLatin1Char('\n'));
+}
+
+void EnvironmentChangesDialog::setChanges(const QStringList &changes)
+{
+ m_editor->setPlainText(changes.join(QLatin1Char('\n')));
+}
+
// #pragma mark -- ExternalToolConfig
ExternalToolConfig::ExternalToolConfig(QWidget *parent) :
@@ -423,6 +463,7 @@ ExternalToolConfig::ExternalToolConfig(QWidget *parent) :
connect(ui->arguments, SIGNAL(editingFinished()), this, SLOT(updateEffectiveArguments()));
connect(ui->workingDirectory, SIGNAL(editingFinished()), this, SLOT(updateCurrentItem()));
connect(ui->workingDirectory, SIGNAL(browsingFinished()), this, SLOT(updateCurrentItem()));
+ connect(ui->environmentButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges()));
connect(ui->outputBehavior, SIGNAL(activated(int)), this, SLOT(updateCurrentItem()));
connect(ui->errorOutputBehavior, SIGNAL(activated(int)), this, SLOT(updateCurrentItem()));
connect(ui->modifiesDocumentCheckbox, SIGNAL(clicked()), this, SLOT(updateCurrentItem()));
@@ -510,6 +551,7 @@ void ExternalToolConfig::updateItem(const QModelIndex &index)
tool->setExecutables(executables);
tool->setArguments(ui->arguments->text());
tool->setWorkingDirectory(ui->workingDirectory->rawPath());
+ tool->setEnvironment(Utils::EnvironmentItem::fromStringList(m_environment));
tool->setOutputHandling((ExternalTool::OutputHandling)ui->outputBehavior->currentIndex());
tool->setErrorHandling((ExternalTool::OutputHandling)ui->errorOutputBehavior->currentIndex());
tool->setModifiesCurrentDocument(ui->modifiesDocumentCheckbox->checkState());
@@ -527,6 +569,7 @@ void ExternalToolConfig::showInfoForItem(const QModelIndex &index)
ui->workingDirectory->setPath(QString());
ui->inputText->clear();
ui->infoWidget->setEnabled(false);
+ m_environment.clear();
return;
}
ui->infoWidget->setEnabled(true);
@@ -537,6 +580,7 @@ void ExternalToolConfig::showInfoForItem(const QModelIndex &index)
ui->outputBehavior->setCurrentIndex((int)tool->outputHandling());
ui->errorOutputBehavior->setCurrentIndex((int)tool->errorHandling());
ui->modifiesDocumentCheckbox->setChecked(tool->modifiesCurrentDocument());
+ m_environment = Utils::EnvironmentItem::toStringList(tool->environment());
bool blocked = ui->inputText->blockSignals(true);
ui->inputText->setPlainText(tool->input());
@@ -544,6 +588,7 @@ void ExternalToolConfig::showInfoForItem(const QModelIndex &index)
ui->description->setCursorPosition(0);
ui->arguments->setCursorPosition(0);
+ updateEnvironmentLabel();
updateEffectiveArguments();
}
@@ -596,3 +641,21 @@ void ExternalToolConfig::updateEffectiveArguments()
{
ui->arguments->setToolTip(Utils::globalMacroExpander()->expandProcessArgs(ui->arguments->text()));
}
+
+void ExternalToolConfig::editEnvironmentChanges()
+{
+ EnvironmentChangesDialog dialog(ui->environmentLabel);
+ dialog.setChanges(m_environment);
+ if (dialog.exec() == QDialog::Accepted) {
+ m_environment = dialog.changes();
+ updateEnvironmentLabel();
+ }
+}
+
+void ExternalToolConfig::updateEnvironmentLabel()
+{
+ QString shortSummary = m_environment.join(QLatin1String("; "));
+ QFontMetrics fm(ui->environmentLabel->font());
+ shortSummary = fm.elidedText(shortSummary, Qt::ElideRight, ui->environmentLabel->width());
+ ui->environmentLabel->setText(shortSummary.isEmpty() ? tr("No Changes to apply") : shortSummary);
+}
diff --git a/src/plugins/coreplugin/dialogs/externaltoolconfig.h b/src/plugins/coreplugin/dialogs/externaltoolconfig.h
index e36aa08ff50..67baec751ad 100644
--- a/src/plugins/coreplugin/dialogs/externaltoolconfig.h
+++ b/src/plugins/coreplugin/dialogs/externaltoolconfig.h
@@ -35,6 +35,9 @@
#include <QWidget>
#include <QAbstractItemModel>
+#include <QDialog>
+
+QT_FORWARD_DECLARE_CLASS(QPlainTextEdit)
namespace Core {
namespace Internal {
@@ -82,6 +85,17 @@ private:
QMap<QString, QList<ExternalTool *> > m_tools;
};
+class EnvironmentChangesDialog : public QDialog
+{
+ Q_OBJECT
+public:
+ explicit EnvironmentChangesDialog(QWidget *parent = 0);
+
+ QStringList changes() const;
+ void setChanges(const QStringList &changes);
+private:
+ QPlainTextEdit *m_editor;
+};
class ExternalToolConfig : public QWidget
{
@@ -106,9 +120,12 @@ private slots:
void removeTool();
void addCategory();
void updateEffectiveArguments();
+ void editEnvironmentChanges();
+ void updateEnvironmentLabel();
private:
Ui::ExternalToolConfig *ui;
+ QStringList m_environment;
ExternalToolModel *m_model;
};
diff --git a/src/plugins/coreplugin/dialogs/externaltoolconfig.ui b/src/plugins/coreplugin/dialogs/externaltoolconfig.ui
index c3302139787..39beea46397 100644
--- a/src/plugins/coreplugin/dialogs/externaltoolconfig.ui
+++ b/src/plugins/coreplugin/dialogs/externaltoolconfig.ui
@@ -210,7 +210,41 @@
</item>
</widget>
</item>
+ <item row="6" column="0">
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>Environment:</string>
+ </property>
+ </widget>
+ </item>
<item row="6" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <property name="spacing">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="environmentLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>No Changes to apply.</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="environmentButton">
+ <property name="text">
+ <string>Change...</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="7" column="1">
<widget class="QCheckBox" name="modifiesDocumentCheckbox">
<property name="toolTip">
<string>If the tool modifies the current document, set this flag to ensure that the document is saved before running the tool and is reloaded after the tool finished.</string>
@@ -220,7 +254,7 @@
</property>
</widget>
</item>
- <item row="7" column="0">
+ <item row="8" column="0">
<widget class="QLabel" name="inputLabel">
<property name="toolTip">
<string>Text to pass to the executable via standard input. Leave empty if the executable should not receive any input.</string>
@@ -230,7 +264,7 @@
</property>
</widget>
</item>
- <item row="7" column="1">
+ <item row="8" column="1">
<widget class="QPlainTextEdit" name="inputText">
<property name="lineWrapMode">
<enum>QPlainTextEdit::NoWrap</enum>
diff --git a/src/plugins/coreplugin/dialogs/ioptionspage.h b/src/plugins/coreplugin/dialogs/ioptionspage.h
index 2067b532e3a..247437fbb53 100644
--- a/src/plugins/coreplugin/dialogs/ioptionspage.h
+++ b/src/plugins/coreplugin/dialogs/ioptionspage.h
@@ -90,7 +90,7 @@ class CORE_EXPORT IOptionsPageProvider : public QObject
public:
IOptionsPageProvider(QObject *parent = 0) : QObject(parent) {}
- Core::Id category() const { return m_category; }
+ Id category() const { return m_category; }
QString displayCategory() const { return m_displayCategory; }
QIcon categoryIcon() const { return QIcon(m_categoryIcon); }
@@ -98,11 +98,11 @@ public:
virtual bool matches(const QString & /* searchKeyWord*/) const = 0;
protected:
- void setCategory(Core::Id category) { m_category = category; }
+ void setCategory(Id category) { m_category = category; }
void setDisplayCategory(const QString &displayCategory) { m_displayCategory = displayCategory; }
void setCategoryIcon(const QString &categoryIcon) { m_categoryIcon = categoryIcon; }
- Core::Id m_category;
+ Id m_category;
QString m_displayCategory;
QString m_categoryIcon;
};
diff --git a/src/plugins/coreplugin/dialogs/newdialog.cpp b/src/plugins/coreplugin/dialogs/newdialog.cpp
index 132addc41fb..b6a96270b7d 100644
--- a/src/plugins/coreplugin/dialogs/newdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/newdialog.cpp
@@ -33,6 +33,7 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
+#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <utils/qtcassert.h>
@@ -192,12 +193,13 @@ QString NewDialog::m_lastCategory = QString();
NewDialog::NewDialog(QWidget *parent) :
QDialog(parent),
- m_ui(new Core::Internal::Ui::NewDialog),
+ m_ui(new Ui::NewDialog),
m_okButton(0)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setWindowFlags(windowFlags());
setAttribute(Qt::WA_DeleteOnClose);
+ ICore::registerWindow(this, Context("Core.NewDialog"));
m_ui->setupUi(this);
QPalette p = m_ui->frame->palette();
p.setColor(QPalette::Window, p.color(QPalette::Base));
diff --git a/src/plugins/coreplugin/dialogs/openwithdialog.cpp b/src/plugins/coreplugin/dialogs/openwithdialog.cpp
index 70a1794f3c6..1da7b5103a6 100644
--- a/src/plugins/coreplugin/dialogs/openwithdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/openwithdialog.cpp
@@ -30,8 +30,9 @@
#include "openwithdialog.h"
+#include <utils/fileutils.h>
+
#include <QPushButton>
-#include <QFileInfo>
using namespace Core;
using namespace Core::Internal;
@@ -41,7 +42,7 @@ OpenWithDialog::OpenWithDialog(const QString &fileName, QWidget *parent)
{
setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
- label->setText(tr("Open file \"%1\" with:").arg(QFileInfo(fileName).fileName()));
+ label->setText(tr("Open file \"%1\" with:").arg(Utils::FileName::fromString(fileName).fileName()));
buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);
connect(buttonBox->button(QDialogButtonBox::Ok), SIGNAL(clicked()),
diff --git a/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp b/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp
index ff912a47a63..c85216ed0a3 100644
--- a/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/readonlyfilesdialog.cpp
@@ -162,7 +162,7 @@ ReadOnlyFilesDialog::ReadOnlyFilesDialog(IDocument *document, QWidget *parent,
: QDialog(parent)
, d(new ReadOnlyFilesDialogPrivate(this, document, displaySaveAs))
{
- d->initDialog(QStringList(document->filePath()));
+ d->initDialog(QStringList(document->filePath().toString()));
}
ReadOnlyFilesDialog::ReadOnlyFilesDialog(const QList<IDocument *> &documents, QWidget *parent)
@@ -171,7 +171,7 @@ ReadOnlyFilesDialog::ReadOnlyFilesDialog(const QList<IDocument *> &documents, QW
{
QStringList files;
foreach (IDocument *document, documents)
- files << document->filePath();
+ files << document->filePath().toString();
d->initDialog(files);
}
diff --git a/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp b/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
index 242af62ff60..52f1f631e49 100644
--- a/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
@@ -63,7 +63,7 @@ SaveItemsDialog::SaveItemsDialog(QWidget *parent,
foreach (IDocument *document, items) {
QString visibleName;
QString directory;
- QString fileName = document->filePath();
+ QString fileName = document->filePath().toString();
if (fileName.isEmpty()) {
visibleName = document->suggestedFileName();
} else {
diff --git a/src/plugins/coreplugin/dialogs/saveitemsdialog.h b/src/plugins/coreplugin/dialogs/saveitemsdialog.h
index 27239b7c8d1..03d57cbf512 100644
--- a/src/plugins/coreplugin/dialogs/saveitemsdialog.h
+++ b/src/plugins/coreplugin/dialogs/saveitemsdialog.h
@@ -54,13 +54,12 @@ class SaveItemsDialog : public QDialog
Q_OBJECT
public:
- SaveItemsDialog(QWidget *parent,
- QList<Core::IDocument *> items);
+ SaveItemsDialog(QWidget *parent, QList<IDocument *> items);
void setMessage(const QString &msg);
void setAlwaysSaveMessage(const QString &msg);
bool alwaysSaveChecked();
- QList<Core::IDocument *> itemsToSave() const;
+ QList<IDocument *> itemsToSave() const;
private slots:
void collectItemsToSave();
@@ -71,7 +70,7 @@ private:
void adjustButtonWidths();
Ui::SaveItemsDialog m_ui;
- QList<Core::IDocument*> m_itemsToSave;
+ QList<IDocument*> m_itemsToSave;
};
} // namespace Internal
diff --git a/src/plugins/coreplugin/dialogs/settingsdialog.cpp b/src/plugins/coreplugin/dialogs/settingsdialog.cpp
index b67a074fa12..80455ef1630 100644
--- a/src/plugins/coreplugin/dialogs/settingsdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/settingsdialog.cpp
@@ -293,9 +293,9 @@ bool optionsPageLessThan(const IOptionsPage *p1, const IOptionsPage *p2)
return p1->id().alphabeticallyBefore(p2->id());
}
-static inline QList<Core::IOptionsPage*> sortedOptionsPages()
+static inline QList<IOptionsPage*> sortedOptionsPages()
{
- QList<Core::IOptionsPage*> rc = ExtensionSystem::PluginManager::getObjects<IOptionsPage>();
+ QList<IOptionsPage*> rc = ExtensionSystem::PluginManager::getObjects<IOptionsPage>();
qStableSort(rc.begin(), rc.end(), optionsPageLessThan);
return rc;
}
diff --git a/src/plugins/coreplugin/dialogs/shortcutsettings.cpp b/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
index 2aa120085b6..9d9b3546cc7 100644
--- a/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
+++ b/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
@@ -49,19 +49,19 @@
Q_DECLARE_METATYPE(Core::Internal::ShortcutItem*)
-using namespace Core;
-using namespace Core::Internal;
+namespace Core {
+namespace Internal {
ShortcutSettings::ShortcutSettings(QObject *parent)
: CommandMappings(parent), m_initialized(false)
{
connect(ActionManager::instance(), SIGNAL(commandListChanged()), this, SLOT(initialize()));
- setId(Core::Constants::SETTINGS_ID_SHORTCUTS);
+ setId(Constants::SETTINGS_ID_SHORTCUTS);
setDisplayName(tr("Keyboard"));
- setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
- setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
- setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
+ setCategory(Constants::SETTINGS_CATEGORY_CORE);
+ setDisplayCategory(QCoreApplication::translate("Core", Constants::SETTINGS_TR_CATEGORY_CORE));
+ setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CORE_ICON));
}
QWidget *ShortcutSettings::widget()
@@ -411,3 +411,5 @@ void ShortcutSettings::markCollisions(ShortcutItem *item)
item->m_item->setForeground(2, hasCollision ? Qt::red : commandList()->palette().foreground());
}
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/dialogs/shortcutsettings.h b/src/plugins/coreplugin/dialogs/shortcutsettings.h
index 198dcb20e70..405aceafb4a 100644
--- a/src/plugins/coreplugin/dialogs/shortcutsettings.h
+++ b/src/plugins/coreplugin/dialogs/shortcutsettings.h
@@ -56,7 +56,7 @@ struct ShortcutItem
};
-class ShortcutSettings : public Core::CommandMappings
+class ShortcutSettings : public CommandMappings
{
Q_OBJECT
diff --git a/src/plugins/coreplugin/documentmanager.cpp b/src/plugins/coreplugin/documentmanager.cpp
index 7b52203241a..7a31b5bba52 100644
--- a/src/plugins/coreplugin/documentmanager.cpp
+++ b/src/plugins/coreplugin/documentmanager.cpp
@@ -44,6 +44,7 @@
#include <coreplugin/editormanager/ieditorfactory.h>
#include <coreplugin/editormanager/iexternaleditor.h>
+#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>
@@ -103,6 +104,8 @@ static const char projectDirectoryKeyC[] = "Projects";
static const char useProjectDirectoryKeyC[] = "UseProjectsDirectory";
static const char buildDirectoryKeyC[] = "BuildDirectory.Template";
+using namespace Utils;
+
namespace Core {
static void readSettings();
@@ -151,12 +154,11 @@ struct DocumentManagerPrivate
QList<DocumentManager::RecentFile> m_recentFiles;
static const int m_maxRecentFiles = 7;
- QString m_currentFile;
-
QFileSystemWatcher *m_fileWatcher; // Delayed creation.
QFileSystemWatcher *m_linkWatcher; // Delayed creation (only UNIX/if a link is seen).
bool m_blockActivated;
QString m_lastVisitedDirectory;
+ QString m_defaultLocationForNewFiles;
QString m_projectsDirectory;
bool m_useProjectsDirectory;
QString m_buildDirectory;
@@ -168,7 +170,7 @@ struct DocumentManagerPrivate
};
static DocumentManager *m_instance;
-static Internal::DocumentManagerPrivate *d;
+static DocumentManagerPrivate *d;
QFileSystemWatcher *DocumentManagerPrivate::fileWatcher()
{
@@ -182,7 +184,7 @@ QFileSystemWatcher *DocumentManagerPrivate::fileWatcher()
QFileSystemWatcher *DocumentManagerPrivate::linkWatcher()
{
- if (Utils::HostOsInfo::isAnyUnixHost()) {
+ if (HostOsInfo::isAnyUnixHost()) {
if (!m_linkWatcher) {
m_linkWatcher = new QFileSystemWatcher(m_instance);
m_linkWatcher->setObjectName(QLatin1String("_qt_autotest_force_engine_poller"));
@@ -265,8 +267,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->filePath(), DocumentManager::KeepLinks);
- const QString fixedResolvedName = DocumentManager::fixFileName(document->filePath(), DocumentManager::ResolveLinks);
+ const QString fixedName = DocumentManager::fixFileName(document->filePath().toString(), DocumentManager::KeepLinks);
+ const QString fixedResolvedName = DocumentManager::fixFileName(document->filePath().toString(), DocumentManager::ResolveLinks);
addFileInfo(fixedResolvedName, document, false);
if (fixedName != fixedResolvedName)
addFileInfo(fixedName, document, true);
@@ -285,7 +287,8 @@ 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(filePathChanged(QString,QString)), m_instance, SLOT(filePathChanged(QString,QString)));
+ connect(document, &IDocument::filePathChanged,
+ m_instance, &DocumentManager::filePathChanged);
d->m_documentsWithoutWatch.append(document);
}
}
@@ -296,7 +299,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(filePathChanged(QString,QString)), m_instance, SLOT(filePathChanged(QString,QString)));
+ connect(document, &IDocument::filePathChanged, m_instance, &DocumentManager::filePathChanged);
addFileInfo(document);
}
}
@@ -387,20 +390,20 @@ void DocumentManager::renamedFile(const QString &from, const QString &to)
foreach (IDocument *document, documentsToRename) {
d->m_blockedIDocument = document;
removeFileInfo(document);
- document->setFilePath(to);
+ document->setFilePath(FileName::fromString(to));
addFileInfo(document);
d->m_blockedIDocument = 0;
}
emit m_instance->allDocumentsRenamed(from, to);
}
-void DocumentManager::filePathChanged(const QString &oldName, const QString &newName)
+void DocumentManager::filePathChanged(const FileName &oldName, const FileName &newName)
{
IDocument *doc = qobject_cast<IDocument *>(sender());
QTC_ASSERT(doc, return);
if (doc == d->m_blockedIDocument)
return;
- emit m_instance->documentRenamed(doc, oldName, newName);
+ emit m_instance->documentRenamed(doc, oldName.toString(), newName.toString());
}
/*!
@@ -479,7 +482,7 @@ QString DocumentManager::fixFileName(const QString &fileName, FixMode fixmode)
s = QDir::cleanPath(s);
}
s = QDir::toNativeSeparators(s);
- if (Utils::HostOsInfo::fileNameCaseSensitivity() == Qt::CaseInsensitive)
+ if (HostOsInfo::fileNameCaseSensitivity() == Qt::CaseInsensitive)
s = s.toLower();
return s;
}
@@ -564,7 +567,7 @@ static bool saveModifiedFilesHelper(const QList<IDocument *> &documents,
foreach (IDocument *document, documents) {
if (document && document->isModified()) {
- QString name = document->filePath();
+ QString name = document->filePath().toString();
if (name.isEmpty())
name = document->suggestedFileName();
@@ -634,7 +637,7 @@ static bool saveModifiedFilesHelper(const QList<IDocument *> &documents,
bool DocumentManager::saveDocument(IDocument *document, const QString &fileName, bool *isReadOnly)
{
bool ret = true;
- QString effName = fileName.isEmpty() ? document->filePath() : fileName;
+ QString effName = fileName.isEmpty() ? document->filePath().toString() : 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
@@ -721,7 +724,7 @@ QString DocumentManager::getSaveAsFileName(const IDocument *document, const QStr
{
if (!document)
return QLatin1String("");
- QString absoluteFilePath = document->filePath();
+ QString absoluteFilePath = document->filePath().toString();
const QFileInfo fi(absoluteFilePath);
QString path;
QString fileName;
@@ -745,7 +748,7 @@ QString DocumentManager::getSaveAsFileName(const IDocument *document, const QStr
}
absoluteFilePath = getSaveFileName(tr("Save File As"),
- path + QDir::separator() + fileName,
+ path + QLatin1Char('/') + fileName,
filterString,
selectedFilter);
return absoluteFilePath;
@@ -876,8 +879,8 @@ QStringList DocumentManager::getOpenFileNames(const QString &filters,
{
QString path = pathIn;
if (path.isEmpty()) {
- if (!d->m_currentFile.isEmpty())
- path = QFileInfo(d->m_currentFile).absoluteFilePath();
+ if (EditorManager::currentDocument() && !EditorManager::currentDocument()->isTemporary())
+ path = EditorManager::currentDocument()->filePath().toString();
if (path.isEmpty() && useProjectsDirectory())
path = projectsDirectory();
}
@@ -921,8 +924,8 @@ void DocumentManager::checkForReload()
d->m_blockActivated = true;
IDocument::ReloadSetting defaultBehavior = EditorManagerPrivate::reloadSetting();
- Utils::ReloadPromptAnswer previousReloadAnswer = Utils::ReloadCurrent;
- Utils::FileDeletedPromptAnswer previousDeletedAnswer = Utils::FileDeletedSave;
+ ReloadPromptAnswer previousReloadAnswer = ReloadCurrent;
+ FileDeletedPromptAnswer previousDeletedAnswer = FileDeletedSave;
QList<IDocument *> documentsToClose;
QMap<IDocument*, QString> documentsToSave;
@@ -1055,26 +1058,26 @@ void DocumentManager::checkForReload()
// IDocument wants us to ask
} else if (type == IDocument::TypeContents) {
// content change, IDocument wants to ask user
- if (previousReloadAnswer == Utils::ReloadNone) {
+ if (previousReloadAnswer == ReloadNone) {
// answer already given, ignore
success = document->reload(&errorString, IDocument::FlagIgnore, IDocument::TypeContents);
- } else if (previousReloadAnswer == Utils::ReloadAll) {
+ } else if (previousReloadAnswer == ReloadAll) {
// answer already given, reload
success = document->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents);
} else {
// Ask about content change
- previousReloadAnswer = Utils::reloadPrompt(document->filePath(), document->isModified(),
+ previousReloadAnswer = reloadPrompt(document->filePath(), document->isModified(),
ICore::dialogParent());
switch (previousReloadAnswer) {
- case Utils::ReloadAll:
- case Utils::ReloadCurrent:
+ case ReloadAll:
+ case ReloadCurrent:
success = document->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents);
break;
- case Utils::ReloadSkipCurrent:
- case Utils::ReloadNone:
+ case ReloadSkipCurrent:
+ case ReloadNone:
success = document->reload(&errorString, IDocument::FlagIgnore, IDocument::TypeContents);
break;
- case Utils::CloseCurrent:
+ case CloseCurrent:
documentsToClose << document;
break;
}
@@ -1084,18 +1087,18 @@ void DocumentManager::checkForReload()
// Ask about removed file
bool unhandled = true;
while (unhandled) {
- if (previousDeletedAnswer != Utils::FileDeletedCloseAll) {
+ if (previousDeletedAnswer != FileDeletedCloseAll) {
previousDeletedAnswer =
- Utils::fileDeletedPrompt(document->filePath(),
+ fileDeletedPrompt(document->filePath().toString(),
trigger == IDocument::TriggerExternal,
QApplication::activeWindow());
}
switch (previousDeletedAnswer) {
- case Utils::FileDeletedSave:
- documentsToSave.insert(document, document->filePath());
+ case FileDeletedSave:
+ documentsToSave.insert(document, document->filePath().toString());
unhandled = false;
break;
- case Utils::FileDeletedSaveAs:
+ case FileDeletedSaveAs:
{
const QString &saveFileName = getSaveAsFileName(document);
if (!saveFileName.isEmpty()) {
@@ -1104,8 +1107,8 @@ void DocumentManager::checkForReload()
}
break;
}
- case Utils::FileDeletedClose:
- case Utils::FileDeletedCloseAll:
+ case FileDeletedClose:
+ case FileDeletedCloseAll:
documentsToClose << document;
unhandled = false;
break;
@@ -1115,7 +1118,7 @@ void DocumentManager::checkForReload()
}
if (!success) {
if (errorString.isEmpty())
- errorStrings << tr("Cannot reload %1").arg(QDir::toNativeSeparators(document->filePath()));
+ errorStrings << tr("Cannot reload %1").arg(document->filePath().toUserOutput());
else
errorStrings << errorString;
}
@@ -1189,7 +1192,7 @@ void DocumentManager::saveSettings()
recentEditorIds.append(file.second.toString());
}
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
s->beginGroup(QLatin1String(settingsGroupC));
s->setValue(QLatin1String(filesKeyC), recentFiles);
s->setValue(QLatin1String(editorsKeyC), recentEditorIds);
@@ -1203,7 +1206,7 @@ void DocumentManager::saveSettings()
void readSettings()
{
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
d->m_recentFiles.clear();
s->beginGroup(QLatin1String(settingsGroupC));
QStringList recentFiles = s->value(QLatin1String(filesKeyC)).toStringList();
@@ -1226,7 +1229,7 @@ void readSettings()
if (!settingsProjectDir.isEmpty() && QFileInfo(settingsProjectDir).isDir())
d->m_projectsDirectory = settingsProjectDir;
else
- d->m_projectsDirectory = Utils::PathChooser::homePath();
+ d->m_projectsDirectory = PathChooser::homePath();
d->m_useProjectsDirectory = s->value(QLatin1String(useProjectDirectoryKeyC),
d->m_useProjectsDirectory).toBool();
@@ -1242,45 +1245,40 @@ void readSettings()
/*!
- The current file is the file currently opened when an editor is active,
- or the selected file in case a Project Explorer is active.
+ Returns the initial directory for a new file dialog. If there is
+ a current file, uses that, otherwise if there is a default location for
+ new files, uses that, otherwise uses the last visited directory.
- \sa currentFile
- */
-void DocumentManager::setCurrentFile(const QString &filePath)
+ \sa setFileDialogLastVisitedDirectory
+ \sa setDefaultLocationForNewFiles
+*/
+
+QString DocumentManager::fileDialogInitialDirectory()
{
- if (d->m_currentFile == filePath)
- return;
- d->m_currentFile = filePath;
- emit m_instance->currentFileChanged(d->m_currentFile);
+ if (EditorManager::currentDocument() && !EditorManager::currentDocument()->isTemporary())
+ return QFileInfo(EditorManager::currentDocument()->filePath().toString()).absolutePath();
+ if (!d->m_defaultLocationForNewFiles.isEmpty())
+ return d->m_defaultLocationForNewFiles;
+ return d->m_lastVisitedDirectory;
}
/*!
- Returns the absolute path of the current file.
- The current file is the file currently opened when an editor is active,
- or the selected file in case a Project Explorer is active.
+ Sets the default location for new files
- \sa setCurrentFile
- */
-QString DocumentManager::currentFile()
+ \sa fileDialogInitialDirectory
+*/
+QString DocumentManager::defaultLocationForNewFiles()
{
- return d->m_currentFile;
+ return d->m_defaultLocationForNewFiles;
}
/*!
-
- Returns the initial directory for a new file dialog. If there is
- a current file, uses that, otherwise uses the last visited directory.
-
- \sa setFileDialogLastVisitedDirectory
-*/
-
-QString DocumentManager::fileDialogInitialDirectory()
+ Returns the default location for new files
+ */
+void DocumentManager::setDefaultLocationForNewFiles(const QString &location)
{
- if (!d->m_currentFile.isEmpty())
- return QFileInfo(d->m_currentFile).absolutePath();
- return d->m_lastVisitedDirectory;
+ d->m_defaultLocationForNewFiles = location;
}
/*!
@@ -1429,11 +1427,11 @@ void DocumentManager::executeOpenWithMenuAction(QAction *action)
if (entry.editorFactory) {
// close any open editors that have this file open
// remember the views to open new editors in there
- QList<Internal::EditorView *> views;
+ QList<EditorView *> views;
QList<IEditor *> editorsOpenForFile
= DocumentModel::editorsForFilePath(entry.fileName);
foreach (IEditor *openEditor, editorsOpenForFile) {
- Internal::EditorView *view = EditorManagerPrivate::viewForEditor(openEditor);
+ EditorView *view = EditorManagerPrivate::viewForEditor(openEditor);
if (view && view->currentEditor() == openEditor) // visible
views.append(view);
}
@@ -1443,12 +1441,12 @@ void DocumentManager::executeOpenWithMenuAction(QAction *action)
if (views.isEmpty()) {
EditorManager::openEditor(entry.fileName, entry.editorFactory->id());
} else {
- if (Internal::EditorView *currentView = EditorManagerPrivate::currentEditorView()) {
+ if (EditorView *currentView = EditorManagerPrivate::currentEditorView()) {
if (views.removeOne(currentView))
views.prepend(currentView); // open editor in current view first
}
EditorManager::OpenEditorFlags flags;
- foreach (Internal::EditorView *view, views) {
+ foreach (EditorView *view, views) {
IEditor *editor =
EditorManagerPrivate::openEditor(view, entry.fileName,
entry.editorFactory->id(), flags);
diff --git a/src/plugins/coreplugin/documentmanager.h b/src/plugins/coreplugin/documentmanager.h
index 7c668954165..010489b6207 100644
--- a/src/plugins/coreplugin/documentmanager.h
+++ b/src/plugins/coreplugin/documentmanager.h
@@ -43,6 +43,8 @@ class QMainWindow;
class QMenu;
QT_END_NAMESPACE
+namespace Utils { class FileName; }
+
namespace Core {
class IContext;
@@ -81,10 +83,6 @@ public:
static void saveSettings();
- // current file
- static void setCurrentFile(const QString &filePath);
- static QString currentFile();
-
// helper functions
static QString fixFileName(const QString &fileName, FixMode fixmode);
@@ -127,6 +125,9 @@ public:
static QString fileDialogInitialDirectory();
+ static QString defaultLocationForNewFiles();
+ static void setDefaultLocationForNewFiles(const QString &location);
+
static bool useProjectsDirectory();
static void setUseProjectsDirectory(bool);
@@ -146,7 +147,6 @@ public slots:
static void executeOpenWithMenuAction(QAction *action);
signals:
- void currentFileChanged(const QString &filePath);
/* Used to notify e.g. the code model to update the given files. Does *not*
lead to any editors to reload or any other editor manager actions. */
void filesChangedInternally(const QStringList &files);
@@ -160,7 +160,6 @@ protected:
private slots:
void documentDestroyed(QObject *obj);
- void filePathChanged(const QString &oldName, const QString &newName);
void checkForNewFileName();
void checkForReload();
void changedFile(const QString &file);
@@ -169,6 +168,8 @@ private:
explicit DocumentManager(QObject *parent);
~DocumentManager();
+ void filePathChanged(const Utils::FileName &oldName, const Utils::FileName &newName);
+
friend class Core::Internal::MainWindow;
};
diff --git a/src/plugins/coreplugin/editmode.cpp b/src/plugins/coreplugin/editmode.cpp
index b8a0239ead8..33733c4bb5e 100644
--- a/src/plugins/coreplugin/editmode.cpp
+++ b/src/plugins/coreplugin/editmode.cpp
@@ -44,8 +44,8 @@
#include <QWidget>
#include <QIcon>
-using namespace Core;
-using namespace Core::Internal;
+namespace Core {
+namespace Internal {
EditMode::EditMode() :
m_splitter(new MiniSplitter),
@@ -73,7 +73,7 @@ EditMode::EditMode() :
MiniSplitter *splitter = new MiniSplitter;
splitter->setOrientation(Qt::Vertical);
splitter->insertWidget(0, rightPaneSplitter);
- QWidget *outputPane = new Core::OutputPanePlaceHolder(this, splitter);
+ QWidget *outputPane = new OutputPanePlaceHolder(this, splitter);
outputPane->setObjectName(QLatin1String("EditModeOutputPanePlaceHolder"));
splitter->insertWidget(1, outputPane);
splitter->setStretchFactor(0, 3);
@@ -84,8 +84,8 @@ EditMode::EditMode() :
m_splitter->setStretchFactor(0, 0);
m_splitter->setStretchFactor(1, 1);
- connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
- this, SLOT(grabEditorManager(Core::IMode*)));
+ connect(ModeManager::instance(), &ModeManager::currentModeChanged,
+ this, &EditMode::grabEditorManager);
m_splitter->setFocusProxy(editorPlaceHolder);
IContext *modeContextObject = new IContext(this);
@@ -103,7 +103,7 @@ EditMode::~EditMode()
delete m_splitter;
}
-void EditMode::grabEditorManager(Core::IMode *mode)
+void EditMode::grabEditorManager(IMode *mode)
{
if (mode != this)
return;
@@ -111,3 +111,6 @@ void EditMode::grabEditorManager(Core::IMode *mode)
if (EditorManager::currentEditor())
EditorManager::currentEditor()->widget()->setFocus();
}
+
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/editmode.h b/src/plugins/coreplugin/editmode.h
index 3aaa0d52f8d..d8b538ce12f 100644
--- a/src/plugins/coreplugin/editmode.h
+++ b/src/plugins/coreplugin/editmode.h
@@ -44,7 +44,7 @@ class EditorManager;
namespace Internal {
-class EditMode : public Core::IMode
+class EditMode : public IMode
{
Q_OBJECT
@@ -52,10 +52,9 @@ public:
EditMode();
~EditMode();
-private slots:
- void grabEditorManager(Core::IMode *mode);
-
private:
+ void grabEditorManager(IMode *mode);
+
QSplitter *m_splitter;
QVBoxLayout *m_rightSplitWidgetLayout;
};
diff --git a/src/plugins/coreplugin/editormanager/documentmodel.cpp b/src/plugins/coreplugin/editormanager/documentmodel.cpp
index c220c892e1f..625f7aba84d 100644
--- a/src/plugins/coreplugin/editormanager/documentmodel.cpp
+++ b/src/plugins/coreplugin/editormanager/documentmodel.cpp
@@ -130,7 +130,7 @@ QAbstractItemModel *DocumentModel::model()
QString DocumentModel::Entry::fileName() const
{
- return document ? document->filePath() : m_fileName;
+ return document ? document->filePath().toString() : m_fileName;
}
QString DocumentModel::Entry::displayName() const
@@ -224,10 +224,10 @@ int DocumentModelPrivate::indexOfFilePath(const QString &filePath) const
{
if (filePath.isEmpty())
return -1;
- const QString fixedPath = DocumentManager::fixFileName(filePath, DocumentManager::KeepLinks);
+ const QString fixedPath = DocumentManager::fixFileName(filePath, DocumentManager::ResolveLinks);
return Utils::indexOf(m_entries, [&fixedPath](DocumentModel::Entry *entry) {
return DocumentManager::fixFileName(entry->fileName(),
- DocumentManager::KeepLinks) == fixedPath;
+ DocumentManager::ResolveLinks) == fixedPath;
});
}
@@ -400,13 +400,10 @@ QVariant DocumentModelPrivate::data(const QModelIndex &index, int role) const
case Qt::DecorationRole:
{
bool showLock = false;
- if (e->document) {
- showLock = e->document->filePath().isEmpty()
- ? false
- : e->document->isFileReadOnly();
- } else {
+ if (e->document)
+ showLock = e->document->filePath().isEmpty() ? false : e->document->isFileReadOnly();
+ else
showLock = !QFileInfo(e->m_fileName).isWritable();
- }
return showLock ? m_lockedIcon : QIcon();
}
case Qt::ToolTipRole:
diff --git a/src/plugins/coreplugin/editormanager/editormanager.cpp b/src/plugins/coreplugin/editormanager/editormanager.cpp
index e7438e00546..b31b2a71102 100644
--- a/src/plugins/coreplugin/editormanager/editormanager.cpp
+++ b/src/plugins/coreplugin/editormanager/editormanager.cpp
@@ -51,6 +51,7 @@
#include <coreplugin/findplaceholder.h>
#include <coreplugin/icore.h>
#include <coreplugin/icorelistener.h>
+#include <coreplugin/imode.h>
#include <coreplugin/infobar.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/mimedatabase.h>
@@ -127,14 +128,14 @@ using namespace Utils;
//===================EditorManager=====================
-EditorManagerPlaceHolder::EditorManagerPlaceHolder(Core::IMode *mode, QWidget *parent)
+EditorManagerPlaceHolder::EditorManagerPlaceHolder(IMode *mode, QWidget *parent)
: QWidget(parent), m_mode(mode)
{
setLayout(new QVBoxLayout);
layout()->setMargin(0);
setFocusProxy(EditorManagerPrivate::mainEditorArea());
- connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
- this, SLOT(currentModeChanged(Core::IMode*)));
+ connect(ModeManager::instance(), &ModeManager::currentModeChanged,
+ this, &EditorManagerPlaceHolder::currentModeChanged);
currentModeChanged(ModeManager::currentMode());
}
@@ -149,7 +150,7 @@ EditorManagerPlaceHolder::~EditorManagerPlaceHolder()
}
}
-void EditorManagerPlaceHolder::currentModeChanged(Core::IMode *mode)
+void EditorManagerPlaceHolder::currentModeChanged(IMode *mode)
{
if (m_mode == mode) {
QWidget *previousFocus = 0;
@@ -216,7 +217,7 @@ static void setFocusToEditorViewAndUnmaximizePanes(EditorView *view)
/* For something that has a 'QString id' (IEditorFactory
* or IExternalEditor), find the one matching a id. */
template <class EditorFactoryLike>
-EditorFactoryLike *findById(Core::Id id)
+EditorFactoryLike *findById(Id id)
{
return ExtensionSystem::PluginManager::getObject<EditorFactoryLike>(
[&id](EditorFactoryLike *efl) {
@@ -238,8 +239,9 @@ EditorManagerPrivate::EditorManagerPrivate(QObject *parent) :
m_gotoPreviousDocHistoryAction(new QAction(EditorManager::tr("Previous Open Document in History"), this)),
m_goBackAction(new QAction(QIcon(QLatin1String(Constants::ICON_PREV)), EditorManager::tr("Go Back"), this)),
m_goForwardAction(new QAction(QIcon(QLatin1String(Constants::ICON_NEXT)), EditorManager::tr("Go Forward"), this)),
- m_copyFilePathContextAction(new QAction(EditorManager::tr("Copy Full Path to Clipboard"), this)),
- m_copyFileNameContextAction(new QAction(EditorManager::tr("Copy File Name to Clipboard"), this)),
+ m_copyFilePathContextAction(new QAction(EditorManager::tr("Copy Full Path"), this)),
+ m_copyLocationContextAction(new QAction(EditorManager::tr("Copy Path and Line Number"), this)),
+ m_copyFileNameContextAction(new QAction(EditorManager::tr("Copy File Name"), this)),
m_saveCurrentEditorContextAction(new QAction(EditorManager::tr("&Save"), this)),
m_saveAsCurrentEditorContextAction(new QAction(EditorManager::tr("Save &As..."), this)),
m_revertToSavedCurrentEditorContextAction(new QAction(EditorManager::tr("Revert to Saved"), this)),
@@ -285,8 +287,8 @@ EditorManagerPrivate::~EditorManagerPrivate()
void EditorManagerPrivate::init()
{
DocumentModel::init();
- connect(ICore::instance(), SIGNAL(contextAboutToChange(QList<Core::IContext*>)),
- this, SLOT(handleContextChange(QList<Core::IContext*>)));
+ connect(ICore::instance(), &ICore::contextAboutToChange,
+ this, &EditorManagerPrivate::handleContextChange);
const Context editManagerContext(Constants::C_EDITORMANAGER);
// combined context for edit & design modes
@@ -321,13 +323,13 @@ void EditorManagerPrivate::init()
// Close Action
cmd = ActionManager::registerAction(m_closeCurrentEditorAction, Constants::CLOSE, editManagerContext, true);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+W")));
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(m_closeCurrentEditorAction->text());
mfile->addAction(cmd, Constants::G_FILE_CLOSE);
connect(m_closeCurrentEditorAction, SIGNAL(triggered()),
m_instance, SLOT(slotCloseCurrentEditorOrDocument()));
- if (Utils::HostOsInfo::isWindowsHost()) {
+ if (HostOsInfo::isWindowsHost()) {
// workaround for QTCREATORBUG-72
QAction *action = new QAction(tr("Alternative Close"), this);
cmd = ActionManager::registerAction(action, Constants::CLOSE_ALTERNATIVE, editManagerContext);
@@ -345,7 +347,7 @@ void EditorManagerPrivate::init()
// Close All Others Action
cmd = ActionManager::registerAction(m_closeOtherDocumentsAction, Constants::CLOSEOTHERS, editManagerContext, true);
mfile->addAction(cmd, Constants::G_FILE_CLOSE);
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd->setAttribute(Command::CA_UpdateText);
connect(m_closeOtherDocumentsAction, SIGNAL(triggered()), m_instance, SLOT(closeOtherDocuments()));
// Close All Others Except Visible Action
@@ -357,6 +359,8 @@ void EditorManagerPrivate::init()
//Save XXX Context Actions
connect(m_copyFilePathContextAction, SIGNAL(triggered()),
this, SLOT(copyFilePathFromContextMenu()));
+ connect(m_copyLocationContextAction, SIGNAL(triggered()),
+ this, SLOT(copyLocationFromContextMenu()));
connect(m_copyFileNameContextAction, SIGNAL(triggered()),
this, SLOT(copyFileNameFromContextMenu()));
connect(m_saveCurrentEditorContextAction, SIGNAL(triggered()),
@@ -488,7 +492,7 @@ void EditorManagerPrivate::init()
globalMacroExpander()->registerFileVariables(kCurrentDocumentPrefix, tr("Current document"),
[]() -> QString {
IDocument *document = EditorManager::currentDocument();
- return document ? document->filePath() : QString();
+ return document ? document->filePath().toString() : QString();
});
globalMacroExpander()->registerIntVariable(kCurrentDocumentXPos,
@@ -506,6 +510,11 @@ void EditorManagerPrivate::init()
});
}
+EditorManagerPrivate *EditorManagerPrivate::instance()
+{
+ return d;
+}
+
EditorArea *EditorManagerPrivate::mainEditorArea()
{
return d->m_editorAreas.at(0);
@@ -587,7 +596,7 @@ IEditor *EditorManagerPrivate::openEditorAt(EditorView *view, const QString &fil
EditorManager::cutForwardNavigationHistory();
EditorManager::addCurrentPositionToNavigationHistory();
EditorManager::OpenEditorFlags tempFlags = flags | EditorManager::IgnoreNavigationHistory;
- Core::IEditor *editor = openEditor(view, fileName, editorId, tempFlags, newEditor);
+ IEditor *editor = openEditor(view, fileName, editorId, tempFlags, newEditor);
if (editor && line != -1)
editor->gotoLine(line, column);
return editor;
@@ -926,7 +935,7 @@ void EditorManagerPrivate::addEditor(IEditor *editor)
const bool addWatcher = !isTemporary;
DocumentManager::addDocument(editor->document(), addWatcher);
if (!isTemporary)
- DocumentManager::addToRecentFiles(editor->document()->filePath(),
+ DocumentManager::addToRecentFiles(editor->document()->filePath().toString(),
editor->document()->id());
}
emit m_instance->editorOpened(editor);
@@ -984,7 +993,7 @@ IEditor *EditorManagerPrivate::duplicateEditor(IEditor *editor)
IEditor *duplicate = editor->duplicate();
duplicate->restoreState(editor->saveState());
- emit m_instance->editorCreated(duplicate, duplicate->document()->filePath());
+ emit m_instance->editorCreated(duplicate, duplicate->document()->filePath().toString());
addEditor(duplicate);
return duplicate;
}
@@ -1007,14 +1016,14 @@ IEditor *EditorManagerPrivate::activateEditor(EditorView *view, IEditor *editor,
if (!(flags & EditorManager::DoNotMakeVisible)) {
// switch to design mode?
if (!(flags & EditorManager::DoNotSwitchToDesignMode) && editor->isDesignModePreferred()) {
- ModeManager::activateMode(Core::Constants::MODE_DESIGN);
+ ModeManager::activateMode(Constants::MODE_DESIGN);
ModeManager::setFocusToCurrentMode();
} else {
int index;
findEditorArea(view, &index);
if (index == 0) // main window --> we might need to switch mode
if (!editor->widget()->isVisible())
- ModeManager::activateMode(Core::Constants::MODE_EDIT);
+ ModeManager::activateMode(Constants::MODE_EDIT);
editor->widget()->setFocus();
ICore::raiseWindow(editor->widget());
}
@@ -1061,19 +1070,22 @@ void EditorManagerPrivate::closeEditorOrDocument(IEditor *editor)
void EditorManagerPrivate::activateView(EditorView *view)
{
QTC_ASSERT(view, return);
+ QWidget *focusWidget;
if (IEditor *editor = view->currentEditor()) {
setCurrentEditor(editor, true);
- editor->widget()->setFocus();
- ICore::raiseWindow(editor->widget());
+ focusWidget = editor->widget();
} else {
setCurrentView(view);
+ focusWidget = view;
}
+ focusWidget->setFocus();
+ ICore::raiseWindow(focusWidget);
}
void EditorManagerPrivate::restoreEditorState(IEditor *editor)
{
QTC_ASSERT(editor, return);
- QString fileName = editor->document()->filePath();
+ QString fileName = editor->document()->filePath().toString();
editor->restoreState(d->m_editorStates.value(fileName).toByteArray());
}
@@ -1125,11 +1137,6 @@ void EditorManagerPrivate::setCurrentView(EditorView *view)
old->update();
if (view)
view->update();
-
- if (view && !view->currentEditor()) {
- view->setFocus();
- ICore::raiseWindow(view);
- }
}
EditorArea *EditorManagerPrivate::findEditorArea(const EditorView *view, int *areaIndex)
@@ -1167,12 +1174,8 @@ void EditorManagerPrivate::closeView(EditorView *view)
splitter->unsplit();
EditorView *newCurrent = splitter->findFirstView();
- if (newCurrent) {
- if (IEditor *e = newCurrent->currentEditor())
- EditorManagerPrivate::activateEditor(newCurrent, e);
- else
- EditorManagerPrivate::setCurrentView(newCurrent);
- }
+ if (newCurrent)
+ EditorManagerPrivate::activateView(newCurrent);
}
void EditorManagerPrivate::emptyView(EditorView *view)
@@ -1249,7 +1252,7 @@ void EditorManagerPrivate::addDocumentToRecentFiles(IDocument *document)
DocumentModel::Entry *entry = DocumentModel::entryForDocument(document);
if (!entry)
return;
- DocumentManager::addToRecentFiles(document->filePath(), entry->id());
+ DocumentManager::addToRecentFiles(document->filePath().toString(), entry->id());
}
void EditorManagerPrivate::updateAutoSave()
@@ -1271,9 +1274,9 @@ void EditorManagerPrivate::updateMakeWritableWarning()
// 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(document->filePath()).absolutePath();
+ const QString directory = document->filePath().toFileInfo().absolutePath();
IVersionControl *versionControl = VcsManager::findVersionControlForDirectory(directory);
- if (versionControl && versionControl->openSupportMode(document->filePath()) != IVersionControl::NoOpen) {
+ if (versionControl && versionControl->openSupportMode(document->filePath().toString()) != IVersionControl::NoOpen) {
if (versionControl->settingsFlags() & IVersionControl::AutoOpen) {
vcsOpenCurrentEditor();
ww = false;
@@ -1364,7 +1367,7 @@ void EditorManagerPrivate::updateWindowTitleForDocument(IDocument *document, QWi
QString windowTitle;
const QString dashSep = QLatin1String(" - ");
- QString filePath = document ? QFileInfo(document->filePath()).absoluteFilePath()
+ QString filePath = document ? document->filePath().toFileInfo().absoluteFilePath()
: QString();
const QString windowTitleAddition = d->m_titleAdditionHandler
@@ -1463,18 +1466,31 @@ void EditorManagerPrivate::makeCurrentEditorWritable()
makeFileWritable(doc);
}
+void EditorManagerPrivate::setPlaceholderText(const QString &text)
+{
+ if (d->m_placeholderText == text)
+ return;
+ d->m_placeholderText = text;
+ emit d->placeholderTextChanged(d->m_placeholderText);
+}
+
+QString EditorManagerPrivate::placeholderText()
+{
+ return d->m_placeholderText;
+}
+
void EditorManagerPrivate::vcsOpenCurrentEditor()
{
IDocument *document = EditorManager::currentDocument();
if (!document)
return;
- const QString directory = QFileInfo(document->filePath()).absolutePath();
+ const QString directory = document->filePath().toFileInfo().absolutePath();
IVersionControl *versionControl = VcsManager::findVersionControlForDirectory(directory);
- if (!versionControl || versionControl->openSupportMode(document->filePath()) == IVersionControl::NoOpen)
+ if (!versionControl || versionControl->openSupportMode(document->filePath().toString()) == IVersionControl::NoOpen)
return;
- if (!versionControl->vcsOpen(document->filePath())) {
+ if (!versionControl->vcsOpen(document->filePath().toString())) {
// TODO: wrong dialog parent
QMessageBox::warning(ICore::mainWindow(), tr("Cannot Open File"),
tr("Cannot open the file for editing with VCS."));
@@ -1530,10 +1546,7 @@ void EditorManagerPrivate::editorAreaDestroyed(QObject *area)
EditorView *focusView = focusSplitterOrView->findFirstView(); // can be just focusSplitterOrView
QTC_ASSERT(focusView, focusView = newActiveArea->findFirstView());
QTC_ASSERT(focusView, return);
- if (focusView->currentEditor())
- setCurrentEditor(focusView->currentEditor());
- else
- setCurrentView(focusView);
+ EditorManagerPrivate::activateView(focusView);
}
void EditorManagerPrivate::autoSave()
@@ -1546,7 +1559,7 @@ void EditorManagerPrivate::autoSave()
if (document->filePath().isEmpty()) // FIXME: save them to a dedicated directory
continue;
QString errorString;
- if (!document->autoSave(&errorString, autoSaveName(document->filePath())))
+ if (!document->autoSave(&errorString, autoSaveName(document->filePath().toString())))
errors << errorString;
}
if (!errors.isEmpty())
@@ -1572,8 +1585,6 @@ void EditorManagerPrivate::handleContextChange(const QList<IContext *> &context)
d->m_scheduledCurrentEditor = editor;
QTimer::singleShot(0, d, SLOT(setCurrentEditorFromContextChange()));
} else {
- if (editor && !editor->document()->isTemporary())
- DocumentManager::setCurrentFile(editor->document()->filePath());
updateActions();
}
}
@@ -1582,15 +1593,26 @@ void EditorManagerPrivate::copyFilePathFromContextMenu()
{
if (!d->m_contextMenuEntry)
return;
- QApplication::clipboard()->setText(Utils::FileName::fromString(
+ QApplication::clipboard()->setText(FileName::fromString(
d->m_contextMenuEntry->fileName()).toUserOutput());
}
+void EditorManagerPrivate::copyLocationFromContextMenu()
+{
+ const QAction *action = qobject_cast<const QAction *>(sender());
+ if (!d->m_contextMenuEntry || !action)
+ return;
+ const QString text =
+ FileName::fromString(d->m_contextMenuEntry->fileName()).toUserOutput()
+ + QLatin1Char(':') + action->data().toString();
+ QApplication::clipboard()->setText(text);
+}
+
void EditorManagerPrivate::copyFileNameFromContextMenu()
{
if (!d->m_contextMenuEntry)
return;
- QApplication::clipboard()->setText(QFileInfo(d->m_contextMenuEntry->fileName()).fileName());
+ QApplication::clipboard()->setText(FileName::fromString(d->m_contextMenuEntry->fileName()).fileName());
}
void EditorManagerPrivate::saveDocumentFromContextMenu()
@@ -1638,7 +1660,7 @@ bool EditorManagerPrivate::saveDocument(IDocument *document)
document->checkPermissions();
- const QString &fileName = document->filePath();
+ const QString &fileName = document->filePath().toString();
if (fileName.isEmpty())
return saveDocumentAs(document);
@@ -1674,7 +1696,7 @@ bool EditorManagerPrivate::saveDocumentAs(IDocument *document)
const QString filter = MimeDatabase::allFiltersString();
QString selectedFilter =
- MimeDatabase::findByFile(QFileInfo(document->filePath())).filterString();
+ MimeDatabase::findByFile(document->filePath().toFileInfo()).filterString();
if (selectedFilter.isEmpty())
selectedFilter = MimeDatabase::findByType(document->mimeType()).filterString();
const QString &absoluteFilePath =
@@ -1683,7 +1705,7 @@ bool EditorManagerPrivate::saveDocumentAs(IDocument *document)
if (absoluteFilePath.isEmpty())
return false;
- if (absoluteFilePath != document->filePath()) {
+ if (absoluteFilePath != document->filePath().toString()) {
// close existing editors for the new file name
IDocument *otherDocument = DocumentModel::documentForFilePath(absoluteFilePath);
if (otherDocument)
@@ -1719,7 +1741,7 @@ void EditorManagerPrivate::revertToSaved(IDocument *document)
{
if (!document)
return;
- const QString fileName = document->filePath();
+ const QString fileName = document->filePath().toString();
if (fileName.isEmpty())
return;
if (document->isModified()) {
@@ -1744,14 +1766,14 @@ void EditorManagerPrivate::showInGraphicalShell()
{
if (!d->m_contextMenuEntry || d->m_contextMenuEntry->fileName().isEmpty())
return;
- Core::FileUtils::showInGraphicalShell(ICore::mainWindow(), d->m_contextMenuEntry->fileName());
+ FileUtils::showInGraphicalShell(ICore::mainWindow(), d->m_contextMenuEntry->fileName());
}
void EditorManagerPrivate::openTerminal()
{
if (!d->m_contextMenuEntry || d->m_contextMenuEntry->fileName().isEmpty())
return;
- Core::FileUtils::openTerminal(QFileInfo(d->m_contextMenuEntry->fileName()).path());
+ FileUtils::openTerminal(QFileInfo(d->m_contextMenuEntry->fileName()).path());
}
void EditorManagerPrivate::findInDirectory()
@@ -1808,9 +1830,6 @@ void EditorManagerPrivate::setCurrentEditorFromContextChange()
IEditor *newCurrent = d->m_scheduledCurrentEditor;
d->m_scheduledCurrentEditor = 0;
setCurrentEditor(newCurrent);
- if (!newCurrent->document()->isTemporary())
- DocumentManager::setCurrentFile(newCurrent->document()->filePath());
-
}
EditorView *EditorManagerPrivate::currentEditorView()
@@ -1911,8 +1930,15 @@ void EditorManager::addSaveAndCloseEditorActions(QMenu *contextMenu, DocumentMod
const QString filePath = entry ? entry->fileName() : QString();
const bool copyActionsEnabled = !filePath.isEmpty();
d->m_copyFilePathContextAction->setEnabled(copyActionsEnabled);
+ d->m_copyLocationContextAction->setEnabled(copyActionsEnabled);
d->m_copyFileNameContextAction->setEnabled(copyActionsEnabled);
contextMenu->addAction(d->m_copyFilePathContextAction);
+ if (editor && entry) {
+ if (const int lineNumber = editor->currentLine()) {
+ d->m_copyLocationContextAction->setData(QVariant(lineNumber));
+ contextMenu->addAction(d->m_copyLocationContextAction);
+ }
+ }
contextMenu->addAction(d->m_copyFileNameContextAction);
contextMenu->addSeparator();
@@ -1985,7 +2011,7 @@ void EditorManager::revertToSaved()
EditorManagerPrivate::revertToSaved(currentDocument());
}
-void EditorManager::closeEditor(Core::IEditor *editor, bool askAboutModifiedEditors)
+void EditorManager::closeEditor(IEditor *editor, bool askAboutModifiedEditors)
{
if (!editor)
return;
@@ -2066,6 +2092,7 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
return false;
QList<EditorView*> closedViews;
+ EditorView *focusView = 0;
// remove the editors
foreach (IEditor *editor, acceptedEditors) {
@@ -2074,11 +2101,13 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
&& !editor->document()->isTemporary()) {
QByteArray state = editor->saveState();
if (!state.isEmpty())
- d->m_editorStates.insert(editor->document()->filePath(), QVariant(state));
+ d->m_editorStates.insert(editor->document()->filePath().toString(), QVariant(state));
}
EditorManagerPrivate::removeEditor(editor);
if (EditorView *view = EditorManagerPrivate::viewForEditor(editor)) {
+ if (qApp->focusWidget() && qApp->focusWidget() == editor->widget()->focusWidget())
+ focusView = view;
if (editor == view->currentEditor())
closedViews += view;
if (d->m_currentEditor == editor) {
@@ -2100,29 +2129,23 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
else
forceViewToShowEditor = closedViews.first();
}
- bool currentViewHandled = false;
foreach (EditorView *view, closedViews) {
- OpenEditorFlags flags;
- if (view == currentView)
- currentViewHandled = true;
- else
- flags = OpenEditorFlags(DoNotChangeCurrentEditor);
IEditor *newCurrent = view->currentEditor();
if (!newCurrent && forceViewToShowEditor == view)
newCurrent = EditorManagerPrivate::pickUnusedEditor();
if (newCurrent) {
- EditorManagerPrivate::activateEditor(view, newCurrent, flags);
+ EditorManagerPrivate::activateEditor(view, newCurrent, DoNotChangeCurrentEditor);
} else if (forceViewToShowEditor == view) {
DocumentModel::Entry *entry = DocumentModel::firstRestoredEntry();
if (entry) {
- EditorManagerPrivate::activateEditorForEntry(view, entry, flags);
- } else {
- // no "restored" ones, so any entry left should have a document
+ EditorManagerPrivate::activateEditorForEntry(view, entry, DoNotChangeCurrentEditor);
+ } else { // no "restored" ones, so any entry left should have a document
const QList<DocumentModel::Entry *> documents = DocumentModel::entries();
if (!documents.isEmpty()) {
- IDocument *document = documents.last()->document;
- if (document)
- EditorManagerPrivate::activateEditorForDocument(view, document, flags);
+ if (IDocument *document = documents.last()->document) {
+ EditorManagerPrivate::activateEditorForDocument(
+ view, document, DoNotChangeCurrentEditor);
+ }
}
}
}
@@ -2133,12 +2156,10 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
foreach (IEditor *editor, acceptedEditors)
delete editor;
- if (currentView && !currentViewHandled) {
- if (IEditor *editor = currentView->currentEditor())
- EditorManagerPrivate::activateEditor(currentView, editor);
- else
- EditorManagerPrivate::setCurrentView(currentView);
- }
+ if (focusView)
+ EditorManagerPrivate::activateView(focusView);
+ else
+ EditorManagerPrivate::setCurrentEditor(currentView->currentEditor());
if (!currentEditor()) {
emit m_instance->currentEditorChanged(0);
@@ -2154,7 +2175,7 @@ void EditorManager::activateEditorForEntry(DocumentModel::Entry *entry, OpenEdit
entry, flags);
}
-void EditorManager::activateEditor(Core::IEditor *editor, OpenEditorFlags flags)
+void EditorManager::activateEditor(IEditor *editor, OpenEditorFlags flags)
{
QTC_ASSERT(editor, return);
EditorView *view = EditorManagerPrivate::viewForEditor(editor);
@@ -2272,7 +2293,7 @@ bool EditorManager::isAutoSaveFile(const QString &fileName)
return fileName.endsWith(QLatin1String(".autosave"));
}
-bool EditorManager::openExternalEditor(const QString &fileName, Core::Id editorId)
+bool EditorManager::openExternalEditor(const QString &fileName, Id editorId)
{
IExternalEditor *ee = findById<IExternalEditor>(editorId);
if (!ee)
@@ -2446,7 +2467,7 @@ QByteArray EditorManager::saveState()
IEditor *editor = DocumentModel::editorsForDocument(document).first();
QByteArray state = editor->saveState();
if (!state.isEmpty())
- d->m_editorStates.insert(document->filePath(), QVariant(state));
+ d->m_editorStates.insert(document->filePath().toString(), QVariant(state));
}
}
@@ -2499,7 +2520,7 @@ bool EditorManager::restoreState(const QByteArray &state)
stream >> fileName;
QString displayName;
stream >> displayName;
- Core::Id id;
+ Id id;
stream >> id;
if (!fileName.isEmpty() && !displayName.isEmpty()) {
@@ -2550,7 +2571,7 @@ void EditorManager::hideEditorStatusBar(const QString &id)
QTextCodec *EditorManager::defaultTextCodec()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
if (QTextCodec *candidate = QTextCodec::codecForName(
settings->value(QLatin1String(Constants::SETTINGS_DEFAULTTEXTENCODING)).toByteArray()))
return candidate;
diff --git a/src/plugins/coreplugin/editormanager/editormanager.h b/src/plugins/coreplugin/editormanager/editormanager.h
index 1608189cd74..1e63748e3aa 100644
--- a/src/plugins/coreplugin/editormanager/editormanager.h
+++ b/src/plugins/coreplugin/editormanager/editormanager.h
@@ -81,12 +81,13 @@ class CORE_EXPORT EditorManagerPlaceHolder : public QWidget
{
Q_OBJECT
public:
- explicit EditorManagerPlaceHolder(Core::IMode *mode, QWidget *parent = 0);
+ explicit EditorManagerPlaceHolder(IMode *mode, QWidget *parent = 0);
~EditorManagerPlaceHolder();
-private slots:
- void currentModeChanged(Core::IMode *);
+
private:
- Core::IMode *m_mode;
+ void currentModeChanged(IMode *);
+
+ IMode *m_mode;
};
class CORE_EXPORT EditorManager : public QObject
diff --git a/src/plugins/coreplugin/editormanager/editormanager_p.h b/src/plugins/coreplugin/editormanager/editormanager_p.h
index 8300656cb8e..a6411645320 100644
--- a/src/plugins/coreplugin/editormanager/editormanager_p.h
+++ b/src/plugins/coreplugin/editormanager/editormanager_p.h
@@ -68,6 +68,8 @@ class EditorManagerPrivate : public QObject
friend class Core::EditorManager;
public:
+ static EditorManagerPrivate *instance();
+
static EditorArea *mainEditorArea();
static EditorView *currentEditorView();
static void setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory = false);
@@ -95,6 +97,7 @@ public:
static EditorView *viewForEditor(IEditor *editor);
static void setCurrentView(EditorView *view);
+ static void activateView(EditorView *view);
static MakeWritableResult makeFileWritable(IDocument *document);
static void doEscapeKeyFocusMoveMagic();
@@ -121,6 +124,9 @@ public:
static void vcsOpenCurrentEditor();
static void makeCurrentEditorWritable();
+ static void setPlaceholderText(const QString &text);
+ static QString placeholderText();
+
public slots:
static bool saveDocument(Core::IDocument *document);
static bool saveDocumentAs(Core::IDocument *document);
@@ -132,6 +138,9 @@ public slots:
void handleDocumentStateChange();
static void editorAreaDestroyed(QObject *area);
+signals:
+ void placeholderTextChanged(const QString &text);
+
private slots:
static void gotoNextDocHistory();
static void gotoPreviousDocHistory();
@@ -140,6 +149,7 @@ private slots:
static void handleContextChange(const QList<Core::IContext *> &context);
static void copyFilePathFromContextMenu();
+ void copyLocationFromContextMenu();
static void copyFileNameFromContextMenu();
static void saveDocumentFromContextMenu();
static void saveDocumentAsFromContextMenu();
@@ -168,7 +178,6 @@ private:
static void addEditor(IEditor *editor);
static void removeEditor(IEditor *editor);
static IEditor *placeEditor(EditorView *view, IEditor *editor);
- static void activateView(EditorView *view);
static void restoreEditorState(IEditor *editor);
static int visibleDocumentsCount();
static EditorArea *findEditorArea(const EditorView *view, int *areaIndex = 0);
@@ -212,6 +221,7 @@ private:
QAction *m_gotoNextSplitAction;
QAction *m_copyFilePathContextAction;
+ QAction *m_copyLocationContextAction; // Copy path and line number.
QAction *m_copyFileNameContextAction;
QAction *m_saveCurrentEditorContextAction;
QAction *m_saveAsCurrentEditorContextAction;
@@ -240,6 +250,8 @@ private:
bool m_autoSaveEnabled;
int m_autoSaveInterval;
+
+ QString m_placeholderText;
};
} // Internal
diff --git a/src/plugins/coreplugin/editormanager/editorview.cpp b/src/plugins/coreplugin/editormanager/editorview.cpp
index 31d4f0adab5..ae541c885a9 100644
--- a/src/plugins/coreplugin/editormanager/editorview.cpp
+++ b/src/plugins/coreplugin/editormanager/editorview.cpp
@@ -34,10 +34,12 @@
#include "editormanager_p.h"
#include "documentmodel.h"
+#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/editortoolbar.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/infobar.h>
+#include <coreplugin/locator/locatorconstants.h>
#include <coreplugin/minisplitter.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/findplaceholder.h>
@@ -119,14 +121,22 @@ EditorView::EditorView(SplitterOrView *parentSplitterOrView, QWidget *parent) :
}
// for the case of no document selected
- QWidget *empty = new QWidget;
+ auto empty = new QWidget;
+ empty->hide();
+ auto emptyLayout = new QGridLayout(empty);
+ empty->setLayout(emptyLayout);
+ m_emptyViewLabel = new QLabel;
+ connect(EditorManagerPrivate::instance(), &EditorManagerPrivate::placeholderTextChanged,
+ m_emptyViewLabel, &QLabel::setText);
+ m_emptyViewLabel->setText(EditorManagerPrivate::placeholderText());
+ emptyLayout->addWidget(m_emptyViewLabel);
m_container->addWidget(empty);
m_widgetEditorMap.insert(empty, 0);
- auto dropSupport = new Utils::FileDropSupport(this, [this](QDropEvent *event) {
+ auto dropSupport = new FileDropSupport(this, [this](QDropEvent *event) {
return event->source() != m_toolBar; // do not accept drops on ourselves
});
- connect(dropSupport, &Utils::FileDropSupport::filesDropped,
+ connect(dropSupport, &FileDropSupport::filesDropped,
this, &EditorView::openDroppedFiles);
updateNavigatorActions();
@@ -219,7 +229,7 @@ void EditorView::updateEditorHistory(IEditor *editor, QList<EditLocation> &histo
EditLocation location;
location.document = document;
- location.fileName = document->filePath();
+ location.fileName = document->filePath().toString();
location.id = document->id();
location.state = QVariant(state);
@@ -357,11 +367,11 @@ void EditorView::closeSplit()
EditorManagerPrivate::updateActions();
}
-void EditorView::openDroppedFiles(const QList<Utils::FileDropSupport::FileSpec> &files)
+void EditorView::openDroppedFiles(const QList<FileDropSupport::FileSpec> &files)
{
const int count = files.size();
for (int i = 0; i < count; ++i) {
- const Utils::FileDropSupport::FileSpec spec = files.at(i);
+ const FileDropSupport::FileSpec spec = files.at(i);
EditorManagerPrivate::openEditorAt(this, spec.filePath, spec.line, spec.column, Id(),
i < count - 1 ? EditorManager::DoNotChangeCurrentEditor
| EditorManager::DoNotMakeVisible
@@ -440,7 +450,7 @@ void EditorView::addCurrentPositionToNavigationHistory(const QByteArray &saveSta
EditLocation location;
location.document = document;
- location.fileName = document->filePath();
+ location.fileName = document->filePath().toString();
location.id = document->id();
location.state = QVariant(state);
m_currentNavigationHistoryPosition = qMin(m_currentNavigationHistoryPosition, m_navigationHistory.size()); // paranoia
@@ -495,7 +505,7 @@ void EditorView::updateCurrentPositionInNavigationHistory()
location = &m_navigationHistory[m_navigationHistory.size()-1];
}
location->document = document;
- location->fileName = document->filePath();
+ location->fileName = document->filePath().toString();
location->id = document->id();
location->state = QVariant(editor->saveState());
}
@@ -551,7 +561,7 @@ void EditorView::goForwardInNavigationHistory()
}
-SplitterOrView::SplitterOrView(Core::IEditor *editor)
+SplitterOrView::SplitterOrView(IEditor *editor)
{
m_layout = new QStackedLayout(this);
m_layout->setSizeConstraint(QLayout::SetNoConstraint);
@@ -671,10 +681,7 @@ void SplitterOrView::split(Qt::Orientation orientation)
otherView->view()->setCloseSplitIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
}
- if (e)
- EditorManagerPrivate::activateEditor(otherView->view(), e);
- else
- EditorManagerPrivate::setCurrentView(otherView->view());
+ EditorManagerPrivate::activateView(otherView->view());
emit splitStateChanged();
}
@@ -775,7 +782,10 @@ void SplitterOrView::unsplit()
m_layout->setCurrentWidget(m_view);
}
delete oldSplitter;
- EditorManagerPrivate::setCurrentView(findFirstView());
+ if (EditorView *newCurrent = findFirstView())
+ EditorManagerPrivate::activateView(newCurrent);
+ else
+ EditorManagerPrivate::setCurrentView(0);
emit splitStateChanged();
}
@@ -810,10 +820,14 @@ QByteArray SplitterOrView::saveState() const
stream << QByteArray("empty");
} else if (e == EditorManager::currentEditor()) {
stream << QByteArray("currenteditor")
- << e->document()->filePath() << e->document()->id().toString() << e->saveState();
+ << e->document()->filePath().toString()
+ << e->document()->id().toString()
+ << e->saveState();
} else {
stream << QByteArray("editor")
- << e->document()->filePath() << e->document()->id().toString() << e->saveState();
+ << e->document()->filePath().toString()
+ << e->document()->id().toString()
+ << e->saveState();
}
}
return bytes;
@@ -840,8 +854,8 @@ void SplitterOrView::restoreState(const QByteArray &state)
if (!QFile::exists(fileName))
return;
IEditor *e = EditorManagerPrivate::openEditor(view(), fileName, Id::fromString(id),
- Core::EditorManager::IgnoreNavigationHistory
- | Core::EditorManager::DoNotChangeCurrentEditor);
+ EditorManager::IgnoreNavigationHistory
+ | EditorManager::DoNotChangeCurrentEditor);
if (!e) {
DocumentModel::Entry *entry = DocumentModel::firstRestoredEntry();
diff --git a/src/plugins/coreplugin/editormanager/editorview.h b/src/plugins/coreplugin/editormanager/editorview.h
index 7cae6590ef5..b5a272e3ede 100644
--- a/src/plugins/coreplugin/editormanager/editorview.h
+++ b/src/plugins/coreplugin/editormanager/editorview.h
@@ -145,6 +145,7 @@ private:
QToolButton *m_statusWidgetButton;
QList<IEditor *> m_editors;
QMap<QWidget *, IEditor *> m_widgetEditorMap;
+ QLabel *m_emptyViewLabel;
QList<EditLocation> m_navigationHistory;
QList<EditLocation> m_editorHistory;
@@ -173,7 +174,7 @@ class SplitterOrView : public QWidget
{
Q_OBJECT
public:
- explicit SplitterOrView(Core::IEditor *editor = 0);
+ explicit SplitterOrView(IEditor *editor = 0);
explicit SplitterOrView(EditorView *view);
~SplitterOrView();
@@ -183,9 +184,9 @@ public:
inline bool isView() const { return m_view != 0; }
inline bool isSplitter() const { return m_splitter != 0; }
- inline Core::IEditor *editor() const { return m_view ? m_view->currentEditor() : 0; }
- inline QList<Core::IEditor *> editors() const { return m_view ? m_view->editors() : QList<Core::IEditor*>(); }
- inline bool hasEditor(Core::IEditor *editor) const { return m_view && m_view->hasEditor(editor); }
+ inline IEditor *editor() const { return m_view ? m_view->currentEditor() : 0; }
+ inline QList<IEditor *> editors() const { return m_view ? m_view->editors() : QList<IEditor*>(); }
+ inline bool hasEditor(IEditor *editor) const { return m_view && m_view->hasEditor(editor); }
inline bool hasEditors() const { return m_view && m_view->editorCount() != 0; }
inline EditorView *view() const { return m_view; }
inline QSplitter *splitter() const { return m_splitter; }
diff --git a/src/plugins/coreplugin/editormanager/openeditorsview.cpp b/src/plugins/coreplugin/editormanager/openeditorsview.cpp
index e6e1cd64285..263f8ff7da4 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsview.cpp
+++ b/src/plugins/coreplugin/editormanager/openeditorsview.cpp
@@ -74,7 +74,7 @@ OpenEditorsWidget::~OpenEditorsWidget()
{
}
-void OpenEditorsWidget::updateCurrentItem(Core::IEditor *editor)
+void OpenEditorsWidget::updateCurrentItem(IEditor *editor)
{
IDocument *document = editor ? editor->document() : 0;
QModelIndex index = m_model->index(DocumentModel::indexOfDocument(document), 0);
@@ -138,7 +138,7 @@ OpenEditorsViewFactory::OpenEditorsViewFactory()
{
setId("Open Documents");
setDisplayName(OpenEditorsWidget::tr("Open Documents"));
- setActivationSequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+O") : tr("Alt+O")));
+ setActivationSequence(QKeySequence(UseMacShortcuts ? tr("Meta+O") : tr("Alt+O")));
setPriority(200);
}
diff --git a/src/plugins/coreplugin/editormanager/openeditorsview.h b/src/plugins/coreplugin/editormanager/openeditorsview.h
index b14fb0dd830..0701617740c 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsview.h
+++ b/src/plugins/coreplugin/editormanager/openeditorsview.h
@@ -77,26 +77,24 @@ public:
OpenEditorsWidget();
~OpenEditorsWidget();
-private slots:
+private:
void handleActivated(const QModelIndex &);
- void updateCurrentItem(Core::IEditor*);
+ void updateCurrentItem(IEditor*);
void contextMenuRequested(QPoint pos);
-
-private:
void activateEditor(const QModelIndex &index);
void closeDocument(const QModelIndex &index);
ProxyModel *m_model;
};
-class OpenEditorsViewFactory : public Core::INavigationWidgetFactory
+class OpenEditorsViewFactory : public INavigationWidgetFactory
{
Q_OBJECT
public:
OpenEditorsViewFactory();
- Core::NavigationView createWidget();
+ NavigationView createWidget();
};
} // namespace Internal
diff --git a/src/plugins/coreplugin/editormanager/openeditorswindow.cpp b/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
index ac3784fd3b9..eab67b2a7a7 100644
--- a/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
+++ b/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
@@ -198,7 +198,7 @@ void OpenEditorsWindow::selectEditor(QTreeWidgetItem *item)
EditorManagerPrivate::activateEditorForDocument(view, document);
} else {
if (!EditorManager::openEditor(
- item->toolTip(0), item->data(0, Qt::UserRole+2).value<Core::Id>())) {
+ item->toolTip(0), item->data(0, Qt::UserRole+2).value<Id>())) {
DocumentModel::removeDocument(item->toolTip(0));
delete item;
}
@@ -233,7 +233,7 @@ void OpenEditorsWindow::addHistoryItems(const QList<EditLocation> &history, Edit
item->setIcon(0, !hi.document->filePath().isEmpty() && hi.document->isFileReadOnly()
? DocumentModel::lockedIcon() : m_emptyIcon);
item->setText(0, title);
- item->setToolTip(0, hi.document->filePath());
+ item->setToolTip(0, hi.document->filePath().toString());
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/editortoolbar.cpp b/src/plugins/coreplugin/editortoolbar.cpp
index 27ccf861781..1c8a0105f2f 100644
--- a/src/plugins/coreplugin/editortoolbar.cpp
+++ b/src/plugins/coreplugin/editortoolbar.cpp
@@ -304,8 +304,8 @@ void EditorToolBar::setToolbarCreationFlags(ToolbarCreationFlags flags)
{
d->m_isStandalone = flags & FlagsStandalone;
if (d->m_isStandalone) {
- EditorManager *em = EditorManager::instance();
- connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), SLOT(updateEditorListSelection(Core::IEditor*)));
+ connect(EditorManager::instance(), &EditorManager::currentEditorChanged,
+ this, &EditorToolBar::updateEditorListSelection);
disconnect(d->m_editorList, SIGNAL(activated(int)), this, SIGNAL(listSelectionActivated(int)));
connect(d->m_editorList, SIGNAL(activated(int)), this, SLOT(changeActiveEditor(int)));
@@ -424,12 +424,11 @@ void EditorToolBar::updateDocumentStatus(IDocument *document)
if (document->filePath().isEmpty())
d->m_dragHandle->setIcon(QIcon());
else
- d->m_dragHandle->setIcon(FileIconProvider::icon(QFileInfo(document->filePath())));
+ d->m_dragHandle->setIcon(FileIconProvider::icon(document->filePath().toFileInfo()));
- d->m_editorList->setToolTip(
- document->filePath().isEmpty()
- ? document->displayName()
- : QDir::toNativeSeparators(document->filePath()));
+ d->m_editorList->setToolTip(document->filePath().isEmpty()
+ ? document->displayName()
+ : document->filePath().toUserOutput());
}
bool EditorToolBar::eventFilter(QObject *obj, QEvent *event)
diff --git a/src/plugins/coreplugin/editortoolbar.h b/src/plugins/coreplugin/editortoolbar.h
index d6bb2ab8a7d..7d13929607e 100644
--- a/src/plugins/coreplugin/editortoolbar.h
+++ b/src/plugins/coreplugin/editortoolbar.h
@@ -90,9 +90,6 @@ public:
void setCloseSplitEnabled(bool enable);
void setCloseSplitIcon(const QIcon &icon);
-public slots:
- void updateDocumentStatus(Core::IDocument *document);
-
signals:
void closeClicked();
void goBackClicked();
@@ -108,7 +105,6 @@ protected:
bool eventFilter(QObject *obj, QEvent *event);
private slots:
- void updateEditorListSelection(Core::IEditor *newSelection);
void changeActiveEditor(int row);
void makeEditorWritable();
@@ -117,6 +113,8 @@ private slots:
void updateActionShortcuts();
private:
+ void updateDocumentStatus(IDocument *document);
+ void updateEditorListSelection(IEditor *newSelection);
void fillListContextMenu(QMenu *menu);
void updateToolBar(QWidget *toolBar);
diff --git a/src/plugins/coreplugin/externaltool.cpp b/src/plugins/coreplugin/externaltool.cpp
index 5f2fd521221..66023c55349 100644
--- a/src/plugins/coreplugin/externaltool.cpp
+++ b/src/plugins/coreplugin/externaltool.cpp
@@ -30,27 +30,22 @@
#include "externaltool.h"
#include "externaltoolmanager.h"
-#include "actionmanager/actionmanager.h"
-#include "actionmanager/actioncontainer.h"
-#include "coreconstants.h"
+
+#include "messagemanager.h"
+#include "documentmanager.h"
+#include "editormanager/editormanager.h"
+#include "editormanager/ieditor.h"
#include <app/app_version.h>
-#include <coreplugin/icore.h>
-#include <coreplugin/messagemanager.h>
-#include <coreplugin/documentmanager.h>
-#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/editormanager/ieditor.h>
#include <utils/fileutils.h>
#include <utils/macroexpander.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
-#include <QAction>
#include <QCoreApplication>
#include <QDateTime>
-#include <QDebug>
-#include <QDir>
+#include <QFileInfo>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
@@ -71,6 +66,7 @@ const char kPath[] = "path";
const char kArguments[] = "arguments";
const char kInput[] = "input";
const char kWorkingDirectory[] = "workingdirectory";
+const char kEnvironment[] = "environment";
const char kXmlLang[] = "xml:lang";
const char kOutput[] = "output";
@@ -84,8 +80,6 @@ const char kNo[] = "no";
const char kTrue[] = "true";
const char kFalse[] = "false";
-const char kSpecialUncategorizedSetting[] = "SpecialEmptyCategoryForUncategorizedTools";
-
// #pragma mark -- ExternalTool
ExternalTool::ExternalTool() :
@@ -107,6 +101,7 @@ ExternalTool::ExternalTool(const ExternalTool *other)
m_arguments(other->m_arguments),
m_input(other->m_input),
m_workingDirectory(other->m_workingDirectory),
+ m_environment(other->m_environment),
m_outputHandling(other->m_outputHandling),
m_errorHandling(other->m_errorHandling),
m_modifiesCurrentDocument(other->m_modifiesCurrentDocument),
@@ -126,6 +121,7 @@ ExternalTool &ExternalTool::operator=(const ExternalTool &other)
m_arguments = other.m_arguments;
m_input = other.m_input;
m_workingDirectory = other.m_workingDirectory;
+ m_environment = other.m_environment;
m_outputHandling = other.m_outputHandling;
m_errorHandling = other.m_errorHandling;
m_modifiesCurrentDocument = other.m_modifiesCurrentDocument;
@@ -184,6 +180,11 @@ QString ExternalTool::workingDirectory() const
return m_workingDirectory;
}
+QList<EnvironmentItem> ExternalTool::environment() const
+{
+ return m_environment;
+}
+
ExternalTool::OutputHandling ExternalTool::outputHandling() const
{
return m_outputHandling;
@@ -281,6 +282,11 @@ void ExternalTool::setWorkingDirectory(const QString &workingDirectory)
m_workingDirectory = workingDirectory;
}
+void ExternalTool::setEnvironment(const QList<EnvironmentItem> &items)
+{
+ m_environment = items;
+}
+
static QStringList splitLocale(const QString &locale)
{
QString value = locale;
@@ -415,6 +421,15 @@ ExternalTool * ExternalTool::createFromXml(const QByteArray &xml, QString *error
break;
}
tool->m_workingDirectory = reader.readElementText();
+ } else if (reader.name() == QLatin1String(kEnvironment)) {
+ if (!tool->m_environment.isEmpty()) {
+ reader.raiseError(QLatin1String("only one <environment> element allowed"));
+ break;
+ }
+ QStringList lines = reader.readElementText().split(QLatin1Char(';'));
+ for (auto iter = lines.begin(); iter != lines.end(); ++iter)
+ *iter = QString::fromUtf8(QByteArray::fromPercentEncoding(iter->toUtf8()));
+ tool->m_environment = EnvironmentItem::fromStringList(lines);
} else {
reader.raiseError(QString::fromLatin1("Unknown element <%1> as subelement of <%2>").arg(
reader.qualifiedName().toString(), QLatin1String(kExecutable)));
@@ -491,6 +506,12 @@ bool ExternalTool::save(QString *errorMessage) const
out.writeTextElement(QLatin1String(kInput), m_input);
if (!m_workingDirectory.isEmpty())
out.writeTextElement(QLatin1String(kWorkingDirectory), m_workingDirectory);
+ if (!m_environment.isEmpty()) {
+ QStringList envLines = EnvironmentItem::toStringList(m_environment);
+ for (auto iter = envLines.begin(); iter != envLines.end(); ++iter)
+ *iter = QString::fromUtf8(iter->toUtf8().toPercentEncoding());
+ out.writeTextElement(QLatin1String(kEnvironment), envLines.join(QLatin1Char(';')));
+ }
out.writeEndElement();
out.writeEndDocument();
@@ -511,6 +532,7 @@ bool ExternalTool::operator==(const ExternalTool &other) const
&& m_arguments == other.m_arguments
&& m_input == other.m_input
&& m_workingDirectory == other.m_workingDirectory
+ && m_environment == other.m_environment
&& m_outputHandling == other.m_outputHandling
&& m_modifiesCurrentDocument == other.m_modifiesCurrentDocument
&& m_errorHandling == other.m_errorHandling
@@ -551,14 +573,19 @@ bool ExternalToolRunner::resolve()
m_resolvedExecutable.clear();
m_resolvedArguments.clear();
m_resolvedWorkingDirectory.clear();
+ m_resolvedEnvironment = Environment::systemEnvironment();
+
MacroExpander *expander = globalMacroExpander();
- { // executable
+ m_resolvedEnvironment.modify(m_tool->environment());
+
+ {
+ // executable
QStringList expandedExecutables; /* for error message */
foreach (const QString &executable, m_tool->executables()) {
QString expanded = expander->expand(executable);
expandedExecutables.append(expanded);
- m_resolvedExecutable = Environment::systemEnvironment().searchInPath(expanded);
+ m_resolvedExecutable = m_resolvedEnvironment.searchInPath(expanded);
if (!m_resolvedExecutable.isEmpty())
break;
}
@@ -591,7 +618,7 @@ void ExternalToolRunner::run()
}
if (m_tool->modifiesCurrentDocument()) {
if (IDocument *document = EditorManager::currentDocument()) {
- m_expectedFileName = document->filePath();
+ m_expectedFileName = document->filePath().toString();
if (!DocumentManager::saveModifiedDocument(document)) {
deleteLater();
return;
@@ -608,6 +635,7 @@ void ExternalToolRunner::run()
if (!m_resolvedWorkingDirectory.isEmpty())
m_process->setWorkingDirectory(m_resolvedWorkingDirectory);
m_process->setCommand(m_resolvedExecutable.toString(), m_resolvedArguments);
+ m_process->setEnvironment(m_resolvedEnvironment);
MessageManager::write(tr("Starting external tool \"%1\" %2")
.arg(m_resolvedExecutable.toUserOutput(), m_resolvedArguments),
MessageManager::Silent);
@@ -670,297 +698,4 @@ void ExternalToolRunner::readStandardError()
} // namespace Internal
-// ExternalToolManager
-
-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;
- d = new ExternalToolManagerPrivate;
-
- d->m_configureSeparator = new QAction(this);
- d->m_configureSeparator->setSeparator(true);
- d->m_configureAction = new QAction(Core::ICore::msgShowOptionsDialog(), 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(ExternalToolManager::tr("&External"));
- ActionContainer *mtools = ActionManager::actionContainer(Constants::M_TOOLS);
- mtools->addMenu(mexternaltools, Constants::G_DEFAULT_THREE);
-
- QMap<QString, QMultiMap<int, ExternalTool*> > categoryPriorityMap;
- QMap<QString, ExternalTool *> tools;
- parseDirectory(ICore::userResourcePath() + QLatin1String("/externaltools"),
- &categoryPriorityMap,
- &tools);
- parseDirectory(ICore::resourcePath() + QLatin1String("/externaltools"),
- &categoryPriorityMap,
- &tools,
- true);
-
- QMap<QString, QList<ExternalTool *> > categoryMap;
- QMapIterator<QString, QMultiMap<int, ExternalTool*> > it(categoryPriorityMap);
- while (it.hasNext()) {
- it.next();
- categoryMap.insert(it.key(), it.value().values());
- }
-
- // read renamed categories and custom order
- readSettings(tools, &categoryMap);
- setToolsByCategory(categoryMap);
-}
-
-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);
- QDir dir(directory, QLatin1String("*.xml"), QDir::Unsorted, QDir::Files | QDir::Readable);
- foreach (const QFileInfo &info, dir.entryInfoList()) {
- const QString &fileName = info.absoluteFilePath();
- QString error;
- ExternalTool *tool = ExternalTool::createFromFile(fileName, &error, ICore::userInterfaceLanguage());
- if (!tool) {
- qWarning() << ExternalTool::tr("Error while parsing external tool %1: %2").arg(fileName, error);
- continue;
- }
- if (tools->contains(tool->id())) {
- if (isPreset) {
- // preset that was changed
- ExternalTool *other = tools->value(tool->id());
- other->setPreset(QSharedPointer<ExternalTool>(tool));
- } else {
- qWarning() << ExternalToolManager::tr("Error: External tool in %1 has duplicate id").arg(fileName);
- delete tool;
- }
- continue;
- }
- if (isPreset) {
- // preset that wasn't changed --> save original values
- tool->setPreset(QSharedPointer<ExternalTool>(new ExternalTool(tool)));
- }
- tools->insert(tool->id(), tool);
- (*categoryMenus)[tool->displayCategory()].insert(tool->order(), tool);
- }
-}
-
-void ExternalToolManager::menuActivated()
-{
- QAction *action = qobject_cast<QAction *>(sender());
- QTC_ASSERT(action, return);
- ExternalTool *tool = d->m_tools.value(action->data().toString());
- QTC_ASSERT(tool, return);
- ExternalToolRunner *runner = new ExternalToolRunner(tool);
- if (runner->hasError())
- MessageManager::write(runner->errorString());
-}
-
-QMap<QString, QList<ExternalTool *> > ExternalToolManager::toolsByCategory()
-{
- return d->m_categoryMap;
-}
-
-QMap<QString, ExternalTool *> ExternalToolManager::toolsById()
-{
- return d->m_tools;
-}
-
-void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<ExternalTool *> > &tools)
-{
- // clear menu
- ActionContainer *mexternaltools = ActionManager::actionContainer(Id(Constants::M_TOOLS_EXTERNAL));
- mexternaltools->clear();
-
- // delete old tools and create list of new ones
- QMap<QString, ExternalTool *> newTools;
- QMap<QString, QAction *> newActions;
- QMapIterator<QString, QList<ExternalTool *> > it(tools);
- while (it.hasNext()) {
- it.next();
- foreach (ExternalTool *tool, it.value()) {
- 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
- d->m_tools.remove(id);
- d->m_actions.remove(id);
- }
- newTools.insert(id, tool);
- }
- }
- 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();
- }
- d->m_actions.clear();
- // assign the new stuff
- 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;
- it.toFront();
- while (it.hasNext()) {
- it.next();
- ActionContainer *container = 0;
- const QString &containerName = it.key();
- if (containerName.isEmpty()) { // no displayCategory, so put into external tools menu directly
- container = mexternaltools;
- } else {
- 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);
- mexternaltools->addMenu(container, Constants::G_DEFAULT_ONE);
- container->menu()->setTitle(containerName);
- }
- foreach (ExternalTool *tool, it.value()) {
- const QString &toolId = tool->id();
- // tool action and command
- QAction *action = 0;
- Command *command = 0;
- if (d->m_actions.contains(toolId)) {
- action = d->m_actions.value(toolId);
- command = ActionManager::command(externalToolsPrefix.withSuffix(toolId));
- } else {
- action = new QAction(tool->displayName(), m_instance);
- action->setData(toolId);
- 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);
- }
- action->setText(tool->displayName());
- action->setToolTip(tool->description());
- action->setWhatsThis(tool->description());
- container->addAction(command, Constants::G_DEFAULT_TWO);
- }
- }
-
- // delete the unused containers
- qDeleteAll(d->m_containers);
- // remember the new containers
- d->m_containers = newContainers;
-
- // (re)add the configure menu item
- mexternaltools->menu()->addAction(d->m_configureSeparator);
- mexternaltools->menu()->addAction(d->m_configureAction);
-}
-
-static void readSettings(const QMap<QString, ExternalTool *> &tools,
- QMap<QString, QList<ExternalTool *> > *categoryMap)
-{
- QSettings *settings = ICore::settings();
- settings->beginGroup(QLatin1String("ExternalTools"));
-
- if (categoryMap) {
- settings->beginGroup(QLatin1String("OverrideCategories"));
- foreach (const QString &settingsCategory, settings->childGroups()) {
- QString displayCategory = settingsCategory;
- if (displayCategory == QLatin1String(kSpecialUncategorizedSetting))
- displayCategory = QLatin1String("");
- int count = settings->beginReadArray(settingsCategory);
- for (int i = 0; i < count; ++i) {
- settings->setArrayIndex(i);
- const QString &toolId = settings->value(QLatin1String("Tool")).toString();
- if (tools.contains(toolId)) {
- ExternalTool *tool = tools.value(toolId);
- // remove from old category
- (*categoryMap)[tool->displayCategory()].removeAll(tool);
- if (categoryMap->value(tool->displayCategory()).isEmpty())
- categoryMap->remove(tool->displayCategory());
- // add to new category
- (*categoryMap)[displayCategory].append(tool);
- }
- }
- settings->endArray();
- }
- settings->endGroup();
- }
-
- settings->endGroup();
-}
-
-static void writeSettings()
-{
- QSettings *settings = ICore::settings();
- settings->beginGroup(QLatin1String("ExternalTools"));
- settings->remove(QLatin1String(""));
-
- settings->beginGroup(QLatin1String("OverrideCategories"));
- QMapIterator<QString, QList<ExternalTool *> > it(d->m_categoryMap);
- while (it.hasNext()) {
- it.next();
- QString category = it.key();
- if (category.isEmpty())
- category = QLatin1String(kSpecialUncategorizedSetting);
- settings->beginWriteArray(category, it.value().count());
- int i = 0;
- foreach (ExternalTool *tool, it.value()) {
- settings->setArrayIndex(i);
- settings->setValue(QLatin1String("Tool"), tool->id());
- ++i;
- }
- settings->endArray();
- }
- settings->endGroup();
-
- settings->endGroup();
-}
-
-void ExternalToolManager::openPreferences()
-{
- ICore::showOptionsDialog(Constants::SETTINGS_CATEGORY_CORE, Constants::SETTINGS_ID_TOOLS);
-}
-
-void ExternalToolManager::emitReplaceSelectionRequested(const QString &output)
-{
- emit m_instance->replaceSelectionRequested(output);
-}
-
} // namespace Core
diff --git a/src/plugins/coreplugin/externaltool.h b/src/plugins/coreplugin/externaltool.h
index 45831fd7630..c01c15c665b 100644
--- a/src/plugins/coreplugin/externaltool.h
+++ b/src/plugins/coreplugin/externaltool.h
@@ -32,6 +32,7 @@
#define EXTERNALTOOL_H
#include <utils/fileutils.h>
+#include <utils/environment.h>
#include <QObject>
#include <QStringList>
@@ -72,6 +73,7 @@ public:
QString arguments() const;
QString input() const;
QString workingDirectory() const;
+ QList<Utils::EnvironmentItem> environment() const;
void setFileName(const QString &fileName);
void setPreset(QSharedPointer<ExternalTool> preset);
@@ -100,6 +102,7 @@ public:
void setArguments(const QString &arguments);
void setInput(const QString &input);
void setWorkingDirectory(const QString &workingDirectory);
+ void setEnvironment(const QList<Utils::EnvironmentItem> &items);
private:
QString m_id;
@@ -111,6 +114,7 @@ private:
QString m_arguments;
QString m_input;
QString m_workingDirectory;
+ QList<Utils::EnvironmentItem> m_environment;
OutputHandling m_outputHandling;
OutputHandling m_errorHandling;
bool m_modifiesCurrentDocument;
@@ -146,6 +150,7 @@ private:
QString m_resolvedArguments;
QString m_resolvedInput;
QString m_resolvedWorkingDirectory;
+ Utils::Environment m_resolvedEnvironment;
Utils::QtcProcess *m_process;
QTextCodec *m_outputCodec;
QTextCodec::ConverterState m_outputCodecState;
diff --git a/src/plugins/coreplugin/externaltoolmanager.cpp b/src/plugins/coreplugin/externaltoolmanager.cpp
new file mode 100644
index 00000000000..8221accc9ba
--- /dev/null
+++ b/src/plugins/coreplugin/externaltoolmanager.cpp
@@ -0,0 +1,343 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "externaltoolmanager.h"
+#include "externaltool.h"
+#include "coreconstants.h"
+#include "icore.h"
+#include "messagemanager.h"
+#include "actionmanager/actionmanager.h"
+#include "actionmanager/actioncontainer.h"
+
+#include <utils/qtcassert.h>
+
+#include <QAction>
+#include <QDebug>
+#include <QDir>
+#include <QMenu>
+
+using namespace Core::Internal;
+
+namespace Core {
+
+const char kSpecialUncategorizedSetting[] = "SpecialEmptyCategoryForUncategorizedTools";
+
+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;
+ d = new ExternalToolManagerPrivate;
+
+ d->m_configureSeparator = new QAction(this);
+ d->m_configureSeparator->setSeparator(true);
+ d->m_configureAction = new QAction(ICore::msgShowOptionsDialog(), 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(ExternalToolManager::tr("&External"));
+ ActionContainer *mtools = ActionManager::actionContainer(Constants::M_TOOLS);
+ mtools->addMenu(mexternaltools, Constants::G_DEFAULT_THREE);
+
+ QMap<QString, QMultiMap<int, ExternalTool*> > categoryPriorityMap;
+ QMap<QString, ExternalTool *> tools;
+ parseDirectory(ICore::userResourcePath() + QLatin1String("/externaltools"),
+ &categoryPriorityMap,
+ &tools);
+ parseDirectory(ICore::resourcePath() + QLatin1String("/externaltools"),
+ &categoryPriorityMap,
+ &tools,
+ true);
+
+ QMap<QString, QList<ExternalTool *> > categoryMap;
+ QMapIterator<QString, QMultiMap<int, ExternalTool*> > it(categoryPriorityMap);
+ while (it.hasNext()) {
+ it.next();
+ categoryMap.insert(it.key(), it.value().values());
+ }
+
+ // read renamed categories and custom order
+ readSettings(tools, &categoryMap);
+ setToolsByCategory(categoryMap);
+}
+
+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);
+ QDir dir(directory, QLatin1String("*.xml"), QDir::Unsorted, QDir::Files | QDir::Readable);
+ foreach (const QFileInfo &info, dir.entryInfoList()) {
+ const QString &fileName = info.absoluteFilePath();
+ QString error;
+ ExternalTool *tool = ExternalTool::createFromFile(fileName, &error, ICore::userInterfaceLanguage());
+ if (!tool) {
+ qWarning() << ExternalTool::tr("Error while parsing external tool %1: %2").arg(fileName, error);
+ continue;
+ }
+ if (tools->contains(tool->id())) {
+ if (isPreset) {
+ // preset that was changed
+ ExternalTool *other = tools->value(tool->id());
+ other->setPreset(QSharedPointer<ExternalTool>(tool));
+ } else {
+ qWarning() << ExternalToolManager::tr("Error: External tool in %1 has duplicate id").arg(fileName);
+ delete tool;
+ }
+ continue;
+ }
+ if (isPreset) {
+ // preset that wasn't changed --> save original values
+ tool->setPreset(QSharedPointer<ExternalTool>(new ExternalTool(tool)));
+ }
+ tools->insert(tool->id(), tool);
+ (*categoryMenus)[tool->displayCategory()].insert(tool->order(), tool);
+ }
+}
+
+void ExternalToolManager::menuActivated()
+{
+ QAction *action = qobject_cast<QAction *>(sender());
+ QTC_ASSERT(action, return);
+ ExternalTool *tool = d->m_tools.value(action->data().toString());
+ QTC_ASSERT(tool, return);
+ ExternalToolRunner *runner = new ExternalToolRunner(tool);
+ if (runner->hasError())
+ MessageManager::write(runner->errorString());
+}
+
+QMap<QString, QList<ExternalTool *> > ExternalToolManager::toolsByCategory()
+{
+ return d->m_categoryMap;
+}
+
+QMap<QString, ExternalTool *> ExternalToolManager::toolsById()
+{
+ return d->m_tools;
+}
+
+void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<ExternalTool *> > &tools)
+{
+ // clear menu
+ ActionContainer *mexternaltools = ActionManager::actionContainer(Id(Constants::M_TOOLS_EXTERNAL));
+ mexternaltools->clear();
+
+ // delete old tools and create list of new ones
+ QMap<QString, ExternalTool *> newTools;
+ QMap<QString, QAction *> newActions;
+ QMapIterator<QString, QList<ExternalTool *> > it(tools);
+ while (it.hasNext()) {
+ it.next();
+ foreach (ExternalTool *tool, it.value()) {
+ 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
+ d->m_tools.remove(id);
+ d->m_actions.remove(id);
+ }
+ newTools.insert(id, tool);
+ }
+ }
+ 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();
+ }
+ d->m_actions.clear();
+ // assign the new stuff
+ 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;
+ it.toFront();
+ while (it.hasNext()) {
+ it.next();
+ ActionContainer *container = 0;
+ const QString &containerName = it.key();
+ if (containerName.isEmpty()) { // no displayCategory, so put into external tools menu directly
+ container = mexternaltools;
+ } else {
+ 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);
+ mexternaltools->addMenu(container, Constants::G_DEFAULT_ONE);
+ container->menu()->setTitle(containerName);
+ }
+ foreach (ExternalTool *tool, it.value()) {
+ const QString &toolId = tool->id();
+ // tool action and command
+ QAction *action = 0;
+ Command *command = 0;
+ if (d->m_actions.contains(toolId)) {
+ action = d->m_actions.value(toolId);
+ command = ActionManager::command(externalToolsPrefix.withSuffix(toolId));
+ } else {
+ action = new QAction(tool->displayName(), m_instance);
+ action->setData(toolId);
+ 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);
+ }
+ action->setText(tool->displayName());
+ action->setToolTip(tool->description());
+ action->setWhatsThis(tool->description());
+ container->addAction(command, Constants::G_DEFAULT_TWO);
+ }
+ }
+
+ // delete the unused containers
+ qDeleteAll(d->m_containers);
+ // remember the new containers
+ d->m_containers = newContainers;
+
+ // (re)add the configure menu item
+ mexternaltools->menu()->addAction(d->m_configureSeparator);
+ mexternaltools->menu()->addAction(d->m_configureAction);
+}
+
+static void readSettings(const QMap<QString, ExternalTool *> &tools,
+ QMap<QString, QList<ExternalTool *> > *categoryMap)
+{
+ QSettings *settings = ICore::settings();
+ settings->beginGroup(QLatin1String("ExternalTools"));
+
+ if (categoryMap) {
+ settings->beginGroup(QLatin1String("OverrideCategories"));
+ foreach (const QString &settingsCategory, settings->childGroups()) {
+ QString displayCategory = settingsCategory;
+ if (displayCategory == QLatin1String(kSpecialUncategorizedSetting))
+ displayCategory = QLatin1String("");
+ int count = settings->beginReadArray(settingsCategory);
+ for (int i = 0; i < count; ++i) {
+ settings->setArrayIndex(i);
+ const QString &toolId = settings->value(QLatin1String("Tool")).toString();
+ if (tools.contains(toolId)) {
+ ExternalTool *tool = tools.value(toolId);
+ // remove from old category
+ (*categoryMap)[tool->displayCategory()].removeAll(tool);
+ if (categoryMap->value(tool->displayCategory()).isEmpty())
+ categoryMap->remove(tool->displayCategory());
+ // add to new category
+ (*categoryMap)[displayCategory].append(tool);
+ }
+ }
+ settings->endArray();
+ }
+ settings->endGroup();
+ }
+
+ settings->endGroup();
+}
+
+static void writeSettings()
+{
+ QSettings *settings = ICore::settings();
+ settings->beginGroup(QLatin1String("ExternalTools"));
+ settings->remove(QLatin1String(""));
+
+ settings->beginGroup(QLatin1String("OverrideCategories"));
+ QMapIterator<QString, QList<ExternalTool *> > it(d->m_categoryMap);
+ while (it.hasNext()) {
+ it.next();
+ QString category = it.key();
+ if (category.isEmpty())
+ category = QLatin1String(kSpecialUncategorizedSetting);
+ settings->beginWriteArray(category, it.value().count());
+ int i = 0;
+ foreach (ExternalTool *tool, it.value()) {
+ settings->setArrayIndex(i);
+ settings->setValue(QLatin1String("Tool"), tool->id());
+ ++i;
+ }
+ settings->endArray();
+ }
+ settings->endGroup();
+
+ settings->endGroup();
+}
+
+void ExternalToolManager::openPreferences()
+{
+ ICore::showOptionsDialog(Constants::SETTINGS_CATEGORY_CORE, Constants::SETTINGS_ID_TOOLS);
+}
+
+void ExternalToolManager::emitReplaceSelectionRequested(const QString &output)
+{
+ emit m_instance->replaceSelectionRequested(output);
+}
+
+} // namespace Core
diff --git a/src/plugins/coreplugin/fancyactionbar.cpp b/src/plugins/coreplugin/fancyactionbar.cpp
index 3af5c19f49f..1fbf2308668 100644
--- a/src/plugins/coreplugin/fancyactionbar.cpp
+++ b/src/plugins/coreplugin/fancyactionbar.cpp
@@ -35,7 +35,6 @@
#include <utils/stylehelper.h>
#include <utils/stringutils.h>
#include <utils/tooltip/tooltip.h>
-#include <utils/tooltip/tipcontents.h>
#include <utils/theme/theme.h>
#include <QPainter>
@@ -82,7 +81,7 @@ bool FancyToolButton::event(QEvent *e)
case QEvent::ToolTip:
{
QHelpEvent *he = static_cast<QHelpEvent *>(e);
- ToolTip::show(mapToGlobal(he->pos()), TextContent(toolTip()), this);
+ ToolTip::show(mapToGlobal(he->pos()), toolTip(), this);
return true;
}
default:
@@ -143,7 +142,7 @@ void FancyToolButton::paintEvent(QPaintEvent *event)
bool isTitledAction = defaultAction()->property("titledAction").toBool();
- if (!Utils::HostOsInfo::isMacHost() // Mac UIs usually don't hover
+ if (!HostOsInfo::isMacHost() // Mac UIs usually don't hover
&& m_fader > 0 && isEnabled() && !isDown() && !isChecked()) {
painter.save();
const QColor hoverColor = creatorTheme()->color(Theme::FancyToolButtonHoverColor);
@@ -184,13 +183,13 @@ void FancyToolButton::paintEvent(QPaintEvent *event)
painter.restore();
}
- QRect iconRect(0, 0, Core::Constants::TARGET_ICON_SIZE, Core::Constants::TARGET_ICON_SIZE);
+ QRect iconRect(0, 0, Constants::TARGET_ICON_SIZE, Constants::TARGET_ICON_SIZE);
// draw popup texts
if (isTitledAction) {
QFont normalFont(painter.font());
QRect centerRect = rect();
- normalFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
+ normalFont.setPointSizeF(StyleHelper::sidebarFontSize());
QFont boldFont(normalFont);
boldFont.setBold(true);
QFontMetrics fm(normalFont);
@@ -205,7 +204,7 @@ void FancyToolButton::paintEvent(QPaintEvent *event)
centerRect.adjust(0, 0, 0, -lineHeight*2 - 4);
iconRect.moveCenter(centerRect.center());
- Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
+ StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
painter.setFont(normalFont);
QPoint textOffset = centerRect.center() - QPoint(iconRect.width()/2, iconRect.height()/2);
@@ -262,11 +261,11 @@ void FancyToolButton::paintEvent(QPaintEvent *event)
QStyleOption opt;
opt.initFrom(this);
opt.rect = rect().adjusted(rect().width() - 16, 0, -8, 0);
- Utils::StyleHelper::drawArrow(QStyle::PE_IndicatorArrowRight, &painter, &opt);
+ StyleHelper::drawArrow(QStyle::PE_IndicatorArrowRight, &painter, &opt);
}
} else {
iconRect.moveCenter(rect().center());
- Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
+ StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
}
}
@@ -280,8 +279,8 @@ void FancyActionBar::paintEvent(QPaintEvent *event)
painter.fillRect(event->rect(), creatorTheme()->color(Theme::FancyTabBarBackgroundColor));
}
- QColor light = Utils::StyleHelper::sidebarHighlight();
- QColor dark = Utils::StyleHelper::sidebarShadow();
+ QColor light = StyleHelper::sidebarHighlight();
+ QColor dark = StyleHelper::sidebarShadow();
painter.setPen(dark);
painter.drawLine(rect().topLeft(), rect().topRight());
painter.setPen(light);
@@ -293,7 +292,7 @@ QSize FancyToolButton::sizeHint() const
QSizeF buttonSize = iconSize().expandedTo(QSize(64, 38));
if (defaultAction()->property("titledAction").toBool()) {
QFont boldFont(font());
- boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
+ boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
boldFont.setBold(true);
QFontMetrics fm(boldFont);
qreal lineHeight = fm.height();
diff --git a/src/plugins/coreplugin/fancytabwidget.cpp b/src/plugins/coreplugin/fancytabwidget.cpp
index 23973efcda9..3dbcef902a5 100644
--- a/src/plugins/coreplugin/fancytabwidget.cpp
+++ b/src/plugins/coreplugin/fancytabwidget.cpp
@@ -100,7 +100,7 @@ FancyTabBar::~FancyTabBar()
QSize FancyTabBar::tabSizeHint(bool minimum) const
{
QFont boldFont(font());
- boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
+ boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
boldFont.setBold(true);
QFontMetrics fm(boldFont);
int spacing = 8;
@@ -288,13 +288,13 @@ void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
QRect tabIconRect(tabTextRect);
tabTextRect.translate(0, drawIcon ? -2 : 1);
QFont boldFont(painter->font());
- boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
+ boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
boldFont.setBold(true);
painter->setFont(boldFont);
painter->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
const int textFlags = Qt::AlignCenter | (drawIcon ? Qt::AlignBottom : Qt::AlignVCenter) | Qt::TextWordWrap;
- if (!Utils::HostOsInfo::isMacHost() && !selected && enabled) {
+ if (!HostOsInfo::isMacHost() && !selected && enabled) {
painter->save();
int fader = int(m_tabs[tabIndex]->fader());
if (creatorTheme()->widgetStyle() == Theme::StyleFlat) {
@@ -320,7 +320,7 @@ void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
if (drawIcon) {
int textHeight = painter->fontMetrics().boundingRect(QRect(0, 0, width(), height()), Qt::TextWordWrap, tabText).height();
tabIconRect.adjust(0, 4, 0, -textHeight);
- Utils::StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, enabled ? QIcon::Normal : QIcon::Disabled);
+ StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, enabled ? QIcon::Normal : QIcon::Disabled);
}
painter->setOpacity(1.0); //FIXME: was 0.7 before?
@@ -386,9 +386,9 @@ public:
void mousePressEvent(QMouseEvent *ev)
{
if (ev->modifiers() & Qt::ShiftModifier) {
- QColor color = QColorDialog::getColor(Utils::StyleHelper::requestedBaseColor(), m_parent);
+ QColor color = QColorDialog::getColor(StyleHelper::requestedBaseColor(), m_parent);
if (color.isValid())
- Utils::StyleHelper::setBaseColor(color);
+ StyleHelper::setBaseColor(color);
}
}
private:
@@ -409,7 +409,7 @@ FancyTabWidget::FancyTabWidget(QWidget *parent)
selectionLayout->setSpacing(0);
selectionLayout->setMargin(0);
- Utils::StyledBar *bar = new Utils::StyledBar;
+ StyledBar *bar = new StyledBar;
QHBoxLayout *layout = new QHBoxLayout(bar);
layout->setMargin(0);
layout->setSpacing(0);
@@ -490,11 +490,11 @@ void FancyTabWidget::paintEvent(QPaintEvent *event)
QRect rect = m_selectionWidget->rect().adjusted(0, 0, 1, 0);
rect = style()->visualRect(layoutDirection(), geometry(), rect);
- Utils::StyleHelper::verticalGradient(&painter, rect, rect);
- painter.setPen(Utils::StyleHelper::borderColor());
+ StyleHelper::verticalGradient(&painter, rect, rect);
+ painter.setPen(StyleHelper::borderColor());
painter.drawLine(rect.topRight(), rect.bottomRight());
- QColor light = Utils::StyleHelper::sidebarHighlight();
+ QColor light = StyleHelper::sidebarHighlight();
painter.setPen(light);
painter.drawLine(rect.bottomLeft(), rect.bottomRight());
}
diff --git a/src/plugins/coreplugin/featureprovider.h b/src/plugins/coreplugin/featureprovider.h
index b4f47b6d214..32b3439cde5 100644
--- a/src/plugins/coreplugin/featureprovider.h
+++ b/src/plugins/coreplugin/featureprovider.h
@@ -64,7 +64,7 @@ class CORE_EXPORT FeatureSet : private QSet<Feature>
public:
FeatureSet() {}
- FeatureSet(Core::Id id)
+ FeatureSet(Id id)
{
if (id.isValid())
insert(id);
diff --git a/src/plugins/coreplugin/fileutils.cpp b/src/plugins/coreplugin/fileutils.cpp
index ecf25d8442f..99a9df5f80c 100644
--- a/src/plugins/coreplugin/fileutils.cpp
+++ b/src/plugins/coreplugin/fileutils.cpp
@@ -204,7 +204,7 @@ bool FileUtils::renameFile(const QString &orgFilePath, const QString &newFilePat
result = fileSystemRenameFile(orgFilePath, newFilePath);
if (result) {
// yeah we moved, tell the filemanager about it
- Core::DocumentManager::renamedFile(orgFilePath, newFilePath);
+ DocumentManager::renamedFile(orgFilePath, newFilePath);
}
return result;
}
diff --git a/src/plugins/coreplugin/find/basetextfind.h b/src/plugins/coreplugin/find/basetextfind.h
index a753bdc376e..b327234d8d9 100644
--- a/src/plugins/coreplugin/find/basetextfind.h
+++ b/src/plugins/coreplugin/find/basetextfind.h
@@ -67,7 +67,7 @@ public:
void defineFindScope();
void clearFindScope();
- void highlightAll(const QString &txt, Core::FindFlags findFlags);
+ void highlightAll(const QString &txt, FindFlags findFlags);
signals:
void highlightAllRequested(const QString &txt, Core::FindFlags findFlags);
diff --git a/src/plugins/coreplugin/find/currentdocumentfind.cpp b/src/plugins/coreplugin/find/currentdocumentfind.cpp
index 96e3c96f829..dea2b315815 100644
--- a/src/plugins/coreplugin/find/currentdocumentfind.cpp
+++ b/src/plugins/coreplugin/find/currentdocumentfind.cpp
@@ -45,8 +45,8 @@ using namespace Core::Internal;
CurrentDocumentFind::CurrentDocumentFind()
: m_currentFind(0)
{
- connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)),
- this, SLOT(updateCandidateFindFilter(QWidget*,QWidget*)));
+ connect(qApp, &QApplication::focusChanged,
+ this, &CurrentDocumentFind::updateCandidateFindFilter);
}
void CurrentDocumentFind::removeConnections()
@@ -159,6 +159,8 @@ void CurrentDocumentFind::updateCandidateFindFilter(QWidget *old, QWidget *now)
if (!impl)
candidate = candidate->parentWidget();
}
+ if (candidate == m_candidateWidget && impl == m_candidateFind)
+ return;
if (m_candidateWidget)
disconnect(Aggregation::Aggregate::parentAggregate(m_candidateWidget), SIGNAL(changed()),
this, SLOT(candidateAggregationChanged()));
@@ -187,7 +189,8 @@ void CurrentDocumentFind::acceptCandidate()
m_currentFind = m_candidateFind;
if (m_currentFind) {
- connect(m_currentFind, SIGNAL(changed()), this, SIGNAL(changed()));
+ connect(m_currentFind.data(), &IFindSupport::changed,
+ this, &CurrentDocumentFind::changed);
connect(m_currentFind, SIGNAL(destroyed(QObject*)), SLOT(clearFindSupport()));
}
if (m_currentWidget)
@@ -198,8 +201,10 @@ void CurrentDocumentFind::acceptCandidate()
void CurrentDocumentFind::removeFindSupportConnections()
{
if (m_currentFind) {
- disconnect(m_currentFind, SIGNAL(changed()), this, SIGNAL(changed()));
- disconnect(m_currentFind, SIGNAL(destroyed(QObject*)), this, SLOT(clearFindSupport()));
+ disconnect(m_currentFind.data(), &IFindSupport::changed,
+ this, &CurrentDocumentFind::changed);
+ disconnect(m_currentFind.data(), &IFindSupport::destroyed,
+ this, &CurrentDocumentFind::clearFindSupport);
}
if (m_currentWidget)
m_currentWidget->removeEventFilter(this);
diff --git a/src/plugins/coreplugin/find/findplugin.cpp b/src/plugins/coreplugin/find/findplugin.cpp
index ac0c854785d..c50213211d8 100644
--- a/src/plugins/coreplugin/find/findplugin.cpp
+++ b/src/plugins/coreplugin/find/findplugin.cpp
@@ -193,41 +193,42 @@ void FindPlugin::openFindDialog(IFindFilter *filter)
void FindPlugin::setupMenu()
{
- Core::ActionContainer *medit = Core::ActionManager::actionContainer(Core::Constants::M_EDIT);
- Core::ActionContainer *mfind = Core::ActionManager::createMenu(Constants::M_FIND);
- medit->addMenu(mfind, Core::Constants::G_EDIT_FIND);
+ ActionContainer *medit = ActionManager::actionContainer(Constants::M_EDIT);
+ ActionContainer *mfind = ActionManager::createMenu(Constants::M_FIND);
+ medit->addMenu(mfind, Constants::G_EDIT_FIND);
mfind->menu()->setTitle(tr("&Find/Replace"));
mfind->appendGroup(Constants::G_FIND_CURRENTDOCUMENT);
mfind->appendGroup(Constants::G_FIND_FILTERS);
mfind->appendGroup(Constants::G_FIND_FLAGS);
mfind->appendGroup(Constants::G_FIND_ACTIONS);
- Core::Context globalcontext(Core::Constants::C_GLOBAL);
- Core::Command *cmd;
+ Context globalcontext(Constants::C_GLOBAL);
+ Command *cmd;
mfind->addSeparator(globalcontext, Constants::G_FIND_FLAGS);
mfind->addSeparator(globalcontext, Constants::G_FIND_ACTIONS);
- Core::ActionContainer *mfindadvanced = Core::ActionManager::createMenu(Constants::M_FIND_ADVANCED);
+ ActionContainer *mfindadvanced = ActionManager::createMenu(Constants::M_FIND_ADVANCED);
mfindadvanced->menu()->setTitle(tr("Advanced Find"));
mfind->addMenu(mfindadvanced, Constants::G_FIND_FILTERS);
d->m_openFindDialog = new QAction(tr("Open Advanced Find..."), this);
d->m_openFindDialog->setIconText(tr("Advanced..."));
- cmd = Core::ActionManager::registerAction(d->m_openFindDialog, Constants::ADVANCED_FIND, globalcontext);
+ cmd = ActionManager::registerAction(d->m_openFindDialog, Constants::ADVANCED_FIND, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+F")));
mfindadvanced->addAction(cmd);
- connect(d->m_openFindDialog, SIGNAL(triggered()), this, SLOT(openFindFilter()));
+ connect(d->m_openFindDialog, &QAction::triggered,
+ this, &FindPlugin::openFindFilter);
}
void FindPlugin::setupFilterMenuItems()
{
QList<IFindFilter*> findInterfaces =
ExtensionSystem::PluginManager::getObjects<IFindFilter>();
- Core::Command *cmd;
- Core::Context globalcontext(Core::Constants::C_GLOBAL);
+ Command *cmd;
+ Context globalcontext(Constants::C_GLOBAL);
- Core::ActionContainer *mfindadvanced = Core::ActionManager::actionContainer(Constants::M_FIND_ADVANCED);
+ ActionContainer *mfindadvanced = ActionManager::actionContainer(Constants::M_FIND_ADVANCED);
d->m_filterActions.clear();
bool haveEnabledFilters = false;
- const Core::Id base("FindFilter.");
+ const Id base("FindFilter.");
foreach (IFindFilter *filter, findInterfaces) {
QAction *action = new QAction(QLatin1String(" ") + filter->displayName(), this);
bool isEnabled = filter->isEnabled();
@@ -235,13 +236,13 @@ void FindPlugin::setupFilterMenuItems()
haveEnabledFilters = true;
action->setEnabled(isEnabled);
action->setData(qVariantFromValue(filter));
- cmd = Core::ActionManager::registerAction(action,
+ cmd = ActionManager::registerAction(action,
base.withSuffix(filter->id()), globalcontext);
cmd->setDefaultKeySequence(filter->defaultShortcut());
mfindadvanced->addAction(cmd);
d->m_filterActions.insert(filter, action);
- connect(action, SIGNAL(triggered(bool)), this, SLOT(openFindFilter()));
- connect(filter, SIGNAL(enabledChanged(bool)), this, SLOT(filterChanged()));
+ connect(action, &QAction::triggered, this, &FindPlugin::openFindFilter);
+ connect(filter, &IFindFilter::enabledChanged, this, &FindPlugin::filterChanged);
}
d->m_findDialog->setFindFilters(findInterfaces);
d->m_openFindDialog->setEnabled(haveEnabledFilters);
@@ -297,7 +298,7 @@ bool FindPlugin::hasFindFlag(FindFlag flag)
void FindPlugin::writeSettings()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String("Find"));
settings->setValue(QLatin1String("Backward"), hasFindFlag(FindBackward));
settings->setValue(QLatin1String("CaseSensitively"), hasFindFlag(FindCaseSensitively));
@@ -314,7 +315,7 @@ void FindPlugin::writeSettings()
void FindPlugin::readSettings()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String("Find"));
bool block = blockSignals(true);
setBackward(settings->value(QLatin1String("Backward"), false).toBool());
diff --git a/src/plugins/coreplugin/find/findplugin.h b/src/plugins/coreplugin/find/findplugin.h
index 8de36b25b50..e28fb9cfc9e 100644
--- a/src/plugins/coreplugin/find/findplugin.h
+++ b/src/plugins/coreplugin/find/findplugin.h
@@ -64,8 +64,8 @@ public:
FindBackwardDirection
};
- Core::FindFlags findFlags() const;
- bool hasFindFlag(Core::FindFlag flag);
+ FindFlags findFlags() const;
+ bool hasFindFlag(FindFlag flag);
void updateFindCompletion(const QString &text);
void updateReplaceCompletion(const QString &text);
QStringListModel *findCompletionModel() const;
diff --git a/src/plugins/coreplugin/find/findtoolbar.cpp b/src/plugins/coreplugin/find/findtoolbar.cpp
index 90c8e1cadfd..a07b9451063 100644
--- a/src/plugins/coreplugin/find/findtoolbar.cpp
+++ b/src/plugins/coreplugin/find/findtoolbar.cpp
@@ -62,8 +62,8 @@ Q_DECLARE_METATYPE(Core::IFindFilter*)
static const int MINIMUM_WIDTH_FOR_COMPLEX_LAYOUT = 150;
static const int FINDBUTTON_SPACER_WIDTH = 20;
-using namespace Core;
-using namespace Core::Internal;
+namespace Core {
+namespace Internal {
FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumentFind)
: m_plugin(plugin),
@@ -92,10 +92,12 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
m_ui.findEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
m_ui.replaceEdit->setAttribute(Qt::WA_MacShowFocusRect, false);
- connect(m_ui.findEdit, SIGNAL(editingFinished()), this, SLOT(invokeResetIncrementalSearch()));
+ connect(m_ui.findEdit, &Utils::FancyLineEdit::editingFinished,
+ this, &FindToolBar::invokeResetIncrementalSearch);
setLightColoredIcon(false);
- connect(m_ui.close, SIGNAL(clicked()), this, SLOT(hideAndResetFocus()));
+ connect(m_ui.close, &QToolButton::clicked,
+ this, &FindToolBar::hideAndResetFocus);
m_findCompleter->setModel(m_plugin->findCompletionModel());
m_replaceCompleter->setModel(m_plugin->replaceCompletionModel());
@@ -108,56 +110,64 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
m_ui.findEdit->button(Utils::FancyLineEdit::Left)->setFocusPolicy(Qt::TabFocus);
m_ui.replaceEdit->setPlaceholderText(QString());
- connect(m_ui.findEdit, SIGNAL(textChanged(QString)), this, SLOT(invokeFindIncremental()));
- connect(m_ui.findEdit, SIGNAL(leftButtonClicked()),
- this, SLOT(findEditButtonClicked()));
+ connect(m_ui.findEdit, &Utils::FancyLineEdit::textChanged,
+ this, &FindToolBar::invokeFindIncremental);
+ connect(m_ui.findEdit, &Utils::FancyLineEdit::leftButtonClicked,
+ this, &FindToolBar::findEditButtonClicked);
// invoke{Find,Replace}Helper change the completion model. QueuedConnection is used to perform these
// changes only after the completer's activated() signal is handled (QTCREATORBUG-8408)
- connect(m_ui.findEdit, SIGNAL(returnPressed()), this, SLOT(invokeFindEnter()), Qt::QueuedConnection);
- connect(m_ui.replaceEdit, SIGNAL(returnPressed()), this, SLOT(invokeReplaceEnter()), Qt::QueuedConnection);
+ connect(m_ui.findEdit, &Utils::FancyLineEdit::returnPressed,
+ this, &FindToolBar::invokeFindEnter, Qt::QueuedConnection);
+ connect(m_ui.replaceEdit, &Utils::FancyLineEdit::returnPressed,
+ this, &FindToolBar::invokeReplaceEnter, Qt::QueuedConnection);
QAction *shiftEnterAction = new QAction(m_ui.findEdit);
shiftEnterAction->setShortcut(QKeySequence(tr("Shift+Enter")));
shiftEnterAction->setShortcutContext(Qt::WidgetShortcut);
- connect(shiftEnterAction, SIGNAL(triggered()), this, SLOT(invokeFindPrevious()));
+ connect(shiftEnterAction, &QAction::triggered,
+ this, &FindToolBar::invokeFindPrevious);
m_ui.findEdit->addAction(shiftEnterAction);
QAction *shiftReturnAction = new QAction(m_ui.findEdit);
shiftReturnAction->setShortcut(QKeySequence(tr("Shift+Return")));
shiftReturnAction->setShortcutContext(Qt::WidgetShortcut);
- connect(shiftReturnAction, SIGNAL(triggered()), this, SLOT(invokeFindPrevious()));
+ connect(shiftReturnAction, &QAction::triggered,
+ this, &FindToolBar::invokeFindPrevious);
m_ui.findEdit->addAction(shiftReturnAction);
QAction *shiftEnterReplaceAction = new QAction(m_ui.replaceEdit);
shiftEnterReplaceAction->setShortcut(QKeySequence(tr("Shift+Enter")));
shiftEnterReplaceAction->setShortcutContext(Qt::WidgetShortcut);
- connect(shiftEnterReplaceAction, SIGNAL(triggered()), this, SLOT(invokeReplacePrevious()));
+ connect(shiftEnterReplaceAction, &QAction::triggered,
+ this, &FindToolBar::invokeReplacePrevious);
m_ui.replaceEdit->addAction(shiftEnterReplaceAction);
QAction *shiftReturnReplaceAction = new QAction(m_ui.replaceEdit);
shiftReturnReplaceAction->setShortcut(QKeySequence(tr("Shift+Return")));
shiftReturnReplaceAction->setShortcutContext(Qt::WidgetShortcut);
- connect(shiftReturnReplaceAction, SIGNAL(triggered()), this, SLOT(invokeReplacePrevious()));
+ connect(shiftReturnReplaceAction, &QAction::triggered,
+ this, &FindToolBar::invokeReplacePrevious);
m_ui.replaceEdit->addAction(shiftReturnReplaceAction);
// need to make sure QStringList is registered as metatype
QMetaTypeId<QStringList>::qt_metatype_id();
// register actions
- Core::Context globalcontext(Core::Constants::C_GLOBAL);
- Core::Context findcontext(Constants::C_FINDTOOLBAR);
- Core::ActionContainer *mfind = Core::ActionManager::actionContainer(Constants::M_FIND);
- Core::Command *cmd;
+ Context globalcontext(Constants::C_GLOBAL);
+ Context findcontext(Constants::C_FINDTOOLBAR);
+ ActionContainer *mfind = ActionManager::actionContainer(Constants::M_FIND);
+ Command *cmd;
- m_ui.advancedButton->setDefaultAction(Core::ActionManager::command(Constants::ADVANCED_FIND)->action());
+ m_ui.advancedButton->setDefaultAction(ActionManager::command(Constants::ADVANCED_FIND)->action());
m_goToCurrentFindAction = new QAction(this);
- Core::ActionManager::registerAction(m_goToCurrentFindAction, Constants::S_RETURNTOEDITOR,
+ ActionManager::registerAction(m_goToCurrentFindAction, Constants::S_RETURNTOEDITOR,
findcontext);
- connect(m_goToCurrentFindAction, SIGNAL(triggered()), this, SLOT(setFocusToCurrentFindSupport()));
+ connect(m_goToCurrentFindAction, &QAction::triggered,
+ this, &FindToolBar::setFocusToCurrentFindSupport);
QIcon icon = QIcon::fromTheme(QLatin1String("edit-find-replace"));
m_findInDocumentAction = new QAction(icon, tr("Find/Replace"), this);
- cmd = Core::ActionManager::registerAction(m_findInDocumentAction, Constants::FIND_IN_DOCUMENT, globalcontext);
+ cmd = ActionManager::registerAction(m_findInDocumentAction, Constants::FIND_IN_DOCUMENT, globalcontext);
cmd->setDefaultKeySequence(QKeySequence::Find);
mfind->addAction(cmd, Constants::G_FIND_CURRENTDOCUMENT);
connect(m_findInDocumentAction, SIGNAL(triggered()), this, SLOT(openFind()));
@@ -172,18 +182,18 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
if (QApplication::clipboard()->supportsFindBuffer()) {
m_enterFindStringAction = new QAction(tr("Enter Find String"), this);
- cmd = Core::ActionManager::registerAction(m_enterFindStringAction, "Find.EnterFindString", globalcontext);
+ cmd = ActionManager::registerAction(m_enterFindStringAction, "Find.EnterFindString", globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+E")));
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_enterFindStringAction, SIGNAL(triggered()), this, SLOT(putSelectionToFindClipboard()));
+ connect(m_enterFindStringAction, &QAction::triggered, this, &FindToolBar::putSelectionToFindClipboard);
connect(QApplication::clipboard(), SIGNAL(findBufferChanged()), this, SLOT(updateFromFindClipboard()));
}
m_findNextAction = new QAction(tr("Find Next"), this);
- cmd = Core::ActionManager::registerAction(m_findNextAction, Constants::FIND_NEXT, globalcontext);
+ cmd = ActionManager::registerAction(m_findNextAction, Constants::FIND_NEXT, globalcontext);
cmd->setDefaultKeySequence(QKeySequence::FindNext);
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_findNextAction, SIGNAL(triggered()), this, SLOT(invokeGlobalFindNext()));
+ connect(m_findNextAction, &QAction::triggered, this, &FindToolBar::invokeGlobalFindNext);
m_localFindNextAction = new QAction(m_findNextAction->text(), this);
cmd = ActionManager::registerAction(m_localFindNextAction, Constants::FIND_NEXT, findcontext);
cmd->augmentActionWithShortcutToolTip(m_localFindNextAction);
@@ -191,10 +201,10 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
m_ui.findNextButton->setDefaultAction(m_localFindNextAction);
m_findPreviousAction = new QAction(tr("Find Previous"), this);
- cmd = Core::ActionManager::registerAction(m_findPreviousAction, Constants::FIND_PREVIOUS, globalcontext);
+ cmd = ActionManager::registerAction(m_findPreviousAction, Constants::FIND_PREVIOUS, globalcontext);
cmd->setDefaultKeySequence(QKeySequence::FindPrevious);
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_findPreviousAction, SIGNAL(triggered()), this, SLOT(invokeGlobalFindPrevious()));
+ connect(m_findPreviousAction, &QAction::triggered, this, &FindToolBar::invokeGlobalFindPrevious);
m_localFindPreviousAction = new QAction(m_findPreviousAction->text(), this);
cmd = ActionManager::registerAction(m_localFindPreviousAction, Constants::FIND_PREVIOUS, findcontext);
cmd->augmentActionWithShortcutToolTip(m_localFindPreviousAction);
@@ -202,22 +212,22 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
m_ui.findPreviousButton->setDefaultAction(m_localFindPreviousAction);
m_findNextSelectedAction = new QAction(tr("Find Next (Selected)"), this);
- cmd = Core::ActionManager::registerAction(m_findNextSelectedAction, Constants::FIND_NEXT_SELECTED, globalcontext);
+ cmd = ActionManager::registerAction(m_findNextSelectedAction, Constants::FIND_NEXT_SELECTED, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+F3")));
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_findNextSelectedAction, SIGNAL(triggered()), this, SLOT(findNextSelected()));
+ connect(m_findNextSelectedAction, &QAction::triggered, this, &FindToolBar::findNextSelected);
m_findPreviousSelectedAction = new QAction(tr("Find Previous (Selected)"), this);
- cmd = Core::ActionManager::registerAction(m_findPreviousSelectedAction, Constants::FIND_PREV_SELECTED, globalcontext);
+ cmd = ActionManager::registerAction(m_findPreviousSelectedAction, Constants::FIND_PREV_SELECTED, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+F3")));
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_findPreviousSelectedAction, SIGNAL(triggered()), this, SLOT(findPreviousSelected()));
+ connect(m_findPreviousSelectedAction, &QAction::triggered, this, &FindToolBar::findPreviousSelected);
m_replaceAction = new QAction(tr("Replace"), this);
- cmd = Core::ActionManager::registerAction(m_replaceAction, Constants::REPLACE, globalcontext);
+ cmd = ActionManager::registerAction(m_replaceAction, Constants::REPLACE, globalcontext);
cmd->setDefaultKeySequence(QKeySequence());
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_replaceAction, SIGNAL(triggered()), this, SLOT(invokeGlobalReplace()));
+ connect(m_replaceAction, &QAction::triggered, this, &FindToolBar::invokeGlobalReplace);
m_localReplaceAction = new QAction(m_replaceAction->text(), this);
cmd = ActionManager::registerAction(m_localReplaceAction, Constants::REPLACE, findcontext);
cmd->augmentActionWithShortcutToolTip(m_localReplaceAction);
@@ -225,10 +235,10 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
m_ui.replaceButton->setDefaultAction(m_localReplaceAction);
m_replaceNextAction = new QAction(tr("Replace && Find"), this);
- cmd = Core::ActionManager::registerAction(m_replaceNextAction, Constants::REPLACE_NEXT, globalcontext);
+ cmd = ActionManager::registerAction(m_replaceNextAction, Constants::REPLACE_NEXT, globalcontext);
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+=")));
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_replaceNextAction, SIGNAL(triggered()), this, SLOT(invokeGlobalReplaceNext()));
+ connect(m_replaceNextAction, &QAction::triggered, this, &FindToolBar::invokeGlobalReplaceNext);
m_localReplaceNextAction = new QAction(m_replaceNextAction->text(), this);
m_localReplaceNextAction->setIconText(m_replaceNextAction->text()); // Workaround QTBUG-23396
cmd = ActionManager::registerAction(m_localReplaceNextAction, Constants::REPLACE_NEXT, findcontext);
@@ -237,18 +247,18 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
m_ui.replaceNextButton->setDefaultAction(m_localReplaceNextAction);
m_replacePreviousAction = new QAction(tr("Replace && Find Previous"), this);
- cmd = Core::ActionManager::registerAction(m_replacePreviousAction, Constants::REPLACE_PREVIOUS, globalcontext);
+ cmd = ActionManager::registerAction(m_replacePreviousAction, Constants::REPLACE_PREVIOUS, globalcontext);
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_replacePreviousAction, SIGNAL(triggered()), this, SLOT(invokeGlobalReplacePrevious()));
+ connect(m_replacePreviousAction, &QAction::triggered, this, &FindToolBar::invokeGlobalReplacePrevious);
m_localReplacePreviousAction = new QAction(m_replacePreviousAction->text(), this);
cmd = ActionManager::registerAction(m_localReplacePreviousAction, Constants::REPLACE_PREVIOUS, findcontext);
cmd->augmentActionWithShortcutToolTip(m_localReplacePreviousAction);
connect(m_localReplacePreviousAction, &QAction::triggered, this, &FindToolBar::invokeReplacePrevious);
m_replaceAllAction = new QAction(tr("Replace All"), this);
- cmd = Core::ActionManager::registerAction(m_replaceAllAction, Constants::REPLACE_ALL, globalcontext);
+ cmd = ActionManager::registerAction(m_replaceAllAction, Constants::REPLACE_ALL, globalcontext);
mfind->addAction(cmd, Constants::G_FIND_ACTIONS);
- connect(m_replaceAllAction, SIGNAL(triggered()), this, SLOT(invokeGlobalReplaceAll()));
+ connect(m_replaceAllAction, &QAction::triggered, this, &FindToolBar::invokeGlobalReplaceAll);
m_localReplaceAllAction = new QAction(m_replaceAllAction->text(), this);
cmd = ActionManager::registerAction(m_localReplaceAllAction, Constants::REPLACE_ALL, findcontext);
cmd->augmentActionWithShortcutToolTip(m_localReplaceAllAction);
@@ -259,48 +269,44 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
m_caseSensitiveAction->setIcon(QIcon(QLatin1String(":/find/images/casesensitively.png")));
m_caseSensitiveAction->setCheckable(true);
m_caseSensitiveAction->setChecked(false);
- cmd = Core::ActionManager::registerAction(m_caseSensitiveAction, Constants::CASE_SENSITIVE, globalcontext);
+ cmd = ActionManager::registerAction(m_caseSensitiveAction, Constants::CASE_SENSITIVE, globalcontext);
mfind->addAction(cmd, Constants::G_FIND_FLAGS);
- connect(m_caseSensitiveAction, SIGNAL(toggled(bool)), this, SLOT(setCaseSensitive(bool)));
+ connect(m_caseSensitiveAction, &QAction::toggled, this, &FindToolBar::setCaseSensitive);
m_wholeWordAction = new QAction(tr("Whole Words Only"), this);
m_wholeWordAction->setIcon(QIcon(QLatin1String(":/find/images/wholewords.png")));
m_wholeWordAction->setCheckable(true);
m_wholeWordAction->setChecked(false);
- cmd = Core::ActionManager::registerAction(m_wholeWordAction, Constants::WHOLE_WORDS, globalcontext);
+ cmd = ActionManager::registerAction(m_wholeWordAction, Constants::WHOLE_WORDS, globalcontext);
mfind->addAction(cmd, Constants::G_FIND_FLAGS);
- connect(m_wholeWordAction, SIGNAL(toggled(bool)), this, SLOT(setWholeWord(bool)));
+ connect(m_wholeWordAction, &QAction::toggled, this, &FindToolBar::setWholeWord);
m_regularExpressionAction = new QAction(tr("Use Regular Expressions"), this);
m_regularExpressionAction->setIcon(QIcon(QLatin1String(":/find/images/regexp.png")));
m_regularExpressionAction->setCheckable(true);
m_regularExpressionAction->setChecked(false);
- cmd = Core::ActionManager::registerAction(m_regularExpressionAction, Constants::REGULAR_EXPRESSIONS, globalcontext);
+ cmd = ActionManager::registerAction(m_regularExpressionAction, Constants::REGULAR_EXPRESSIONS, globalcontext);
mfind->addAction(cmd, Constants::G_FIND_FLAGS);
- connect(m_regularExpressionAction, SIGNAL(toggled(bool)), this, SLOT(setRegularExpressions(bool)));
+ connect(m_regularExpressionAction, &QAction::toggled, this, &FindToolBar::setRegularExpressions);
m_preserveCaseAction = new QAction(tr("Preserve Case when Replacing"), this);
m_preserveCaseAction->setIcon(QPixmap(QLatin1String(":/find/images/preservecase.png")));
m_preserveCaseAction->setCheckable(true);
m_preserveCaseAction->setChecked(false);
- cmd = Core::ActionManager::registerAction(m_preserveCaseAction, Constants::PRESERVE_CASE, globalcontext);
+ cmd = ActionManager::registerAction(m_preserveCaseAction, Constants::PRESERVE_CASE, globalcontext);
mfind->addAction(cmd, Constants::G_FIND_FLAGS);
- connect(m_preserveCaseAction, SIGNAL(toggled(bool)), this, SLOT(setPreserveCase(bool)));
-
- connect(m_currentDocumentFind, &CurrentDocumentFind::candidateChanged,
- this, &FindToolBar::adaptToCandidate);
- connect(m_currentDocumentFind, &CurrentDocumentFind::changed,
- this, &FindToolBar::updateGlobalActions);
- connect(m_currentDocumentFind, &CurrentDocumentFind::changed,
- this, &FindToolBar::updateToolBar);
+ connect(m_preserveCaseAction, &QAction::toggled, this, &FindToolBar::setPreserveCase);
+
+ connect(m_currentDocumentFind, &CurrentDocumentFind::candidateChanged, this, &FindToolBar::adaptToCandidate);
+ connect(m_currentDocumentFind, &CurrentDocumentFind::changed, this, &FindToolBar::updateGlobalActions);
+ connect(m_currentDocumentFind, &CurrentDocumentFind::changed, this, &FindToolBar::updateToolBar);
updateGlobalActions();
updateToolBar();
m_findIncrementalTimer.setSingleShot(true);
m_findStepTimer.setSingleShot(true);
- connect(&m_findIncrementalTimer, SIGNAL(timeout()),
- this, SLOT(invokeFindIncremental()));
- connect(&m_findStepTimer, SIGNAL(timeout()), this, SLOT(invokeFindStep()));
+ connect(&m_findIncrementalTimer, &QTimer::timeout, this, &FindToolBar::invokeFindIncremental);
+ connect(&m_findStepTimer, &QTimer::timeout, this, &FindToolBar::invokeFindStep);
}
FindToolBar::~FindToolBar()
@@ -363,9 +369,9 @@ bool FindToolBar::eventFilter(QObject *obj, QEvent *event)
void FindToolBar::adaptToCandidate()
{
updateGlobalActions();
- if (findToolBarPlaceHolder() == Core::FindToolBarPlaceHolder::getCurrent()) {
+ if (findToolBarPlaceHolder() == FindToolBarPlaceHolder::getCurrent()) {
m_currentDocumentFind->acceptCandidate();
- if (isVisible())
+ if (isVisible() && m_currentDocumentFind->isEnabled())
m_currentDocumentFind->highlightAll(getFindText(), effectiveFindFlags());
}
}
@@ -493,12 +499,14 @@ QString FindToolBar::getReplaceText()
void FindToolBar::setFindText(const QString &text)
{
- disconnect(m_ui.findEdit, SIGNAL(textChanged(QString)), this, SLOT(invokeFindIncremental()));
+ disconnect(m_ui.findEdit, &Utils::FancyLineEdit::textChanged,
+ this, &FindToolBar::invokeFindIncremental);
if (hasFindFlag(FindRegularExpression))
m_ui.findEdit->setText(QRegExp::escape(text));
else
m_ui.findEdit->setText(text);
- connect(m_ui.findEdit, SIGNAL(textChanged(QString)), this, SLOT(invokeFindIncremental()));
+ connect(m_ui.findEdit, &Utils::FancyLineEdit::textChanged,
+ this, &FindToolBar::invokeFindIncremental);
}
void FindToolBar::selectFindText()
@@ -647,7 +655,7 @@ void FindToolBar::updateIcons()
bool preserveCase = effectiveFlags & FindPreserveCase;
if (!casesensitive && !wholewords && !regexp && !preserveCase) {
m_ui.findEdit->setButtonPixmap(Utils::FancyLineEdit::Left,
- Utils::StyleHelper::dpiSpecificImageFile(QLatin1Literal(Core::Constants::ICON_MAGNIFIER)));
+ Utils::StyleHelper::dpiSpecificImageFile(QLatin1Literal(Constants::ICON_MAGNIFIER)));
} else {
m_ui.findEdit->setButtonPixmap(Utils::FancyLineEdit::Left,
IFindFilter::pixmapForFindFlags(effectiveFlags));
@@ -706,12 +714,12 @@ void FindToolBar::hideAndResetFocus()
hide();
}
-Core::FindToolBarPlaceHolder *FindToolBar::findToolBarPlaceHolder() const
+FindToolBarPlaceHolder *FindToolBar::findToolBarPlaceHolder() const
{
- QList<Core::FindToolBarPlaceHolder*> placeholders = ExtensionSystem::PluginManager::getObjects<Core::FindToolBarPlaceHolder>();
+ QList<FindToolBarPlaceHolder*> placeholders = ExtensionSystem::PluginManager::getObjects<FindToolBarPlaceHolder>();
QWidget *candidate = QApplication::focusWidget();
while (candidate) {
- foreach (Core::FindToolBarPlaceHolder *ph, placeholders) {
+ foreach (FindToolBarPlaceHolder *ph, placeholders) {
if (ph->owner() == candidate)
return ph;
}
@@ -778,15 +786,15 @@ void FindToolBar::openFind(bool focus)
void FindToolBar::openFindToolBar(OpenFlags flags)
{
installEventFilters();
- Core::FindToolBarPlaceHolder *holder = findToolBarPlaceHolder();
+ FindToolBarPlaceHolder *holder = findToolBarPlaceHolder();
if (!holder)
return;
- Core::FindToolBarPlaceHolder *previousHolder = Core::FindToolBarPlaceHolder::getCurrent();
+ FindToolBarPlaceHolder *previousHolder = FindToolBarPlaceHolder::getCurrent();
if (previousHolder != holder) {
if (previousHolder)
previousHolder->setWidget(0);
holder->setWidget(this);
- Core::FindToolBarPlaceHolder::setCurrent(holder);
+ FindToolBarPlaceHolder::setCurrent(holder);
}
m_currentDocumentFind->acceptCandidate();
holder->setVisible(true);
@@ -846,7 +854,7 @@ void FindToolBar::resizeEvent(QResizeEvent *event)
void FindToolBar::writeSettings()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String("Find"));
settings->beginGroup(QLatin1String("FindToolBar"));
settings->setValue(QLatin1String("Backward"), QVariant((m_findFlags & FindBackward) != 0));
@@ -860,7 +868,7 @@ void FindToolBar::writeSettings()
void FindToolBar::readSettings()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String("Find"));
settings->beginGroup(QLatin1String("FindToolBar"));
FindFlags flags;
@@ -930,8 +938,8 @@ void FindToolBar::setBackward(bool backward)
void FindToolBar::setLightColoredIcon(bool lightColored)
{
- m_ui.close->setIcon(lightColored ? QIcon(QLatin1String(Core::Constants::ICON_DARK_CLOSE))
- : QIcon(QLatin1String(Core::Constants::ICON_BUTTON_CLOSE)));
+ m_ui.close->setIcon(lightColored ? QIcon(QLatin1String(Constants::ICON_DARK_CLOSE))
+ : QIcon(QLatin1String(Constants::ICON_BUTTON_CLOSE)));
}
OptionsPopup::OptionsPopup(QWidget *parent)
@@ -994,8 +1002,11 @@ QCheckBox *OptionsPopup::createCheckboxForCommand(Id id)
checkbox->setChecked(action->isChecked());
checkbox->setEnabled(action->isEnabled());
checkbox->installEventFilter(this); // enter key handling
- QObject::connect(checkbox, SIGNAL(clicked(bool)), action, SLOT(setChecked(bool)));
- QObject::connect(action, SIGNAL(changed()), this, SLOT(actionChanged()));
+ QObject::connect(checkbox, &QCheckBox::clicked, action, &QAction::setChecked);
+ QObject::connect(action, &QAction::changed, this, &OptionsPopup::actionChanged);
m_checkboxMap.insert(action, checkbox);
return checkbox;
}
+
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/find/findtoolbar.h b/src/plugins/coreplugin/find/findtoolbar.h
index ba2b41c34c2..1ee63ac3e0b 100644
--- a/src/plugins/coreplugin/find/findtoolbar.h
+++ b/src/plugins/coreplugin/find/findtoolbar.h
@@ -148,7 +148,7 @@ private:
void setFindFlag(FindFlag flag, bool enabled);
bool hasFindFlag(FindFlag flag);
FindFlags effectiveFindFlags();
- Core::FindToolBarPlaceHolder *findToolBarPlaceHolder() const;
+ FindToolBarPlaceHolder *findToolBarPlaceHolder() const;
bool toolBarHasFocus() const;
bool canShowAllControls(bool replaceIsVisible) const;
void acceptCandidateAndMoveToolBar();
diff --git a/src/plugins/coreplugin/find/findtoolwindow.cpp b/src/plugins/coreplugin/find/findtoolwindow.cpp
index 469ea6cd135..0a00df7a304 100644
--- a/src/plugins/coreplugin/find/findtoolwindow.cpp
+++ b/src/plugins/coreplugin/find/findtoolwindow.cpp
@@ -244,7 +244,7 @@ void FindToolWindow::replace()
void FindToolWindow::writeSettings()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String("Find"));
settings->setValue(QLatin1String("CurrentFilter"), m_currentFilter ? m_currentFilter->id() : QString());
foreach (IFindFilter *filter, m_filters)
@@ -254,7 +254,7 @@ void FindToolWindow::writeSettings()
void FindToolWindow::readSettings()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String("Find"));
const QString currentFilter = settings->value(QLatin1String("CurrentFilter")).toString();
for (int i = 0; i < m_filters.size(); ++i) {
diff --git a/src/plugins/coreplugin/find/ifindsupport.cpp b/src/plugins/coreplugin/find/ifindsupport.cpp
index 62907e05483..87665ff4d0f 100644
--- a/src/plugins/coreplugin/find/ifindsupport.cpp
+++ b/src/plugins/coreplugin/find/ifindsupport.cpp
@@ -30,64 +30,7 @@
#include "ifindsupport.h"
-#include <QTimer>
-#include <QPropertyAnimation>
-#include <QWidget>
-#include <QPaintEvent>
-#include <QPainter>
-
-namespace Core {
-namespace Internal {
-
-class WrapIndicator : public QWidget
-{
- Q_OBJECT
- Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity USER true)
-
-public:
- WrapIndicator(QWidget *parent = 0)
- : QWidget(parent),
- m_opacity(1.0)
- {
- if (parent)
- setGeometry(QRect(parent->rect().center() - QPoint(25, 25),
- parent->rect().center() + QPoint(25, 25)));
- }
-
- qreal opacity() const { return m_opacity; }
- void setOpacity(qreal value) { m_opacity = value; update(); }
-
- void run()
- {
- show();
- QTimer::singleShot(300, this, SLOT(runInternal()));
- }
-
-protected:
- void paintEvent(QPaintEvent *)
- {
- static QPixmap foreground(QLatin1String(":/find/images/wrapindicator.png"));
- QPainter p(this);
- p.setOpacity(m_opacity);
- p.drawPixmap(rect(), foreground);
- }
-
-private slots:
- void runInternal()
- {
- QPropertyAnimation *anim = new QPropertyAnimation(this, "opacity", this);
- anim->setDuration(200);
- anim->setEndValue(0.);
- connect(anim, SIGNAL(finished()), this, SLOT(deleteLater()));
- anim->start(QAbstractAnimation::DeleteWhenStopped);
- }
-
-private:
- qreal m_opacity;
-};
-
-} // Internal
-} // Find
+#include <utils/fadingindicator.h>
using namespace Core;
@@ -116,7 +59,5 @@ int IFindSupport::replaceAll(const QString &before, const QString &after, FindFl
void IFindSupport::showWrapIndicator(QWidget *parent)
{
- (new Internal::WrapIndicator(parent))->run();
+ Utils::FadingIndicator::showPixmap(parent, QLatin1String(":/find/images/wrapindicator.png"));
}
-
-#include "ifindsupport.moc"
diff --git a/src/plugins/coreplugin/find/itemviewfind.cpp b/src/plugins/coreplugin/find/itemviewfind.cpp
index 603b5e88659..17b8b2cfd80 100644
--- a/src/plugins/coreplugin/find/itemviewfind.cpp
+++ b/src/plugins/coreplugin/find/itemviewfind.cpp
@@ -141,7 +141,7 @@ QFrame *ItemViewFind::createSearchableWrapper(QAbstractItemView *treeView, Color
vbox->setMargin(0);
vbox->setSpacing(0);
vbox->addWidget(treeView);
- auto placeHolder = new Core::FindToolBarPlaceHolder(widget);
+ auto placeHolder = new FindToolBarPlaceHolder(widget);
placeHolder->setLightColored(lightColored);
vbox->addWidget(placeHolder);
diff --git a/src/plugins/coreplugin/find/searchresulttreeview.cpp b/src/plugins/coreplugin/find/searchresulttreeview.cpp
index cceaee286a0..f1ba0b733e0 100644
--- a/src/plugins/coreplugin/find/searchresulttreeview.cpp
+++ b/src/plugins/coreplugin/find/searchresulttreeview.cpp
@@ -51,7 +51,8 @@ SearchResultTreeView::SearchResultTreeView(QWidget *parent)
setExpandsOnDoubleClick(true);
header()->hide();
- connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(emitJumpToSearchResult(QModelIndex)));
+ connect(this, &SearchResultTreeView::activated,
+ this, &SearchResultTreeView::emitJumpToSearchResult);
}
void SearchResultTreeView::setAutoExpandResults(bool expand)
diff --git a/src/plugins/coreplugin/find/searchresultwidget.cpp b/src/plugins/coreplugin/find/searchresultwidget.cpp
index d334ab62b8f..0ee63e7f919 100644
--- a/src/plugins/coreplugin/find/searchresultwidget.cpp
+++ b/src/plugins/coreplugin/find/searchresultwidget.cpp
@@ -205,7 +205,7 @@ SearchResultWidget::SearchResultWidget(QWidget *parent) :
SearchResultWidget::~SearchResultWidget()
{
- if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID)))
+ if (m_infoBar.containsInfo(Id(SIZE_WARNING_ID)))
cancelAfterSizeWarning();
}
@@ -240,10 +240,10 @@ void SearchResultWidget::addResults(const QList<SearchResultItem> &items, Search
updateMatchesFoundLabel();
if (firstItems) {
if (!m_dontAskAgainGroup.isEmpty()) {
- Core::Id undoWarningId = Core::Id("warninglabel/").withSuffix(m_dontAskAgainGroup);
+ Id undoWarningId = Id("warninglabel/").withSuffix(m_dontAskAgainGroup);
if (m_infoBar.canInfoBeAdded(undoWarningId)) {
- Core::InfoBarEntry info(undoWarningId, tr("This change cannot be undone."),
- Core::InfoBarEntry::GlobalSuppressionEnabled);
+ InfoBarEntry info(undoWarningId, tr("This change cannot be undone."),
+ InfoBarEntry::GlobalSuppressionEnabled);
m_infoBar.addInfo(info);
}
}
@@ -261,13 +261,13 @@ void SearchResultWidget::addResults(const QList<SearchResultItem> &items, Search
} else if (m_count <= SEARCHRESULT_WARNING_LIMIT) {
return;
} else {
- Core::Id sizeWarningId(SIZE_WARNING_ID);
+ Id sizeWarningId(SIZE_WARNING_ID);
if (!m_infoBar.canInfoBeAdded(sizeWarningId))
return;
emit paused(true);
- Core::InfoBarEntry info(sizeWarningId,
- tr("The search resulted in more than %n items, do you still want to continue?",
- 0, SEARCHRESULT_WARNING_LIMIT));
+ InfoBarEntry info(sizeWarningId,
+ tr("The search resulted in more than %n items, do you still want to continue?",
+ 0, SEARCHRESULT_WARNING_LIMIT));
info.setCancelButtonInfo(tr("Cancel"), [this]() { cancelAfterSizeWarning(); });
info.setCustomButtonInfo(tr("Continue"), [this]() { continueAfterSizeWarning(); });
m_infoBar.addInfo(info);
@@ -402,7 +402,7 @@ void SearchResultWidget::restart()
m_replaceButton->setEnabled(false);
m_searchResultTreeView->clear();
m_count = 0;
- Core::Id sizeWarningId(SIZE_WARNING_ID);
+ Id sizeWarningId(SIZE_WARNING_ID);
m_infoBar.removeInfo(sizeWarningId);
m_infoBar.enableInfo(sizeWarningId);
m_cancelButton->setVisible(true);
@@ -425,7 +425,7 @@ void SearchResultWidget::setSearchAgainEnabled(bool enabled)
void SearchResultWidget::finishSearch(bool canceled)
{
- Core::Id sizeWarningId(SIZE_WARNING_ID);
+ Id sizeWarningId(SIZE_WARNING_ID);
m_infoBar.removeInfo(sizeWarningId);
m_infoBar.enableInfo(sizeWarningId);
m_replaceTextEdit->setEnabled(m_count > 0);
@@ -443,13 +443,13 @@ void SearchResultWidget::sendRequestPopup()
void SearchResultWidget::continueAfterSizeWarning()
{
- m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID));
+ m_infoBar.suppressInfo(Id(SIZE_WARNING_ID));
emit paused(false);
}
void SearchResultWidget::cancelAfterSizeWarning()
{
- m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID));
+ m_infoBar.suppressInfo(Id(SIZE_WARNING_ID));
emit cancelled();
emit paused(false);
}
@@ -473,7 +473,7 @@ void SearchResultWidget::handleReplaceButton()
void SearchResultWidget::cancel()
{
m_cancelButton->setVisible(false);
- if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID)))
+ if (m_infoBar.containsInfo(Id(SIZE_WARNING_ID)))
cancelAfterSizeWarning();
else
emit cancelled();
diff --git a/src/plugins/coreplugin/find/searchresultwidget.h b/src/plugins/coreplugin/find/searchresultwidget.h
index 7d68bb94f07..6314f5e2ff2 100644
--- a/src/plugins/coreplugin/find/searchresultwidget.h
+++ b/src/plugins/coreplugin/find/searchresultwidget.h
@@ -129,8 +129,8 @@ private:
QString m_dontAskAgainGroup;
bool m_preserveCaseSupported;
QFrame *m_messageWidget;
- Core::InfoBar m_infoBar;
- Core::InfoBarDisplay m_infoBarDisplay;
+ InfoBar m_infoBar;
+ InfoBarDisplay m_infoBarDisplay;
bool m_isShowingReplaceUI;
QLabel *m_replaceLabel;
QLineEdit *m_replaceTextEdit;
diff --git a/src/plugins/coreplugin/find/searchresultwindow.cpp b/src/plugins/coreplugin/find/searchresultwindow.cpp
index e7f251163e1..db4dd1e4b75 100644
--- a/src/plugins/coreplugin/find/searchresultwindow.cpp
+++ b/src/plugins/coreplugin/find/searchresultwindow.cpp
@@ -190,10 +190,10 @@ namespace Internal {
QTC_ASSERT(widget, return);
int internalIndex = m_searchResultWidgets.indexOf(widget) + 1/*account for "new search" entry*/;
setCurrentIndex(internalIndex, focus);
- q->popup(focus ? Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus
- : Core::IOutputPane::NoModeSwitch);
+ q->popup(focus ? IOutputPane::ModeSwitch | IOutputPane::WithFocus
+ : IOutputPane::NoModeSwitch);
}
-}
+} // namespace Internal
using namespace Core::Internal;
@@ -307,10 +307,10 @@ SearchResultWindow::SearchResultWindow(QWidget *newSearchPanel)
d->m_expandCollapseAction = new QAction(tr("Expand All"), this);
d->m_expandCollapseAction->setCheckable(true);
d->m_expandCollapseAction->setIcon(QIcon(QLatin1String(":/find/images/expand.png")));
- Core::Command *cmd = Core::ActionManager::registerAction(
+ Command *cmd = ActionManager::registerAction(
d->m_expandCollapseAction, "Find.ExpandAll",
- Core::Context(Core::Constants::C_GLOBAL));
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ Context(Constants::C_GLOBAL));
+ cmd->setAttribute(Command::CA_UpdateText);
d->m_expandCollapseButton->setDefaultAction(cmd->action());
connect(d->m_expandCollapseAction, SIGNAL(toggled(bool)), this, SLOT(handleExpandCollapseToolButton(bool)));
@@ -535,7 +535,7 @@ void SearchResultWindow::handleExpandCollapseToolButton(bool checked)
*/
void SearchResultWindow::readSettings()
{
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
s->beginGroup(QLatin1String(SETTINGSKEYSECTIONNAME));
d->m_expandCollapseAction->setChecked(s->value(QLatin1String(SETTINGSKEYEXPANDRESULTS), d->m_initiallyExpand).toBool());
s->endGroup();
@@ -546,7 +546,7 @@ void SearchResultWindow::readSettings()
*/
void SearchResultWindow::writeSettings()
{
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
s->beginGroup(QLatin1String(SETTINGSKEYSECTIONNAME));
s->setValue(QLatin1String(SETTINGSKEYEXPANDRESULTS), d->m_expandCollapseAction->isChecked());
s->endGroup();
diff --git a/src/plugins/coreplugin/find/searchresultwindow.h b/src/plugins/coreplugin/find/searchresultwindow.h
index a2547dafa61..0155885b67f 100644
--- a/src/plugins/coreplugin/find/searchresultwindow.h
+++ b/src/plugins/coreplugin/find/searchresultwindow.h
@@ -128,7 +128,7 @@ private:
QVariant m_userData;
};
-class CORE_EXPORT SearchResultWindow : public Core::IOutputPane
+class CORE_EXPORT SearchResultWindow : public IOutputPane
{
Q_OBJECT
diff --git a/src/plugins/coreplugin/generalsettings.cpp b/src/plugins/coreplugin/generalsettings.cpp
index 7e13b15b0ce..8c31525d29b 100644
--- a/src/plugins/coreplugin/generalsettings.cpp
+++ b/src/plugins/coreplugin/generalsettings.cpp
@@ -60,11 +60,11 @@ namespace Internal {
GeneralSettings::GeneralSettings()
: m_page(0), m_dialog(0)
{
- setId(Core::Constants::SETTINGS_ID_ENVIRONMENT);
+ setId(Constants::SETTINGS_ID_ENVIRONMENT);
setDisplayName(tr("General"));
- setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
- setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
- setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
+ setCategory(Constants::SETTINGS_CATEGORY_CORE);
+ setDisplayCategory(QCoreApplication::translate("Core", Constants::SETTINGS_TR_CATEGORY_CORE));
+ setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CORE_ICON));
}
static bool hasQmFilesForLocale(const QString &locale, const QString &creatorTrPath)
diff --git a/src/plugins/coreplugin/helpmanager.cpp b/src/plugins/coreplugin/helpmanager.cpp
index 2da39c91a7a..02f794b96d6 100644
--- a/src/plugins/coreplugin/helpmanager.cpp
+++ b/src/plugins/coreplugin/helpmanager.cpp
@@ -33,6 +33,7 @@
#include <coreplugin/icore.h>
#include <utils/algorithm.h>
#include <utils/filesystemwatcher.h>
+#include <utils/qtcassert.h>
#include <QDateTime>
#include <QDebug>
@@ -47,6 +48,8 @@
#include <QSqlError>
#include <QSqlQuery>
+static const char kUserDocumentationKey[] = "Help/UserDocumentation";
+
namespace Core {
struct HelpManagerPrivate
@@ -56,14 +59,20 @@ struct HelpManagerPrivate
{}
QStringList documentationFromInstaller();
+ void readSettings();
+ void writeSettings();
+ void cleanUpDocumentation();
bool m_needsSetup;
QHelpEngineCore *m_helpEngine;
Utils::FileSystemWatcher *m_collectionWatcher;
- QStringList m_filesToRegister;
- QStringList m_nameSpacesToUnregister;
+ // data for delayed initialization
+ QSet<QString> m_filesToRegister;
+ QSet<QString> m_nameSpacesToUnregister;
QHash<QString, QVariant> m_customValues;
+
+ QSet<QString> m_userRegisteredFiles;
};
static HelpManager *m_instance = 0;
@@ -88,20 +97,21 @@ struct DbCleaner
HelpManager::HelpManager(QObject *parent) :
QObject(parent)
{
- Q_ASSERT(!m_instance);
+ QTC_CHECK(!m_instance);
m_instance = this;
d = new HelpManagerPrivate;
}
HelpManager::~HelpManager()
{
+ d->writeSettings();
delete d->m_helpEngine;
d->m_helpEngine = 0;
m_instance = 0;
delete d;
}
-QObject *HelpManager::instance()
+HelpManager *HelpManager::instance()
{
Q_ASSERT(m_instance);
return m_instance;
@@ -109,14 +119,15 @@ QObject *HelpManager::instance()
QString HelpManager::collectionFilePath()
{
- return QDir::cleanPath(Core::ICore::userResourcePath()
+ return QDir::cleanPath(ICore::userResourcePath()
+ QLatin1String("/helpcollection.qhc"));
}
void HelpManager::registerDocumentation(const QStringList &files)
{
if (d->m_needsSetup) {
- d->m_filesToRegister.append(files);
+ foreach (const QString &filePath, files)
+ d->m_filesToRegister.insert(filePath);
return;
}
@@ -153,17 +164,20 @@ void HelpManager::registerDocumentation(const QStringList &files)
void HelpManager::unregisterDocumentation(const QStringList &nameSpaces)
{
if (d->m_needsSetup) {
- d->m_nameSpacesToUnregister.append(nameSpaces);
+ foreach (const QString &name, nameSpaces)
+ d->m_nameSpacesToUnregister.insert(name);
return;
}
bool docsChanged = false;
foreach (const QString &nameSpace, nameSpaces) {
+ const QString filePath = d->m_helpEngine->documentationFileName(nameSpace);
if (d->m_helpEngine->unregisterDocumentation(nameSpace)) {
docsChanged = true;
+ d->m_userRegisteredFiles.remove(filePath);
} else {
qWarning() << "Error unregistering namespace '" << nameSpace
- << "' from file '" << d->m_helpEngine->documentationFileName(nameSpace)
+ << "' from file '" << filePath
<< "': " << d->m_helpEngine->error();
}
}
@@ -171,6 +185,18 @@ void HelpManager::unregisterDocumentation(const QStringList &nameSpaces)
emit m_instance->documentationChanged();
}
+void HelpManager::registerUserDocumentation(const QStringList &filePaths)
+{
+ foreach (const QString &filePath, filePaths)
+ d->m_userRegisteredFiles.insert(filePath);
+ registerDocumentation(filePaths);
+}
+
+QSet<QString> HelpManager::userDocumentationPaths()
+{
+ return d->m_userRegisteredFiles;
+}
+
static QUrl buildQUrl(const QString &ns, const QString &folder,
const QString &relFileName, const QString &anchor)
{
@@ -186,8 +212,7 @@ static QUrl buildQUrl(const QString &ns, const QString &folder,
QMap<QString, QUrl> HelpManager::linksForKeyword(const QString &key)
{
QMap<QString, QUrl> links;
- if (d->m_needsSetup)
- return links;
+ QTC_ASSERT(!d->m_needsSetup, return links);
const QLatin1String sqlite("QSQLITE");
const QLatin1String name("HelpManager::linksForKeyword");
@@ -218,68 +243,20 @@ QMap<QString, QUrl> HelpManager::linksForKeyword(const QString &key)
QMap<QString, QUrl> HelpManager::linksForIdentifier(const QString &id)
{
- if (d->m_needsSetup)
- return QMap<QString, QUrl>();
+ QMap<QString, QUrl> empty;
+ QTC_ASSERT(!d->m_needsSetup, return empty);
return d->m_helpEngine->linksForIdentifier(id);
}
-// This should go into Qt 4.8 once we start using it for Qt Creator
-QStringList HelpManager::findKeywords(const QString &key, Qt::CaseSensitivity caseSensitivity,
- int maxHits)
-{
- if (d->m_needsSetup)
- return QStringList();
-
- const QLatin1String sqlite("QSQLITE");
- const QLatin1String name("HelpManager::findKeywords");
-
- QSet<QString> keywords;
- QSet<QString> keywordsToSort;
-
- DbCleaner cleaner(name);
- QSqlDatabase db = QSqlDatabase::addDatabase(sqlite, name);
- if (db.driver() && db.driver()->lastError().type() == QSqlError::NoError) {
- QHelpEngineCore core(collectionFilePath());
- core.setAutoSaveFilter(false);
- core.setCurrentFilter(tr("Unfiltered"));
- core.setupData();
- const QStringList &registeredDocs = core.registeredDocumentations();
- foreach (const QString &nameSpace, registeredDocs) {
- db.setDatabaseName(core.documentationFileName(nameSpace));
- if (db.open()) {
- QSqlQuery query = QSqlQuery(db);
- query.setForwardOnly(true);
- query.exec(QString::fromLatin1("SELECT DISTINCT Name FROM IndexTable WHERE Name LIKE "
- "'%%1%' LIMIT %2").arg(key, QString::number(maxHits)));
- while (query.next()) {
- const QString &keyValue = query.value(0).toString();
- if (!keyValue.isEmpty()) {
- if (keyValue.startsWith(key, caseSensitivity))
- keywordsToSort.insert(keyValue);
- else
- keywords.insert(keyValue);
- }
- }
- }
- }
- }
-
- QStringList keywordsSorted = keywordsToSort.toList();
- Utils::sort(keywordsSorted);
- return keywordsSorted + keywords.toList();
-}
-
QUrl HelpManager::findFile(const QUrl &url)
{
- if (d->m_needsSetup)
- return QUrl();
+ QTC_ASSERT(!d->m_needsSetup, return QUrl());
return d->m_helpEngine->findFile(url);
}
QByteArray HelpManager::fileData(const QUrl &url)
{
- if (d->m_needsSetup)
- return QByteArray();
+ QTC_ASSERT(!d->m_needsSetup, return QByteArray());
return d->m_helpEngine->fileData(url);
}
@@ -295,22 +272,19 @@ void HelpManager::handleHelpRequest(const QString &url, HelpViewerLocation locat
QStringList HelpManager::registeredNamespaces()
{
- if (d->m_needsSetup)
- return QStringList();
+ QTC_ASSERT(!d->m_needsSetup, return QStringList());
return d->m_helpEngine->registeredDocumentations();
}
QString HelpManager::namespaceFromFile(const QString &file)
{
- if (d->m_needsSetup)
- return QString();
+ QTC_ASSERT(!d->m_needsSetup, return QString());
return d->m_helpEngine->namespaceName(file);
}
QString HelpManager::fileFromNamespace(const QString &nameSpace)
{
- if (d->m_needsSetup)
- return QString();
+ QTC_ASSERT(!d->m_needsSetup, return QString());
return d->m_helpEngine->documentationFileName(nameSpace);
}
@@ -326,15 +300,13 @@ void HelpManager::setCustomValue(const QString &key, const QVariant &value)
QVariant HelpManager::customValue(const QString &key, const QVariant &value)
{
- if (d->m_needsSetup)
- return QVariant();
+ QTC_ASSERT(!d->m_needsSetup, return QVariant());
return d->m_helpEngine->customValue(key, value);
}
HelpManager::Filters HelpManager::filters()
{
- if (d->m_needsSetup)
- return Filters();
+ QTC_ASSERT(!d->m_needsSetup, return Filters());
Filters filters;
const QStringList &customFilters = d->m_helpEngine->customFilters();
@@ -346,8 +318,7 @@ HelpManager::Filters HelpManager::filters()
HelpManager::Filters HelpManager::fixedFilters()
{
Filters fixedFilters;
- if (d->m_needsSetup)
- return fixedFilters;
+ QTC_ASSERT(!d->m_needsSetup, return fixedFilters);
const QLatin1String sqlite("QSQLITE");
const QLatin1String name("HelpManager::fixedCustomFilters");
@@ -374,8 +345,7 @@ HelpManager::Filters HelpManager::fixedFilters()
HelpManager::Filters HelpManager::userDefinedFilters()
{
- if (d->m_needsSetup)
- return Filters();
+ QTC_ASSERT(!d->m_needsSetup, return Filters());
Filters all = filters();
const Filters &fixed = fixedFilters();
@@ -386,8 +356,7 @@ HelpManager::Filters HelpManager::userDefinedFilters()
void HelpManager::removeUserDefinedFilter(const QString &filter)
{
- if (d->m_needsSetup)
- return;
+ QTC_ASSERT(!d->m_needsSetup, return);
if (d->m_helpEngine->removeCustomFilter(filter))
emit m_instance->collectionFileChanged();
@@ -395,8 +364,7 @@ void HelpManager::removeUserDefinedFilter(const QString &filter)
void HelpManager::addUserDefinedFilter(const QString &filter, const QStringList &attr)
{
- if (d->m_needsSetup)
- return;
+ QTC_ASSERT(!d->m_needsSetup, return);
if (d->m_helpEngine->addCustomFilter(filter, attr))
emit m_instance->collectionFileChanged();
@@ -410,21 +378,26 @@ void HelpManager::setupHelpManager()
return;
d->m_needsSetup = false;
+ d->readSettings();
+
+ // create the help engine
d->m_helpEngine = new QHelpEngineCore(collectionFilePath(), m_instance);
d->m_helpEngine->setAutoSaveFilter(false);
d->m_helpEngine->setCurrentFilter(tr("Unfiltered"));
d->m_helpEngine->setupData();
- verifyDocumenation();
+
+ foreach (const QString &filePath, d->documentationFromInstaller())
+ d->m_filesToRegister.insert(filePath);
+
+ d->cleanUpDocumentation();
if (!d->m_nameSpacesToUnregister.isEmpty()) {
- unregisterDocumentation(d->m_nameSpacesToUnregister);
+ unregisterDocumentation(d->m_nameSpacesToUnregister.toList());
d->m_nameSpacesToUnregister.clear();
}
- d->m_filesToRegister << d->documentationFromInstaller();
-
if (!d->m_filesToRegister.isEmpty()) {
- registerDocumentation(d->m_filesToRegister);
+ registerDocumentation(d->m_filesToRegister.toList());
d->m_filesToRegister.clear();
}
@@ -437,18 +410,24 @@ void HelpManager::setupHelpManager()
// -- private
-void HelpManager::verifyDocumenation()
+void HelpManagerPrivate::cleanUpDocumentation()
{
- const QStringList &registeredDocs = d->m_helpEngine->registeredDocumentations();
+ // mark documentation for removal for which there is no documentation file anymore
+ // mark documentation for removal that is neither user registered, nor marked for registration
+ const QStringList &registeredDocs = m_helpEngine->registeredDocumentations();
foreach (const QString &nameSpace, registeredDocs) {
- if (!QFileInfo::exists(d->m_helpEngine->documentationFileName(nameSpace)))
- d->m_nameSpacesToUnregister.append(nameSpace);
+ const QString filePath = m_helpEngine->documentationFileName(nameSpace);
+ if (!QFileInfo::exists(filePath)
+ || (!m_filesToRegister.contains(filePath)
+ && !m_userRegisteredFiles.contains(filePath))) {
+ m_nameSpacesToUnregister.insert(nameSpace);
+ }
}
}
QStringList HelpManagerPrivate::documentationFromInstaller()
{
- QSettings *installSettings = Core::ICore::settings();
+ QSettings *installSettings = ICore::settings();
QStringList documentationPaths = installSettings->value(QLatin1String("Help/InstalledDocumentation"))
.toStringList();
QStringList documentationFiles;
@@ -467,4 +446,16 @@ QStringList HelpManagerPrivate::documentationFromInstaller()
return documentationFiles;
}
+void HelpManagerPrivate::readSettings()
+{
+ m_userRegisteredFiles = ICore::settings()->value(QLatin1String(kUserDocumentationKey))
+ .toStringList().toSet();
+}
+
+void HelpManagerPrivate::writeSettings()
+{
+ const QStringList list = m_userRegisteredFiles.toList();
+ ICore::settings()->setValue(QLatin1String(kUserDocumentationKey), list);
+}
+
} // Core
diff --git a/src/plugins/coreplugin/helpmanager.h b/src/plugins/coreplugin/helpmanager.h
index da01c46e2f3..cf843eae5d1 100644
--- a/src/plugins/coreplugin/helpmanager.h
+++ b/src/plugins/coreplugin/helpmanager.h
@@ -63,17 +63,17 @@ public:
typedef QHash<QString, QStringList> Filters;
- static QObject *instance();
+ static HelpManager *instance();
static QString collectionFilePath();
static void registerDocumentation(const QStringList &fileNames);
static void unregisterDocumentation(const QStringList &nameSpaces);
+ static void registerUserDocumentation(const QStringList &filePaths);
+ static QSet<QString> userDocumentationPaths();
+
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);
static QUrl findFile(const QUrl &url);
static QByteArray fileData(const QUrl &url);
@@ -109,7 +109,6 @@ private:
~HelpManager();
static void setupHelpManager();
- static void verifyDocumenation();
friend class Core::Internal::CorePlugin; // setupHelpManager
friend class Core::Internal::MainWindow; // constructor/destructor
};
diff --git a/src/plugins/coreplugin/icore.cpp b/src/plugins/coreplugin/icore.cpp
index f6c7c59ec52..a60db0d7222 100644
--- a/src/plugins/coreplugin/icore.cpp
+++ b/src/plugins/coreplugin/icore.cpp
@@ -323,7 +323,7 @@ ICore::ICore(MainWindow *mainwindow)
m_instance = this;
m_mainwindow = mainwindow;
// Save settings once after all plugins are initialized:
- connect(ExtensionSystem::PluginManager::instance(), SIGNAL(initializationDone()),
+ connect(PluginManager::instance(), SIGNAL(initializationDone()),
this, SLOT(saveSettings()));
connect(m_mainwindow, SIGNAL(newItemDialogRunningChanged()),
this, SIGNAL(newItemDialogRunningChanged()));
diff --git a/src/plugins/coreplugin/idocument.cpp b/src/plugins/coreplugin/idocument.cpp
index e9cda916053..075f13c2382 100644
--- a/src/plugins/coreplugin/idocument.cpp
+++ b/src/plugins/coreplugin/idocument.cpp
@@ -32,6 +32,7 @@
#include "infobar.h"
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QFile>
@@ -62,29 +63,57 @@
namespace Core {
+namespace Internal {
+
+class IDocumentPrivate
+{
+public:
+ IDocumentPrivate() :
+ infoBar(0),
+ temporary(false),
+ hasWriteWarning(false),
+ restored(false)
+ {
+ }
+
+ ~IDocumentPrivate()
+ {
+ delete infoBar;
+ }
+
+ QString mimeType;
+ Utils::FileName filePath;
+ QString displayName;
+ QString autoSaveName;
+ InfoBar *infoBar;
+ Id id;
+ bool temporary;
+ bool hasWriteWarning;
+ bool restored;
+};
+
+} // namespace Internal
+
IDocument::IDocument(QObject *parent) : QObject(parent),
- m_temporary(false),
- m_infoBar(0),
- m_hasWriteWarning(false),
- m_restored(false)
+ d(new Internal::IDocumentPrivate)
{
}
IDocument::~IDocument()
{
removeAutoSaveFile();
- delete m_infoBar;
+ delete d;
}
void IDocument::setId(Id id)
{
- m_id = id;
+ d->id = id;
}
Id IDocument::id() const
{
- QTC_CHECK(m_id.isValid());
- return m_id;
+ QTC_CHECK(d->id.isValid());
+ return d->id;
}
/*!
@@ -99,6 +128,11 @@ bool IDocument::setContents(const QByteArray &contents)
return false;
}
+Utils::FileName IDocument::filePath() const
+{
+ return d->filePath;
+}
+
IDocument::ReloadBehavior IDocument::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
if (type == TypePermissions)
@@ -121,7 +155,7 @@ bool IDocument::isFileReadOnly() const
{
if (filePath().isEmpty())
return false;
- return !QFileInfo(filePath()).isWritable();
+ return !filePath().toFileInfo().isWritable();
}
/*!
@@ -131,7 +165,7 @@ bool IDocument::isFileReadOnly() const
*/
bool IDocument::isTemporary() const
{
- return m_temporary;
+ return d->temporary;
}
/*!
@@ -140,13 +174,18 @@ bool IDocument::isTemporary() const
*/
void IDocument::setTemporary(bool temporary)
{
- m_temporary = temporary;
+ d->temporary = temporary;
+}
+
+QString IDocument::mimeType() const
+{
+ return d->mimeType;
}
void IDocument::setMimeType(const QString &mimeType)
{
- if (m_mimeType != mimeType) {
- m_mimeType = mimeType;
+ if (d->mimeType != mimeType) {
+ d->mimeType = mimeType;
emit mimeTypeChanged();
}
}
@@ -155,7 +194,7 @@ bool IDocument::autoSave(QString *errorString, const QString &fileName)
{
if (!save(errorString, fileName, true))
return false;
- m_autoSaveName = fileName;
+ d->autoSaveName = fileName;
return true;
}
@@ -163,8 +202,8 @@ static const char kRestoredAutoSave[] = "RestoredAutoSave";
void IDocument::setRestoredFrom(const QString &name)
{
- m_autoSaveName = name;
- m_restored = true;
+ d->autoSaveName = name;
+ d->restored = true;
InfoBarEntry info(Id(kRestoredAutoSave),
tr("File was restored from auto-saved copy. "
"Select Save to confirm or Revert to Saved to discard changes."));
@@ -173,21 +212,31 @@ void IDocument::setRestoredFrom(const QString &name)
void IDocument::removeAutoSaveFile()
{
- if (!m_autoSaveName.isEmpty()) {
- QFile::remove(m_autoSaveName);
- m_autoSaveName.clear();
- if (m_restored) {
- m_restored = false;
+ if (!d->autoSaveName.isEmpty()) {
+ QFile::remove(d->autoSaveName);
+ d->autoSaveName.clear();
+ if (d->restored) {
+ d->restored = false;
infoBar()->removeInfo(Id(kRestoredAutoSave));
}
}
}
+bool IDocument::hasWriteWarning() const
+{
+ return d->hasWriteWarning;
+}
+
+void IDocument::setWriteWarning(bool has)
+{
+ d->hasWriteWarning = has;
+}
+
InfoBar *IDocument::infoBar()
{
- if (!m_infoBar)
- m_infoBar = new InfoBar;
- return m_infoBar;
+ if (!d->infoBar)
+ d->infoBar = new InfoBar;
+ return d->infoBar;
}
/*!
@@ -196,13 +245,13 @@ InfoBar *IDocument::infoBar()
signals. Can be reimplemented by subclasses to do more.
\sa filePath()
*/
-void IDocument::setFilePath(const QString &filePath)
+void IDocument::setFilePath(const Utils::FileName &filePath)
{
- if (m_filePath == filePath)
+ if (d->filePath == filePath)
return;
- QString oldName = m_filePath;
- m_filePath = filePath;
- emit filePathChanged(oldName, m_filePath);
+ Utils::FileName oldName = d->filePath;
+ d->filePath = filePath;
+ emit filePathChanged(oldName, d->filePath);
emit changed();
}
@@ -213,9 +262,9 @@ void IDocument::setFilePath(const QString &filePath)
*/
QString IDocument::displayName() const
{
- if (!m_displayName.isEmpty())
- return m_displayName;
- return QFileInfo(m_filePath).fileName();
+ if (!d->displayName.isEmpty())
+ return d->displayName;
+ return d->filePath.fileName();
}
/*!
@@ -227,9 +276,9 @@ QString IDocument::displayName() const
*/
void IDocument::setDisplayName(const QString &name)
{
- if (name == m_displayName)
+ if (name == d->displayName)
return;
- m_displayName = name;
+ d->displayName = name;
emit changed();
}
diff --git a/src/plugins/coreplugin/idocument.h b/src/plugins/coreplugin/idocument.h
index ee267f69242..0f19eb8a94f 100644
--- a/src/plugins/coreplugin/idocument.h
+++ b/src/plugins/coreplugin/idocument.h
@@ -34,6 +34,8 @@
#include "core_global.h"
#include "id.h"
+#include <utils/fileutils.h>
+
#include <QObject>
namespace Core {
@@ -41,6 +43,10 @@ namespace Core {
class MimeType;
class InfoBar;
+namespace Internal {
+class IDocumentPrivate;
+}
+
class CORE_EXPORT IDocument : public QObject
{
Q_OBJECT
@@ -78,14 +84,14 @@ public:
IDocument(QObject *parent = 0);
virtual ~IDocument();
- void setId(Core::Id id);
- Core::Id id() const;
+ void setId(Id id);
+ Id id() const;
virtual bool save(QString *errorString, const QString &fileName = QString(), bool autoSave = false) = 0;
virtual bool setContents(const QByteArray &contents);
- QString filePath() const { return m_filePath; }
- virtual void setFilePath(const QString &filePath);
+ Utils::FileName filePath() const;
+ virtual void setFilePath(const Utils::FileName &filePath);
QString displayName() const;
void setDisplayName(const QString &name);
@@ -96,7 +102,7 @@ public:
virtual QString defaultPath() const = 0;
virtual QString suggestedFileName() const = 0;
- QString mimeType() const { return m_mimeType; }
+ QString mimeType() const;
void setMimeType(const QString &mimeType);
virtual bool shouldAutoSave() const;
@@ -112,8 +118,8 @@ public:
void setRestoredFrom(const QString &name);
void removeAutoSaveFile();
- bool hasWriteWarning() const { return m_hasWriteWarning; }
- void setWriteWarning(bool has) { m_hasWriteWarning = has; }
+ bool hasWriteWarning() const;
+ void setWriteWarning(bool has);
InfoBar *infoBar();
@@ -124,18 +130,10 @@ signals:
void aboutToReload();
void reloadFinished(bool success);
- void filePathChanged(const QString &oldName, const QString &newName);
+ void filePathChanged(const Utils::FileName &oldName, const Utils::FileName &newName);
private:
- Id m_id;
- QString m_mimeType;
- QString m_filePath;
- QString m_displayName;
- bool m_temporary;
- QString m_autoSaveName;
- InfoBar *m_infoBar;
- bool m_hasWriteWarning;
- bool m_restored;
+ Internal::IDocumentPrivate *d;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/infobar.cpp b/src/plugins/coreplugin/infobar.cpp
index aa9bee33bd1..eb982a3a7db 100644
--- a/src/plugins/coreplugin/infobar.cpp
+++ b/src/plugins/coreplugin/infobar.cpp
@@ -248,7 +248,7 @@ void InfoBarDisplay::update()
if (info.cancelButtonText.isEmpty()) {
infoWidgetCloseButton->setAutoRaise(true);
- infoWidgetCloseButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_CLEAR)));
+ infoWidgetCloseButton->setIcon(QIcon(QLatin1String(Constants::ICON_CLEAR)));
infoWidgetCloseButton->setToolTip(tr("Close"));
if (infoWidgetSuppressButton)
hbox->addWidget(infoWidgetSuppressButton);
diff --git a/src/plugins/coreplugin/iversioncontrol.h b/src/plugins/coreplugin/iversioncontrol.h
index e2a5be7fc86..d47619777e6 100644
--- a/src/plugins/coreplugin/iversioncontrol.h
+++ b/src/plugins/coreplugin/iversioncontrol.h
@@ -56,10 +56,8 @@ public:
AddOperation, DeleteOperation, MoveOperation,
CreateRepositoryOperation,
SnapshotOperations,
- AnnotateOperation,
- CheckoutOperation,
- GetRepositoryRootOperation
- };
+ AnnotateOperation
+ };
enum OpenSupportMode {
NoOpen, /*!< Files can be edited without noticing the VCS */
@@ -78,8 +76,9 @@ public:
virtual QString refreshTopic(const QString &repository) = 0;
private:
- struct TopicData
+ class TopicData
{
+ public:
QDateTime timeStamp;
QString topic;
};
@@ -170,16 +169,6 @@ public:
virtual bool vcsCreateRepository(const QString &directory) = 0;
/*!
- * Called to clone/checkout the version control system in a directory.
- */
- virtual bool vcsCheckout(const QString &directory, const QByteArray &url) = 0;
-
- /*!
- * Called to get the version control repository root.
- */
- virtual QString vcsGetRepositoryURL(const QString &directory) = 0;
-
- /*!
* Topic (e.g. name of the current branch)
*/
virtual QString vcsTopic(const QString &topLevel);
@@ -228,7 +217,7 @@ class CORE_EXPORT TestVersionControl : public IVersionControl
{
Q_OBJECT
public:
- TestVersionControl(Core::Id id, const QString &name) :
+ TestVersionControl(Id id, const QString &name) :
m_id(id), m_displayName(name), m_dirCount(0), m_fileCount(0)
{ }
~TestVersionControl();
@@ -251,8 +240,6 @@ public:
bool vcsDelete(const QString &) { return false; }
bool vcsMove(const QString &, const QString &) { return false; }
bool vcsCreateRepository(const QString &) { return false; }
- bool vcsCheckout(const QString &, const QByteArray &) { return false; }
- QString vcsGetRepositoryURL(const QString &) { return QString(); }
bool vcsAnnotate(const QString &, int) { return false; }
private:
diff --git a/src/libs/utils/iwelcomepage.cpp b/src/plugins/coreplugin/iwelcomepage.cpp
index c5b781fe918..3e449afc277 100644
--- a/src/libs/utils/iwelcomepage.cpp
+++ b/src/plugins/coreplugin/iwelcomepage.cpp
@@ -32,7 +32,7 @@
#include <QUrl>
-namespace Utils {
+namespace Core {
IWelcomePage::IWelcomePage()
{
@@ -43,5 +43,3 @@ IWelcomePage::~IWelcomePage()
}
} // namespace Utils
-
-#include "moc_iwelcomepage.cpp"
diff --git a/src/libs/utils/iwelcomepage.h b/src/plugins/coreplugin/iwelcomepage.h
index e98afadbc43..508dc1e7f4c 100644
--- a/src/libs/utils/iwelcomepage.h
+++ b/src/plugins/coreplugin/iwelcomepage.h
@@ -31,16 +31,18 @@
#ifndef IWELCOMEPAGE_H
#define IWELCOMEPAGE_H
-#include "utils_global.h"
+#include "core_global.h"
+
+#include "id.h"
#include <QObject>
+#include <QUrl>
-QT_FORWARD_DECLARE_CLASS(QUrl)
QT_FORWARD_DECLARE_CLASS(QQmlEngine)
-namespace Utils {
+namespace Core {
-class QTCREATOR_UTILS_EXPORT IWelcomePage : public QObject
+class CORE_EXPORT IWelcomePage : public QObject
{
Q_OBJECT
@@ -50,14 +52,6 @@ class QTCREATOR_UTILS_EXPORT IWelcomePage : public QObject
Q_PROPERTY(bool hasSearchBar READ hasSearchBar CONSTANT)
public:
- enum Id {
- GettingStarted = 0,
- Develop = 1,
- Examples = 2,
- Tutorials = 3,
- UserDefined = 32
- };
-
IWelcomePage();
virtual ~IWelcomePage();
@@ -66,9 +60,9 @@ public:
virtual int priority() const { return 0; }
virtual void facilitateQml(QQmlEngine *) {}
virtual bool hasSearchBar() const { return false; }
- virtual Id id() const = 0;
+ virtual Core::Id id() const = 0;
};
-}
+} // Core
#endif // IWELCOMEPAGE_H
diff --git a/src/plugins/coreplugin/iwizardfactory.cpp b/src/plugins/coreplugin/iwizardfactory.cpp
index 15477c23ae4..4262b4abc53 100644
--- a/src/plugins/coreplugin/iwizardfactory.cpp
+++ b/src/plugins/coreplugin/iwizardfactory.cpp
@@ -193,7 +193,7 @@ bool IWizardFactory::isAvailable(const QString &platformName) const
{
FeatureSet availableFeatures = pluginFeatures();
- foreach (const Core::IFeatureProvider *featureManager, s_providerList)
+ foreach (const IFeatureProvider *featureManager, s_providerList)
availableFeatures |= featureManager->availableFeatures(platformName);
return availableFeatures.contains(requiredFeatures());
@@ -215,7 +215,7 @@ QStringList IWizardFactory::allAvailablePlatforms()
{
QStringList platforms;
- foreach (const Core::IFeatureProvider *featureManager, s_providerList)
+ foreach (const IFeatureProvider *featureManager, s_providerList)
platforms.append(featureManager->availablePlatforms());
return platforms;
@@ -223,7 +223,7 @@ QStringList IWizardFactory::allAvailablePlatforms()
QString IWizardFactory::displayNameForPlatform(const QString &string)
{
- foreach (const Core::IFeatureProvider *featureManager, s_providerList) {
+ foreach (const IFeatureProvider *featureManager, s_providerList) {
QString displayName = featureManager->displayNameForPlatform(string);
if (!displayName.isEmpty())
return displayName;
diff --git a/src/plugins/coreplugin/iwizardfactory.h b/src/plugins/coreplugin/iwizardfactory.h
index 0ac2cc1f645..4c0d6b32a98 100644
--- a/src/plugins/coreplugin/iwizardfactory.h
+++ b/src/plugins/coreplugin/iwizardfactory.h
@@ -101,7 +101,7 @@ public:
static void registerFeatureProvider(IFeatureProvider *provider);
protected:
- Core::FeatureSet pluginFeatures() const;
+ FeatureSet pluginFeatures() const;
private:
static void destroyFeatureProvider();
diff --git a/src/plugins/coreplugin/locator/basefilefilter.cpp b/src/plugins/coreplugin/locator/basefilefilter.cpp
index c73200429cf..30ff691ea0d 100644
--- a/src/plugins/coreplugin/locator/basefilefilter.cpp
+++ b/src/plugins/coreplugin/locator/basefilefilter.cpp
@@ -32,20 +32,70 @@
#include <coreplugin/editormanager/editormanager.h>
#include <utils/fileutils.h>
+#include <utils/qtcassert.h>
#include <QDir>
#include <QStringMatcher>
+#include <QTimer>
using namespace Core;
-using namespace Core;
using namespace Utils;
+namespace Core {
+namespace Internal {
+
+class Data
+{
+public:
+ void clear()
+ {
+ iterator.clear();
+ previousResultPaths.clear();
+ previousResultNames.clear();
+ previousEntry.clear();
+ }
+
+ QSharedPointer<BaseFileFilter::Iterator> iterator;
+ QStringList previousResultPaths;
+ QStringList previousResultNames;
+ bool forceNewSearchList;
+ QString previousEntry;
+};
+
+class BaseFileFilterPrivate
+{
+public:
+ Data m_data;
+ Data m_current;
+};
+
+} // Internal
+} // Core
+
BaseFileFilter::BaseFileFilter()
- : m_forceNewSearchList(false)
+ : d(new Internal::BaseFileFilterPrivate)
+{
+ d->m_data.forceNewSearchList = true;
+ setFileIterator(new ListIterator(QStringList()));
+}
+
+BaseFileFilter::~BaseFileFilter()
{
+ delete d;
}
-QList<LocatorFilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &origEntry)
+void BaseFileFilter::prepareSearch(const QString &entry)
+{
+ Q_UNUSED(entry)
+ d->m_current.iterator = d->m_data.iterator;
+ d->m_current.previousResultPaths = d->m_data.previousResultPaths;
+ d->m_current.previousResultNames = d->m_data.previousResultNames;
+ d->m_current.forceNewSearchList = d->m_data.forceNewSearchList;
+ d->m_current.previousEntry = d->m_data.previousEntry;
+ d->m_data.forceNewSearchList = false;
+}
+
+QList<LocatorFilterEntry> BaseFileFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &origEntry)
{
QList<LocatorFilterEntry> betterEntries;
QList<LocatorFilterEntry> goodEntries;
@@ -54,37 +104,39 @@ QList<LocatorFilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Core::Loca
QStringMatcher matcher(needle, Qt::CaseInsensitive);
const QChar asterisk = QLatin1Char('*');
QRegExp regexp(asterisk + needle+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard);
- if (!regexp.isValid())
+ if (!regexp.isValid()) {
+ d->m_current.clear(); // free memory
return betterEntries;
+ }
const QChar pathSeparator(QLatin1Char('/'));
const bool hasPathSeparator = needle.contains(pathSeparator);
const bool hasWildcard = needle.contains(asterisk) || needle.contains(QLatin1Char('?'));
- QStringList searchListPaths;
- QStringList searchListNames;
- const bool containsPreviousEntry = !m_previousEntry.isEmpty()
- && needle.contains(m_previousEntry);
- const bool pathSeparatorAdded = !m_previousEntry.contains(pathSeparator)
+ const bool containsPreviousEntry = !d->m_current.previousEntry.isEmpty()
+ && needle.contains(d->m_current.previousEntry);
+ const bool pathSeparatorAdded = !d->m_current.previousEntry.contains(pathSeparator)
&& needle.contains(pathSeparator);
- if (!m_forceNewSearchList && containsPreviousEntry && !pathSeparatorAdded) {
- searchListPaths = m_previousResultPaths;
- searchListNames = m_previousResultNames;
- } else {
- searchListPaths = m_files;
- searchListNames = m_fileNames;
- }
- m_previousResultPaths.clear();
- m_previousResultNames.clear();
- m_forceNewSearchList = false;
- m_previousEntry = needle;
+ const bool searchInPreviousResults = !d->m_current.forceNewSearchList && containsPreviousEntry
+ && !pathSeparatorAdded;
+ if (searchInPreviousResults)
+ d->m_current.iterator.reset(new ListIterator(d->m_current.previousResultPaths,
+ d->m_current.previousResultNames));
+
+ QTC_ASSERT(d->m_current.iterator.data(), return QList<LocatorFilterEntry>());
+ d->m_current.previousResultPaths.clear();
+ d->m_current.previousResultNames.clear();
+ d->m_current.previousEntry = needle;
const Qt::CaseSensitivity caseSensitivityForPrefix = caseSensitivity(needle);
- QStringListIterator paths(searchListPaths);
- QStringListIterator names(searchListNames);
- while (paths.hasNext() && names.hasNext()) {
- if (future.isCanceled())
+ d->m_current.iterator->toFront();
+ bool canceled = false;
+ while (d->m_current.iterator->hasNext()) {
+ if (future.isCanceled()) {
+ canceled = true;
break;
+ }
- QString path = paths.next();
- QString name = names.next();
+ d->m_current.iterator->next();
+ QString path = d->m_current.iterator->filePath();
+ QString name = d->m_current.iterator->fileName();
QString matchText = hasPathSeparator ? path : name;
if ((hasWildcard && regexp.exactMatch(matchText))
|| (!hasWildcard && matcher.indexIn(matchText) != -1)) {
@@ -96,27 +148,106 @@ QList<LocatorFilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Core::Loca
betterEntries.append(entry);
else
goodEntries.append(entry);
- m_previousResultPaths.append(path);
- m_previousResultNames.append(name);
+ d->m_current.previousResultPaths.append(path);
+ d->m_current.previousResultNames.append(name);
}
}
betterEntries.append(goodEntries);
+ if (canceled) {
+ // we keep the old list of previous search results if this search was canceled
+ // so a later search without foreNewSearchList will use that previous list instead of an
+ // incomplete list of a canceled search
+ d->m_current.clear(); // free memory
+ } else {
+ d->m_current.iterator.clear();
+ QTimer::singleShot(0, this, SLOT(updatePreviousResultData()));
+ }
return betterEntries;
}
-void BaseFileFilter::accept(Core::LocatorFilterEntry selection) const
+void BaseFileFilter::accept(LocatorFilterEntry selection) const
{
EditorManager::openEditor(selection.internalData.toString(), Id(),
EditorManager::CanContainLineNumber);
}
-void BaseFileFilter::generateFileNames()
+/*!
+ Takes ownership of the \a iterator. The previously set iterator might not be deleted until
+ a currently running search is finished.
+*/
+
+void BaseFileFilter::setFileIterator(BaseFileFilter::Iterator *iterator)
+{
+ d->m_data.clear();
+ d->m_data.forceNewSearchList = true;
+ d->m_data.iterator.reset(iterator);
+}
+
+QSharedPointer<BaseFileFilter::Iterator> BaseFileFilter::fileIterator()
+{
+ return d->m_data.iterator;
+}
+
+void BaseFileFilter::updatePreviousResultData()
+{
+ if (d->m_data.forceNewSearchList) // in the meantime the iterator was reset / cache invalidated
+ return; // do not update with the new result list etc
+ d->m_data.previousEntry = d->m_current.previousEntry;
+ d->m_data.previousResultPaths = d->m_current.previousResultPaths;
+ d->m_data.previousResultNames = d->m_current.previousResultNames;
+ // forceNewSearchList was already reset in prepareSearch
+}
+
+BaseFileFilter::ListIterator::ListIterator(const QStringList &filePaths)
{
- m_fileNames.clear();
- foreach (const QString &fileName, m_files) {
- QFileInfo fi(fileName);
+ m_filePaths = filePaths;
+ foreach (const QString &path, m_filePaths) {
+ QFileInfo fi(path);
m_fileNames.append(fi.fileName());
}
- m_forceNewSearchList = true;
+ toFront();
+}
+
+BaseFileFilter::ListIterator::ListIterator(const QStringList &filePaths,
+ const QStringList &fileNames)
+{
+ m_filePaths = filePaths;
+ m_fileNames = fileNames;
+ toFront();
+}
+
+void BaseFileFilter::ListIterator::toFront()
+{
+ m_pathPosition = m_filePaths.constBegin() - 1;
+ m_namePosition = m_fileNames.constBegin() - 1;
+}
+
+bool BaseFileFilter::ListIterator::hasNext() const
+{
+ QTC_ASSERT(m_pathPosition != m_filePaths.constEnd(), return false);
+ return m_pathPosition + 1 != m_filePaths.constEnd();
+}
+
+QString BaseFileFilter::ListIterator::next()
+{
+ QTC_ASSERT(m_pathPosition != m_filePaths.constEnd(), return QString());
+ QTC_ASSERT(m_namePosition != m_fileNames.constEnd(), return QString());
+ ++m_pathPosition;
+ ++m_namePosition;
+ QTC_ASSERT(m_pathPosition != m_filePaths.constEnd(), return QString());
+ QTC_ASSERT(m_namePosition != m_fileNames.constEnd(), return QString());
+ return *m_pathPosition;
+}
+
+QString BaseFileFilter::ListIterator::filePath() const
+{
+ QTC_ASSERT(m_pathPosition != m_filePaths.constEnd(), return QString());
+ return *m_pathPosition;
+}
+
+QString BaseFileFilter::ListIterator::fileName() const
+{
+ QTC_ASSERT(m_namePosition != m_fileNames.constEnd(), return QString());
+ return *m_namePosition;
}
diff --git a/src/plugins/coreplugin/locator/basefilefilter.h b/src/plugins/coreplugin/locator/basefilefilter.h
index 052d26f2229..fefc6a1d39a 100644
--- a/src/plugins/coreplugin/locator/basefilefilter.h
+++ b/src/plugins/coreplugin/locator/basefilefilter.h
@@ -33,34 +33,61 @@
#include "ilocatorfilter.h"
+#include <QSharedPointer>
#include <QStringList>
namespace Core {
-class CORE_EXPORT BaseFileFilter : public Core::ILocatorFilter
+namespace Internal { class BaseFileFilterPrivate; }
+
+class CORE_EXPORT BaseFileFilter : public ILocatorFilter
{
Q_OBJECT
public:
+ class Iterator {
+ public:
+ virtual ~Iterator() { }
+ virtual void toFront() = 0;
+ virtual bool hasNext() const = 0;
+ virtual QString next() = 0;
+ virtual QString filePath() const = 0;
+ virtual QString fileName() const = 0;
+ };
+
+ class CORE_EXPORT ListIterator : public Iterator {
+ public:
+ ListIterator(const QStringList &filePaths);
+ ListIterator(const QStringList &filePaths, const QStringList &fileNames);
+
+ void toFront();
+ bool hasNext() const;
+ QString next();
+ QString filePath() const;
+ QString fileName() const;
+
+ private:
+ QStringList m_filePaths;
+ QStringList m_fileNames;
+ QStringList::const_iterator m_pathPosition;
+ QStringList::const_iterator m_namePosition;
+ };
+
BaseFileFilter();
- QList<Core::LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry);
- void accept(Core::LocatorFilterEntry selection) const;
+ ~BaseFileFilter();
+ void prepareSearch(const QString &entry);
+ QList<LocatorFilterEntry> matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry);
+ void accept(LocatorFilterEntry selection) const;
protected:
- /* Generates the file names from the list of file paths in m_files. */
- void generateFileNames();
+ void setFileIterator(Iterator *iterator);
+ QSharedPointer<Iterator> fileIterator();
- /* Subclasses should update the file list latest in their prepareSearch method. */
- inline QStringList &files() { return m_files; }
- inline const QStringList &files() const { return m_files; }
+private slots:
+ void updatePreviousResultData();
private:
- QStringList m_files;
- QStringList m_fileNames;
- QStringList m_previousResultPaths;
- QStringList m_previousResultNames;
- bool m_forceNewSearchList;
- QString m_previousEntry;
+ Internal::BaseFileFilterPrivate *d;
};
} // namespace Core
diff --git a/src/plugins/coreplugin/locator/commandlocator.cpp b/src/plugins/coreplugin/locator/commandlocator.cpp
index 5b6ebbc741d..611d56f9746 100644
--- a/src/plugins/coreplugin/locator/commandlocator.cpp
+++ b/src/plugins/coreplugin/locator/commandlocator.cpp
@@ -40,14 +40,14 @@ namespace Core {
struct CommandLocatorPrivate
{
- QList<Core::Command *> commands;
+ QList<Command *> commands;
};
-CommandLocator::CommandLocator(Core::Id id,
+CommandLocator::CommandLocator(Id id,
const QString &displayName,
const QString &shortCutString,
QObject *parent) :
- Core::ILocatorFilter(parent),
+ ILocatorFilter(parent),
d(new CommandLocatorPrivate)
{
setId(id);
@@ -60,12 +60,12 @@ CommandLocator::~CommandLocator()
delete d;
}
-void CommandLocator::appendCommand(Core::Command *cmd)
+void CommandLocator::appendCommand(Command *cmd)
{
d->commands.push_back(cmd);
}
-QList<Core::LocatorFilterEntry> CommandLocator::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry)
+QList<LocatorFilterEntry> CommandLocator::matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry)
{
QList<LocatorFilterEntry> goodEntries;
QList<LocatorFilterEntry> betterEntries;
@@ -93,7 +93,7 @@ QList<Core::LocatorFilterEntry> CommandLocator::matchesFor(QFutureInterface<Core
return betterEntries;
}
-void CommandLocator::accept(Core::LocatorFilterEntry entry) const
+void CommandLocator::accept(LocatorFilterEntry entry) const
{
// Retrieve action via index.
const int index = entry.internalData.toInt();
diff --git a/src/plugins/coreplugin/locator/commandlocator.h b/src/plugins/coreplugin/locator/commandlocator.h
index b40a3a90e02..ddbabe5148b 100644
--- a/src/plugins/coreplugin/locator/commandlocator.h
+++ b/src/plugins/coreplugin/locator/commandlocator.h
@@ -40,18 +40,18 @@ namespace Core {
class Command;
struct CommandLocatorPrivate;
-class CORE_EXPORT CommandLocator : public Core::ILocatorFilter
+class CORE_EXPORT CommandLocator : public ILocatorFilter
{
Q_OBJECT
public:
- CommandLocator(Core::Id id, const QString &displayName,
+ CommandLocator(Id id, const QString &displayName,
const QString &shortCutString, QObject *parent = 0);
~CommandLocator();
- void appendCommand(Core::Command *cmd);
+ void appendCommand(Command *cmd);
- QList<LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry);
+ QList<LocatorFilterEntry> matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry);
void accept(LocatorFilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/coreplugin/locator/directoryfilter.cpp b/src/plugins/coreplugin/locator/directoryfilter.cpp
index 004b55766e8..019c99033bf 100644
--- a/src/plugins/coreplugin/locator/directoryfilter.cpp
+++ b/src/plugins/coreplugin/locator/directoryfilter.cpp
@@ -30,9 +30,11 @@
#include "directoryfilter.h"
-#include <QFileDialog>
#include <utils/filesearch.h>
+#include <QFileDialog>
+#include <QTimer>
+
using namespace Core;
using namespace Core::Internal;
@@ -59,7 +61,7 @@ QByteArray DirectoryFilter::saveState() const
out << m_filters;
out << shortcutString();
out << isIncludedByDefault();
- out << files();
+ out << m_files;
return value;
}
@@ -77,13 +79,13 @@ bool DirectoryFilter::restoreState(const QByteArray &state)
in >> m_filters;
in >> shortcut;
in >> defaultFilter;
- in >> files();
+ in >> m_files;
setDisplayName(name);
setShortcutString(shortcut);
setIncludedByDefault(defaultFilter);
- generateFileNames();
+ updateFileIterator();
return true;
}
@@ -94,14 +96,14 @@ bool DirectoryFilter::openConfigDialog(QWidget *parent, bool &needsRefresh)
m_dialog = &dialog;
m_ui.setupUi(&dialog);
dialog.setWindowTitle(tr("Filter Configuration"));
- connect(m_ui.addButton, SIGNAL(clicked()),
- this, SLOT(addDirectory()), Qt::DirectConnection);
- connect(m_ui.editButton, SIGNAL(clicked()),
- this, SLOT(editDirectory()), Qt::DirectConnection);
- connect(m_ui.removeButton, SIGNAL(clicked()),
- this, SLOT(removeDirectory()), Qt::DirectConnection);
- connect(m_ui.directoryList, SIGNAL(itemSelectionChanged()),
- this, SLOT(updateOptionButtons()), Qt::DirectConnection);
+ connect(m_ui.addButton, &QPushButton::clicked,
+ this, &DirectoryFilter::addDirectory, Qt::DirectConnection);
+ connect(m_ui.editButton, &QPushButton::clicked,
+ this, &DirectoryFilter::editDirectory, Qt::DirectConnection);
+ connect(m_ui.removeButton, &QPushButton::clicked,
+ this, &DirectoryFilter::removeDirectory, Qt::DirectConnection);
+ connect(m_ui.directoryList, &QListWidget::itemSelectionChanged,
+ this, &DirectoryFilter::updateOptionButtons, Qt::DirectConnection);
m_ui.nameEdit->setText(displayName());
m_ui.nameEdit->selectAll();
m_ui.directoryList->clear();
@@ -169,14 +171,19 @@ void DirectoryFilter::updateOptionButtons()
m_ui.removeButton->setEnabled(haveSelectedItem);
}
+void DirectoryFilter::updateFileIterator()
+{
+ setFileIterator(new BaseFileFilter::ListIterator(m_files));
+}
+
void DirectoryFilter::refresh(QFutureInterface<void> &future)
{
QStringList directories;
{
QMutexLocker locker(&m_lock);
if (m_directories.count() < 1) {
- files().clear();
- generateFileNames();
+ m_files.clear();
+ QTimer::singleShot(0, this, SLOT(updateFileIterator()));
future.setProgressRange(0, 1);
future.setProgressValueAndText(1, tr("%1 filter update: 0 files").arg(displayName()));
return;
@@ -197,8 +204,8 @@ void DirectoryFilter::refresh(QFutureInterface<void> &future)
if (!future.isCanceled()) {
QMutexLocker locker(&m_lock);
- files() = filesFound;
- generateFileNames();
+ m_files = filesFound;
+ QTimer::singleShot(0, this, SLOT(updateFileIterator()));
future.setProgressValue(it.maxProgress());
} else {
future.setProgressValueAndText(it.currentProgress(), tr("%1 filter update: canceled").arg(displayName()));
diff --git a/src/plugins/coreplugin/locator/directoryfilter.h b/src/plugins/coreplugin/locator/directoryfilter.h
index 4343df2a228..ce4ceaace88 100644
--- a/src/plugins/coreplugin/locator/directoryfilter.h
+++ b/src/plugins/coreplugin/locator/directoryfilter.h
@@ -47,7 +47,7 @@ class DirectoryFilter : public BaseFileFilter
Q_OBJECT
public:
- DirectoryFilter(Core::Id id);
+ DirectoryFilter(Id id);
QByteArray saveState() const;
bool restoreState(const QByteArray &state);
bool openConfigDialog(QWidget *parent, bool &needsRefresh);
@@ -58,6 +58,7 @@ private slots:
void editDirectory();
void removeDirectory();
void updateOptionButtons();
+ void updateFileIterator();
private:
QStringList m_directories;
@@ -67,6 +68,7 @@ private:
QDialog *m_dialog;
Ui::DirectoryFilterOptions m_ui;
mutable QMutex m_lock;
+ QStringList m_files;
};
} // namespace Internal
diff --git a/src/plugins/coreplugin/locator/executefilter.cpp b/src/plugins/coreplugin/locator/executefilter.cpp
index 75afecd4436..9da02f19e95 100644
--- a/src/plugins/coreplugin/locator/executefilter.cpp
+++ b/src/plugins/coreplugin/locator/executefilter.cpp
@@ -44,6 +44,7 @@ ExecuteFilter::ExecuteFilter()
setId("Execute custom commands");
setDisplayName(tr("Execute Custom Commands"));
setShortcutString(QString(QLatin1Char('!')));
+ setPriority(High);
setIncludedByDefault(false);
m_process = new Utils::QtcProcess(this);
@@ -57,7 +58,7 @@ ExecuteFilter::ExecuteFilter()
connect(&m_runTimer, SIGNAL(timeout()), this, SLOT(runHeadCommand()));
}
-QList<LocatorFilterEntry> ExecuteFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future,
+QList<LocatorFilterEntry> ExecuteFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future,
const QString &entry)
{
QList<LocatorFilterEntry> value;
diff --git a/src/plugins/coreplugin/locator/executefilter.h b/src/plugins/coreplugin/locator/executefilter.h
index 55a5dcee922..70587570577 100644
--- a/src/plugins/coreplugin/locator/executefilter.h
+++ b/src/plugins/coreplugin/locator/executefilter.h
@@ -55,9 +55,9 @@ class ExecuteFilter : public Core::ILocatorFilter
public:
ExecuteFilter();
- QList<Core::LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future,
- const QString &entry);
- void accept(Core::LocatorFilterEntry selection) const;
+ QList<LocatorFilterEntry> matchesFor(QFutureInterface<LocatorFilterEntry> &future,
+ const QString &entry);
+ void accept(LocatorFilterEntry selection) const;
void refresh(QFutureInterface<void> &) {}
private slots:
diff --git a/src/plugins/coreplugin/locator/filesystemfilter.cpp b/src/plugins/coreplugin/locator/filesystemfilter.cpp
index 91ce18cf15d..310414b4829 100644
--- a/src/plugins/coreplugin/locator/filesystemfilter.cpp
+++ b/src/plugins/coreplugin/locator/filesystemfilter.cpp
@@ -69,14 +69,15 @@ void FileSystemFilter::prepareSearch(const QString &entry)
Q_UNUSED(entry)
IDocument *document= EditorManager::currentDocument();
if (document && !document->filePath().isEmpty()) {
- QFileInfo info(document->filePath());
+ const QFileInfo info = document->filePath().toFileInfo();
m_currentDocumentDirectory = info.absolutePath() + QLatin1Char('/');
} else {
m_currentDocumentDirectory.clear();
}
}
-QList<LocatorFilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry)
+QList<LocatorFilterEntry> FileSystemFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future,
+ const QString &entry)
{
QList<LocatorFilterEntry> goodEntries;
QList<LocatorFilterEntry> betterEntries;
diff --git a/src/plugins/coreplugin/locator/filesystemfilter.h b/src/plugins/coreplugin/locator/filesystemfilter.h
index 8acdf21e439..587725f7f2d 100644
--- a/src/plugins/coreplugin/locator/filesystemfilter.h
+++ b/src/plugins/coreplugin/locator/filesystemfilter.h
@@ -44,15 +44,15 @@ namespace Internal {
class LocatorWidget;
-class FileSystemFilter : public Core::ILocatorFilter
+class FileSystemFilter : public ILocatorFilter
{
Q_OBJECT
public:
explicit FileSystemFilter(LocatorWidget *locatorWidget);
void prepareSearch(const QString &entry);
- QList<Core::LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry);
- void accept(Core::LocatorFilterEntry selection) const;
+ QList<LocatorFilterEntry> matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry);
+ void accept(LocatorFilterEntry selection) const;
QByteArray saveState() const;
bool restoreState(const QByteArray &state);
bool openConfigDialog(QWidget *parent, bool &needsRefresh);
diff --git a/src/plugins/coreplugin/locator/ilocatorfilter.cpp b/src/plugins/coreplugin/locator/ilocatorfilter.cpp
index 735c269efc7..ae93a8afb99 100644
--- a/src/plugins/coreplugin/locator/ilocatorfilter.cpp
+++ b/src/plugins/coreplugin/locator/ilocatorfilter.cpp
@@ -106,8 +106,8 @@ bool ILocatorFilter::openConfigDialog(QWidget *parent, bool &needsRefresh)
QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok |
QDialogButtonBox::Cancel);
- connect(buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
- connect(buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
+ connect(buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
+ connect(buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
vlayout->addLayout(hlayout);
vlayout->addStretch();
@@ -173,7 +173,7 @@ bool ILocatorFilter::isEnabled() const
return m_enabled;
}
-Core::Id ILocatorFilter::id() const
+Id ILocatorFilter::id() const
{
return m_id;
}
@@ -193,7 +193,7 @@ void ILocatorFilter::setEnabled(bool enabled)
m_enabled = enabled;
}
-void ILocatorFilter::setId(Core::Id id)
+void ILocatorFilter::setId(Id id)
{
m_id = id;
}
diff --git a/src/plugins/coreplugin/locator/ilocatorfilter.h b/src/plugins/coreplugin/locator/ilocatorfilter.h
index 251959d3f2f..4919715ed0e 100644
--- a/src/plugins/coreplugin/locator/ilocatorfilter.h
+++ b/src/plugins/coreplugin/locator/ilocatorfilter.h
@@ -84,13 +84,13 @@ class CORE_EXPORT ILocatorFilter : public QObject
Q_OBJECT
public:
- enum Priority {High = 0, Medium = 1, Low = 2};
+ enum Priority {Highest = 0, High = 1, Medium = 2, Low = 3};
ILocatorFilter(QObject *parent = 0);
virtual ~ILocatorFilter() {}
/* Internal Id. */
- Core::Id id() const;
+ Id id() const;
/* Visible name. */
QString displayName() const;
@@ -108,7 +108,7 @@ public:
/* List of matches for the given user entry. This runs in a separate thread, but only
a single thread at a time. */
- virtual QList<LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry) = 0;
+ virtual QList<LocatorFilterEntry> matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry) = 0;
/* User has selected the given entry that belongs to this filter. */
virtual void accept(LocatorFilterEntry selection) const = 0;
@@ -153,13 +153,13 @@ protected:
void setShortcutString(const QString &shortcut);
void setIncludedByDefault(bool includedByDefault);
void setHidden(bool hidden);
- void setId(Core::Id id);
+ void setId(Id id);
void setPriority(Priority priority);
void setDisplayName(const QString &displayString);
void setConfigurable(bool configurable);
private:
- Core::Id m_id;
+ Id m_id;
QString m_shortcut;
Priority m_priority;
QString m_displayName;
diff --git a/src/plugins/coreplugin/locator/locator.cpp b/src/plugins/coreplugin/locator/locator.cpp
index b35b702c0b7..f0b60c6ef6e 100644
--- a/src/plugins/coreplugin/locator/locator.cpp
+++ b/src/plugins/coreplugin/locator/locator.cpp
@@ -35,7 +35,7 @@
#include "locatorwidget.h"
#include "opendocumentsfilter.h"
#include "filesystemfilter.h"
-#include "settingspage.h"
+#include "locatorsettingspage.h"
#include <coreplugin/coreplugin.h>
#include <coreplugin/statusbarwidget.h>
@@ -44,6 +44,8 @@
#include <coreplugin/icore.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/editormanager_p.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <extensionsystem/pluginmanager.h>
@@ -84,7 +86,7 @@ void Locator::initialize(CorePlugin *corePlugin, const QStringList &, QString *)
{
m_corePlugin = corePlugin;
- m_settingsPage = new SettingsPage(this);
+ m_settingsPage = new LocatorSettingsPage(this);
m_corePlugin->addObject(m_settingsPage);
m_locatorWidget = new LocatorWidget(this);
@@ -96,14 +98,14 @@ void Locator::initialize(CorePlugin *corePlugin, const QStringList &, QString *)
m_corePlugin->addAutoReleasedObject(view);
QAction *action = new QAction(m_locatorWidget->windowIcon(), m_locatorWidget->windowTitle(), this);
- Command *cmd = ActionManager::registerAction(action, "QtCreator.Locate",
- Context(Core::Constants::C_GLOBAL));
+ Command *cmd = ActionManager::registerAction(action, Constants::LOCATE,
+ Context(Constants::C_GLOBAL));
cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+K")));
- connect(action, SIGNAL(triggered()), this, SLOT(openLocator()));
+ connect(action, &QAction::triggered, this, &Locator::openLocator);
connect(cmd, SIGNAL(keySequenceChanged()), this, SLOT(updatePlaceholderText()));
updatePlaceholderText(cmd);
- ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
+ ActionContainer *mtools = ActionManager::actionContainer(Constants::M_TOOLS);
mtools->addAction(cmd);
m_corePlugin->addObject(new LocatorManager(m_locatorWidget));
@@ -148,6 +150,14 @@ void Locator::extensionsInitialized()
return first->id().alphabeticallyBefore(second->id());
});
setFilters(m_filters);
+
+ Command *openCommand = ActionManager::command(Constants::OPEN);
+ Command *locateCommand = ActionManager::command(Constants::LOCATE);
+ connect(openCommand, &Command::keySequenceChanged,
+ this, &Locator::updateEditorManagerPlaceholderText);
+ connect(locateCommand, &Command::keySequenceChanged,
+ this, &Locator::updateEditorManagerPlaceholderText);
+ updateEditorManagerPlaceholderText();
}
bool Locator::delayedInitialize()
@@ -177,6 +187,50 @@ void Locator::loadSettings()
m_settingsInitialized = true;
}
+void Locator::updateEditorManagerPlaceholderText()
+{
+ Command *openCommand = ActionManager::command(Constants::OPEN);
+ Command *locateCommand = ActionManager::command(Constants::LOCATE);
+ const QString placeholderText = tr("<html><body style=\"color:#909090; font-size:14px\">"
+ "<div align='center'>"
+ "<div style=\"font-size:20px\">Open a document</div>"
+ "<table><tr><td>"
+ "<hr/>"
+ "<div style=\"margin-top: 5px\">&bull; File > Open File or Project (%1)</div>"
+ "<div style=\"margin-top: 5px\">&bull; File > Recent Files</div>"
+ "<div style=\"margin-top: 5px\">&bull; Tools > Locate (%2) and</div>"
+ "<div style=\"margin-left: 1em\">- type to open file from any open project</div>"
+ "%4"
+ "%5"
+ "<div style=\"margin-left: 1em\">- type <code>%3&lt;space&gt;&lt;filename&gt;</code> to open file from file system</div>"
+ "<div style=\"margin-left: 1em\">- select one of the other filters for jumping to a location</div>"
+ "<div style=\"margin-top: 5px\">&bull; Drag and drop files here</div>"
+ "</td></tr></table>"
+ "</div>"
+ "</body></html>")
+ .arg(openCommand->keySequence().toString(QKeySequence::NativeText))
+ .arg(locateCommand->keySequence().toString(QKeySequence::NativeText))
+ .arg(m_fileSystemFilter->shortcutString());
+
+ QString classes;
+ ILocatorFilter *classesFilter = Utils::findOrDefault(m_filters, [](const ILocatorFilter *filter) {
+ return filter->id() == Id("Classes"); // not nice, but anyhow
+ });
+ if (classesFilter)
+ classes = tr("<div style=\"margin-left: 1em\">- type <code>%1&lt;space&gt;&lt;pattern&gt;</code>"
+ " to jump to a class definition</div>").arg(classesFilter->shortcutString());
+
+ QString methods;
+ ILocatorFilter *methodsFilter = Utils::findOrDefault(m_filters, [](const ILocatorFilter *filter) {
+ return filter->id() == Id("Methods"); // not nice, but anyhow
+ });
+ if (methodsFilter)
+ methods = tr("<div style=\"margin-left: 1em\">- type <code>%1&lt;space&gt;&lt;pattern&gt;</code>"
+ " to jump to a function definition</div>").arg(methodsFilter->shortcutString());
+
+ EditorManagerPrivate::setPlaceholderText(placeholderText.arg(classes, methods));
+}
+
void Locator::saveSettings()
{
if (m_settingsInitialized) {
@@ -222,6 +276,7 @@ QList<ILocatorFilter *> Locator::customFilters()
void Locator::setFilters(QList<ILocatorFilter *> f)
{
m_filters = f;
+ updateEditorManagerPlaceholderText(); // possibly some shortcut changed
m_locatorWidget->updateFilterList();
}
@@ -252,8 +307,8 @@ void Locator::refresh(QList<ILocatorFilter *> filters)
filters = m_filters;
QFuture<void> task = QtConcurrent::run(&ILocatorFilter::refresh, filters);
FutureProgress *progress =
- ProgressManager::addTask(task, tr("Updating Locator Caches"), Core::Constants::TASK_INDEX);
- connect(progress, SIGNAL(finished()), this, SLOT(saveSettings()));
+ ProgressManager::addTask(task, tr("Updating Locator Caches"), Constants::TASK_INDEX);
+ connect(progress, &FutureProgress::finished, this, &Locator::saveSettings);
}
} // namespace Internal
diff --git a/src/plugins/coreplugin/locator/locator.h b/src/plugins/coreplugin/locator/locator.h
index a56bf7d77c6..6c115be7eb6 100644
--- a/src/plugins/coreplugin/locator/locator.h
+++ b/src/plugins/coreplugin/locator/locator.h
@@ -49,7 +49,7 @@ class CorePlugin;
class LocatorWidget;
class OpenDocumentsFilter;
class FileSystemFilter;
-class SettingsPage;
+class LocatorSettingsPage;
class Locator : public QObject
{
@@ -80,12 +80,13 @@ private slots:
private:
void loadSettings();
+ void updateEditorManagerPlaceholderText();
template <typename S>
void loadSettingsHelper(S *settings);
LocatorWidget *m_locatorWidget;
- SettingsPage *m_settingsPage;
+ LocatorSettingsPage *m_settingsPage;
bool m_settingsInitialized;
QList<ILocatorFilter *> m_filters;
@@ -115,7 +116,7 @@ void Locator::loadSettingsHelper(S *settings)
QList<ILocatorFilter *> customFilters;
const QStringList keys = settings->childKeys();
int count = 0;
- Core::Id baseId(Constants::CUSTOM_FILTER_BASEID);
+ Id baseId(Constants::CUSTOM_FILTER_BASEID);
foreach (const QString &key, keys) {
ILocatorFilter *filter = new DirectoryFilter(baseId.withSuffix(++count));
filter->restoreState(settings->value(key).toByteArray());
diff --git a/src/plugins/coreplugin/locator/locator.pri b/src/plugins/coreplugin/locator/locator.pri
index f5b214b1a98..5ff92bfd43d 100644
--- a/src/plugins/coreplugin/locator/locator.pri
+++ b/src/plugins/coreplugin/locator/locator.pri
@@ -3,7 +3,6 @@ HEADERS += \
$$PWD/commandlocator.h \
$$PWD/locatorwidget.h \
$$PWD/locatorfiltersfilter.h \
- $$PWD/settingspage.h \
$$PWD/ilocatorfilter.h \
$$PWD/opendocumentsfilter.h \
$$PWD/filesystemfilter.h \
@@ -12,7 +11,8 @@ HEADERS += \
$$PWD/locatormanager.h \
$$PWD/basefilefilter.h \
$$PWD/executefilter.h \
- $$PWD/locatorsearchutils.h
+ $$PWD/locatorsearchutils.h \
+ $$PWD/locatorsettingspage.h
SOURCES += \
$$PWD/locator.cpp \
@@ -21,18 +21,18 @@ SOURCES += \
$$PWD/locatorfiltersfilter.cpp \
$$PWD/opendocumentsfilter.cpp \
$$PWD/filesystemfilter.cpp \
- $$PWD/settingspage.cpp \
$$PWD/directoryfilter.cpp \
$$PWD/locatormanager.cpp \
$$PWD/basefilefilter.cpp \
$$PWD/ilocatorfilter.cpp \
$$PWD/executefilter.cpp \
- $$PWD/locatorsearchutils.cpp
+ $$PWD/locatorsearchutils.cpp \
+ $$PWD/locatorsettingspage.cpp
FORMS += \
- $$PWD/settingspage.ui \
$$PWD/filesystemfilter.ui \
- $$PWD/directoryfilter.ui
+ $$PWD/directoryfilter.ui \
+ $$PWD/locatorsettingspage.ui
RESOURCES += \
$$PWD/locator.qrc
diff --git a/src/plugins/coreplugin/locator/locator_test.cpp b/src/plugins/coreplugin/locator/locator_test.cpp
index dc27ba5b750..2d2142f619f 100644
--- a/src/plugins/coreplugin/locator/locator_test.cpp
+++ b/src/plugins/coreplugin/locator/locator_test.cpp
@@ -52,9 +52,7 @@ class MyBaseFileFilter : public Core::BaseFileFilter
public:
MyBaseFileFilter(const QStringList &theFiles)
{
- files().clear();
- files().append(theFiles);
- BaseFileFilter::generateFileNames();
+ setFileIterator(new BaseFileFilter::ListIterator(theFiles));
}
void refresh(QFutureInterface<void> &) {}
diff --git a/src/plugins/coreplugin/locator/locatorconstants.h b/src/plugins/coreplugin/locator/locatorconstants.h
index d63b585fa61..fdf072c29c8 100644
--- a/src/plugins/coreplugin/locator/locatorconstants.h
+++ b/src/plugins/coreplugin/locator/locatorconstants.h
@@ -36,6 +36,7 @@
namespace Core {
namespace Constants {
+const char LOCATE[] = "QtCreator.Locate";
const char FILTER_OPTIONS_PAGE[] = QT_TRANSLATE_NOOP("Locator", "Locator");
const char CUSTOM_FILTER_BASEID[] = "Locator.CustomFilter";
const char TASK_INDEX[] = "Locator.Task.Index";
diff --git a/src/plugins/coreplugin/locator/locatorfiltersfilter.cpp b/src/plugins/coreplugin/locator/locatorfiltersfilter.cpp
index 0dd49d48bb9..146a4d98241 100644
--- a/src/plugins/coreplugin/locator/locatorfiltersfilter.cpp
+++ b/src/plugins/coreplugin/locator/locatorfiltersfilter.cpp
@@ -33,6 +33,7 @@
#include "locatorwidget.h"
#include <coreplugin/coreconstants.h>
+#include <utils/qtcassert.h>
using namespace Core;
using namespace Core::Internal;
@@ -43,13 +44,13 @@ LocatorFiltersFilter::LocatorFiltersFilter(Locator *plugin,
LocatorWidget *locatorWidget):
m_plugin(plugin),
m_locatorWidget(locatorWidget),
- m_icon(QIcon(QLatin1String(Core::Constants::ICON_NEXT)))
+ m_icon(QIcon(QLatin1String(Constants::ICON_NEXT)))
{
setId("FiltersFilter");
setDisplayName(tr("Available filters"));
setIncludedByDefault(true);
setHidden(true);
- setPriority(High);
+ setPriority(Highest);
setConfigurable(false);
}
@@ -74,7 +75,7 @@ void LocatorFiltersFilter::prepareSearch(const QString &entry)
}
}
-QList<LocatorFilterEntry> LocatorFiltersFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry)
+QList<LocatorFilterEntry> LocatorFiltersFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry)
{
Q_UNUSED(entry) // search is already done in the GUI thread in prepareSearch
QList<LocatorFilterEntry> entries;
@@ -83,7 +84,7 @@ QList<LocatorFilterEntry> LocatorFiltersFilter::matchesFor(QFutureInterface<Core
break;
LocatorFilterEntry filterEntry(this,
m_filterShortcutStrings.at(i),
- m_filterShortcutStrings.at(i),
+ i,
m_icon);
filterEntry.extraInfo = m_filterDisplayNames.at(i);
entries.append(filterEntry);
@@ -93,7 +94,10 @@ QList<LocatorFilterEntry> LocatorFiltersFilter::matchesFor(QFutureInterface<Core
void LocatorFiltersFilter::accept(LocatorFilterEntry selection) const
{
- const QString shortcutString = selection.internalData.toString();
+ bool ok;
+ int index = selection.internalData.toInt(&ok);
+ QTC_ASSERT(ok && index >= 0 && index < m_filterShortcutStrings.size(), return);
+ const QString shortcutString = m_filterShortcutStrings.at(index);
if (!shortcutString.isEmpty())
m_locatorWidget->show(shortcutString + QLatin1Char(' '),
shortcutString.length() + 1);
diff --git a/src/plugins/coreplugin/locator/locatorfiltersfilter.h b/src/plugins/coreplugin/locator/locatorfiltersfilter.h
index 06ce8502f6c..c375a809031 100644
--- a/src/plugins/coreplugin/locator/locatorfiltersfilter.h
+++ b/src/plugins/coreplugin/locator/locatorfiltersfilter.h
@@ -55,7 +55,7 @@ public:
// ILocatorFilter
void prepareSearch(const QString &entry);
- QList<LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry);
+ QList<LocatorFilterEntry> matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry);
void accept(LocatorFilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/coreplugin/locator/locatorfiltertest.cpp b/src/plugins/coreplugin/locator/locatorfiltertest.cpp
index 563a3262d7f..18a960b4eea 100644
--- a/src/plugins/coreplugin/locator/locatorfiltertest.cpp
+++ b/src/plugins/coreplugin/locator/locatorfiltertest.cpp
@@ -50,7 +50,8 @@ QList<LocatorFilterEntry> BasicLocatorFilterTest::matchesFor(const QString &sear
{
doBeforeLocatorRun();
const QList<ILocatorFilter *> filters = QList<ILocatorFilter *>() << m_filter;
- QFuture<LocatorFilterEntry> locatorSearch = QtConcurrent::run(Core::Internal::runSearch,
+ m_filter->prepareSearch(searchText);
+ QFuture<LocatorFilterEntry> locatorSearch = QtConcurrent::run(Internal::runSearch,
filters, searchText);
locatorSearch.waitForFinished();
doAfterLocatorRun();
diff --git a/src/plugins/coreplugin/locator/locatorfiltertest.h b/src/plugins/coreplugin/locator/locatorfiltertest.h
index c0fd4e1f6c8..9de1be0470b 100644
--- a/src/plugins/coreplugin/locator/locatorfiltertest.h
+++ b/src/plugins/coreplugin/locator/locatorfiltertest.h
@@ -43,15 +43,15 @@ namespace Tests {
class CORE_EXPORT BasicLocatorFilterTest
{
public:
- BasicLocatorFilterTest(Core::ILocatorFilter *filter);
+ BasicLocatorFilterTest(ILocatorFilter *filter);
- QList<Core::LocatorFilterEntry> matchesFor(const QString &searchText = QString());
+ QList<LocatorFilterEntry> matchesFor(const QString &searchText = QString());
private:
virtual void doBeforeLocatorRun() {}
virtual void doAfterLocatorRun() {}
- Core::ILocatorFilter *m_filter;
+ ILocatorFilter *m_filter;
};
class CORE_EXPORT ResultData
diff --git a/src/plugins/coreplugin/locator/locatorsearchutils.cpp b/src/plugins/coreplugin/locator/locatorsearchutils.cpp
index c240e8804fc..b46e784996a 100644
--- a/src/plugins/coreplugin/locator/locatorsearchutils.cpp
+++ b/src/plugins/coreplugin/locator/locatorsearchutils.cpp
@@ -37,7 +37,7 @@
namespace Core {
-uint qHash(const Core::LocatorFilterEntry &entry)
+uint qHash(const LocatorFilterEntry &entry)
{
if (entry.internalData.canConvert(QVariant::String))
return QT_PREPEND_NAMESPACE(qHash)(entry.internalData.toString());
@@ -55,12 +55,17 @@ void Core::Internal::runSearch(QFutureInterface<Core::LocatorFilterEntry> &futur
if (future.isCanceled())
break;
- foreach (const LocatorFilterEntry &entry, filter->matchesFor(future, searchText)) {
+ QList<LocatorFilterEntry> filterResults = filter->matchesFor(future, searchText);
+ QVector<LocatorFilterEntry> uniqueFilterResults;
+ uniqueFilterResults.reserve(filterResults.size());
+ foreach (const LocatorFilterEntry &entry, filterResults) {
if (checkDuplicates && alreadyAdded.contains(entry))
continue;
- future.reportResult(entry);
+ uniqueFilterResults.append(entry);
if (checkDuplicates)
alreadyAdded.insert(entry);
}
+ if (!uniqueFilterResults.isEmpty())
+ future.reportResults(uniqueFilterResults);
}
}
diff --git a/src/plugins/coreplugin/locator/settingspage.cpp b/src/plugins/coreplugin/locator/locatorsettingspage.cpp
index f8d9b5da30c..7e09f700dce 100644
--- a/src/plugins/coreplugin/locator/settingspage.cpp
+++ b/src/plugins/coreplugin/locator/locatorsettingspage.cpp
@@ -28,7 +28,7 @@
**
****************************************************************************/
-#include "settingspage.h"
+#include "locatorsettingspage.h"
#include "locatorconstants.h"
#include "locator.h"
@@ -45,32 +45,32 @@ Q_DECLARE_METATYPE(Core::ILocatorFilter*)
using namespace Core;
using namespace Core::Internal;
-SettingsPage::SettingsPage(Locator *plugin)
+LocatorSettingsPage::LocatorSettingsPage(Locator *plugin)
: m_plugin(plugin), m_widget(0)
{
setId(Constants::FILTER_OPTIONS_PAGE);
- setDisplayName(QCoreApplication::translate("Locator", Core::Constants::FILTER_OPTIONS_PAGE));
- setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
- setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
- setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
+ setDisplayName(QCoreApplication::translate("Locator", Constants::FILTER_OPTIONS_PAGE));
+ setCategory(Constants::SETTINGS_CATEGORY_CORE);
+ setDisplayCategory(QCoreApplication::translate("Core", Constants::SETTINGS_TR_CATEGORY_CORE));
+ setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CORE_ICON));
}
-QWidget *SettingsPage::widget()
+QWidget *LocatorSettingsPage::widget()
{
if (!m_widget) {
m_widget = new QWidget;
m_ui.setupUi(m_widget);
m_ui.refreshInterval->setToolTip(m_ui.refreshIntervalLabel->toolTip());
- connect(m_ui.filterList, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
- this, SLOT(updateButtonStates()));
+ connect(m_ui.filterList, &QListWidget::currentItemChanged,
+ this, &LocatorSettingsPage::updateButtonStates);
connect(m_ui.filterList, SIGNAL(itemActivated(QListWidgetItem*)),
this, SLOT(configureFilter(QListWidgetItem*)));
connect(m_ui.editButton, SIGNAL(clicked()),
this, SLOT(configureFilter()));
- connect(m_ui.addButton, SIGNAL(clicked()),
- this, SLOT(addCustomFilter()));
- connect(m_ui.removeButton, SIGNAL(clicked()),
- this, SLOT(removeCustomFilter()));
+ connect(m_ui.addButton, &QPushButton::clicked,
+ this, &LocatorSettingsPage::addCustomFilter);
+ connect(m_ui.removeButton, &QPushButton::clicked,
+ this, &LocatorSettingsPage::removeCustomFilter);
m_ui.refreshInterval->setValue(m_plugin->refreshInterval());
m_filters = m_plugin->filters();
@@ -81,7 +81,7 @@ QWidget *SettingsPage::widget()
return m_widget;
}
-void SettingsPage::apply()
+void LocatorSettingsPage::apply()
{
// Delete removed filters and clear added filters
qDeleteAll(m_removedFilters);
@@ -97,7 +97,7 @@ void SettingsPage::apply()
saveFilterStates();
}
-void SettingsPage::finish()
+void LocatorSettingsPage::finish()
{
// If settings were applied, this shouldn't change anything. Otherwise it
// makes sure the filter states aren't changed permanently.
@@ -115,26 +115,26 @@ void SettingsPage::finish()
delete m_widget;
}
-void SettingsPage::requestRefresh()
+void LocatorSettingsPage::requestRefresh()
{
if (!m_refreshFilters.isEmpty())
m_plugin->refresh(m_refreshFilters);
}
-void SettingsPage::saveFilterStates()
+void LocatorSettingsPage::saveFilterStates()
{
m_filterStates.clear();
foreach (ILocatorFilter *filter, m_filters)
m_filterStates.insert(filter, filter->saveState());
}
-void SettingsPage::restoreFilterStates()
+void LocatorSettingsPage::restoreFilterStates()
{
foreach (ILocatorFilter *filter, m_filterStates.keys())
filter->restoreState(m_filterStates.value(filter));
}
-void SettingsPage::updateFilterList()
+void LocatorSettingsPage::updateFilterList()
{
m_ui.filterList->clear();
foreach (ILocatorFilter *filter, m_filters) {
@@ -154,7 +154,7 @@ void SettingsPage::updateFilterList()
m_ui.filterList->setCurrentRow(0);
}
-void SettingsPage::updateButtonStates()
+void LocatorSettingsPage::updateButtonStates()
{
QListWidgetItem *item = m_ui.filterList->currentItem();
ILocatorFilter *filter = (item ? item->data(Qt::UserRole).value<ILocatorFilter *>() : 0);
@@ -162,7 +162,7 @@ void SettingsPage::updateButtonStates()
m_ui.removeButton->setEnabled(filter && m_customFilters.contains(filter));
}
-void SettingsPage::configureFilter(QListWidgetItem *item)
+void LocatorSettingsPage::configureFilter(QListWidgetItem *item)
{
if (!item)
item = m_ui.filterList->currentItem();
@@ -179,10 +179,10 @@ void SettingsPage::configureFilter(QListWidgetItem *item)
updateFilterList();
}
-void SettingsPage::addCustomFilter()
+void LocatorSettingsPage::addCustomFilter()
{
ILocatorFilter *filter = new DirectoryFilter(
- Core::Id(Constants::CUSTOM_FILTER_BASEID).withSuffix(m_customFilters.size() + 1));
+ Id(Constants::CUSTOM_FILTER_BASEID).withSuffix(m_customFilters.size() + 1));
bool needsRefresh = false;
if (filter->openConfigDialog(m_widget, needsRefresh)) {
m_filters.append(filter);
@@ -193,7 +193,7 @@ void SettingsPage::addCustomFilter()
}
}
-void SettingsPage::removeCustomFilter()
+void LocatorSettingsPage::removeCustomFilter()
{
QListWidgetItem *item = m_ui.filterList->currentItem();
QTC_ASSERT(item, return);
diff --git a/src/plugins/coreplugin/locator/settingspage.h b/src/plugins/coreplugin/locator/locatorsettingspage.h
index 4df14923938..fa3a5fdb411 100644
--- a/src/plugins/coreplugin/locator/settingspage.h
+++ b/src/plugins/coreplugin/locator/locatorsettingspage.h
@@ -28,10 +28,10 @@
**
****************************************************************************/
-#ifndef SETTINGSPAGE_H
-#define SETTINGSPAGE_H
+#ifndef LOCATORSETTINGSPAGE_H
+#define LOCATORSETTINGSPAGE_H
-#include "ui_settingspage.h"
+#include "ui_locatorsettingspage.h"
#include <coreplugin/dialogs/ioptionspage.h>
@@ -50,12 +50,12 @@ namespace Internal {
class Locator;
-class SettingsPage : public Core::IOptionsPage
+class LocatorSettingsPage : public IOptionsPage
{
Q_OBJECT
public:
- explicit SettingsPage(Locator *plugin);
+ explicit LocatorSettingsPage(Locator *plugin);
QWidget *widget();
void apply();
@@ -87,4 +87,4 @@ private:
} // namespace Internal
} // namespace Core
-#endif // SETTINGSPAGE_H
+#endif // LOCATORSETTINGSPAGE_H
diff --git a/src/plugins/coreplugin/locator/settingspage.ui b/src/plugins/coreplugin/locator/locatorsettingspage.ui
index e8590f61da1..e8590f61da1 100644
--- a/src/plugins/coreplugin/locator/settingspage.ui
+++ b/src/plugins/coreplugin/locator/locatorsettingspage.ui
diff --git a/src/plugins/coreplugin/locator/locatorwidget.cpp b/src/plugins/coreplugin/locator/locatorwidget.cpp
index 34215b84a96..7c42ed6202a 100644
--- a/src/plugins/coreplugin/locator/locatorwidget.cpp
+++ b/src/plugins/coreplugin/locator/locatorwidget.cpp
@@ -43,6 +43,7 @@
#include <utils/appmainwindow.h>
#include <utils/fancylineedit.h>
#include <utils/hostosinfo.h>
+#include <utils/progressindicator.h>
#include <utils/qtcassert.h>
#include <utils/runextensions.h>
#include <utils/stylehelper.h>
@@ -73,19 +74,17 @@ class LocatorModel : public QAbstractListModel
public:
LocatorModel(QObject *parent = 0)
: QAbstractListModel(parent)
-// , mDisplayCount(64)
{}
+ void clear();
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- void setEntries(const QList<LocatorFilterEntry> &entries);
- //void setDisplayCount(int count);
+ void addEntries(const QList<LocatorFilterEntry> &entries);
private:
mutable QList<LocatorFilterEntry> mEntries;
- //int mDisplayCount;
};
class CompletionList : public QTreeView
@@ -133,8 +132,17 @@ using namespace Core::Internal;
// =========== LocatorModel ===========
-int LocatorModel::rowCount(const QModelIndex & /* parent */) const
+void LocatorModel::clear()
{
+ beginResetModel();
+ mEntries.clear();
+ endResetModel();
+}
+
+int LocatorModel::rowCount(const QModelIndex & parent) const
+{
+ if (parent.isValid())
+ return 0;
return mEntries.size();
}
@@ -143,12 +151,6 @@ int LocatorModel::columnCount(const QModelIndex &parent) const
return parent.isValid() ? 0 : 2;
}
-/*!
- * When asked for the icon via Qt::DecorationRole, the LocatorModel lazily
- * resolves and caches the Greehouse-specific file icon when
- * FilterEntry::resolveFileIcon is true. FilterEntry::internalData is assumed
- * to be the filename.
- */
QVariant LocatorModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= mEntries.size())
@@ -181,11 +183,11 @@ QVariant LocatorModel::data(const QModelIndex &index, int role) const
return QVariant();
}
-void LocatorModel::setEntries(const QList<LocatorFilterEntry> &entries)
+void LocatorModel::addEntries(const QList<LocatorFilterEntry> &entries)
{
- beginResetModel();
- mEntries = entries;
- endResetModel();
+ beginInsertRows(QModelIndex(), mEntries.size(), mEntries.size() + entries.size() - 1);
+ mEntries.append(entries);
+ endInsertRows();
}
// =========== CompletionList ===========
@@ -225,8 +227,9 @@ LocatorWidget::LocatorWidget(Locator *qop) :
m_completionList(new CompletionList(this)),
m_filterMenu(new QMenu(this)),
m_refreshAction(new QAction(tr("Refresh"), this)),
- m_configureAction(new QAction(Core::ICore::msgShowOptionsDialog(), this)),
+ m_configureAction(new QAction(ICore::msgShowOptionsDialog(), this)),
m_fileLineEdit(new Utils::FancyLineEdit),
+ m_needsClearResult(true),
m_updateRequested(false),
m_acceptRequested(false),
m_possibleToolTipRequest(false)
@@ -249,7 +252,7 @@ LocatorWidget::LocatorWidget(Locator *qop) :
layout->addWidget(m_fileLineEdit);
setWindowIcon(QIcon(QLatin1String(":/locator/images/locator.png")));
- const QPixmap image = Utils::StyleHelper::dpiSpecificImageFile(QLatin1String(Core::Constants::ICON_MAGNIFIER));
+ const QPixmap image = Utils::StyleHelper::dpiSpecificImageFile(QLatin1String(Constants::ICON_MAGNIFIER));
m_fileLineEdit->setFiltering(true);
m_fileLineEdit->setButtonPixmap(Utils::FancyLineEdit::Left, image);
m_fileLineEdit->setButtonToolTip(Utils::FancyLineEdit::Left, tr("Options"));
@@ -280,12 +283,23 @@ LocatorWidget::LocatorWidget(Locator *qop) :
this, SLOT(scheduleAcceptCurrentEntry()));
m_entriesWatcher = new QFutureWatcher<LocatorFilterEntry>(this);
- connect(m_entriesWatcher, SIGNAL(finished()), SLOT(updateEntries()));
+ connect(m_entriesWatcher, &QFutureWatcher<LocatorFilterEntry>::resultsReadyAt,
+ this, &LocatorWidget::addSearchResults);
+ connect(m_entriesWatcher, &QFutureWatcher<LocatorFilterEntry>::finished,
+ this, &LocatorWidget::handleSearchFinished);
m_showPopupTimer = new QTimer(this);
m_showPopupTimer->setInterval(100);
m_showPopupTimer->setSingleShot(true);
connect(m_showPopupTimer, SIGNAL(timeout()), SLOT(showPopupNow()));
+
+ m_progressIndicator = new Utils::ProgressIndicator(Utils::ProgressIndicator::Small,
+ m_fileLineEdit);
+ m_progressIndicator->raise();
+ m_progressIndicator->hide();
+ m_showProgressTimer.setSingleShot(true);
+ m_showProgressTimer.setInterval(50); // don't show progress for < 50ms tasks
+ connect(&m_showProgressTimer, &QTimer::timeout, [this]() { setProgressIndicatorVisible(true);});
}
void LocatorWidget::setPlaceholderText(const QString &text)
@@ -314,7 +328,7 @@ void LocatorWidget::updateFilterList()
// register new action
action = new QAction(filter->displayName(), this);
cmd = ActionManager::registerAction(action, locatorId,
- Context(Core::Constants::C_GLOBAL));
+ Context(Constants::C_GLOBAL));
cmd->setAttribute(Command::CA_UpdateText);
connect(action, SIGNAL(triggered()), this, SLOT(filterSelected()));
action->setData(qVariantFromValue(filter));
@@ -425,7 +439,7 @@ bool LocatorWidget::eventFilter(QObject *obj, QEvent *event)
void LocatorWidget::setFocusToCurrentMode()
{
- Core::ModeManager::setFocusToCurrentMode();
+ ModeManager::setFocusToCurrentMode();
}
void LocatorWidget::showCompletionList()
@@ -477,6 +491,21 @@ QList<ILocatorFilter *> LocatorWidget::filtersFor(const QString &text, QString &
return activeFilters;
}
+void LocatorWidget::setProgressIndicatorVisible(bool visible)
+{
+ if (!visible) {
+ m_progressIndicator->hide();
+ return;
+ }
+ const QSize iconSize = m_progressIndicator->sizeHint();
+ m_progressIndicator->setGeometry(m_fileLineEdit->button(Utils::FancyLineEdit::Right)->geometry().x()
+ - iconSize.width(),
+ (m_fileLineEdit->height() - iconSize.height()) / 2 /*center*/,
+ iconSize.width(),
+ iconSize.height());
+ m_progressIndicator->show();
+}
+
void LocatorWidget::updateCompletionList(const QString &text)
{
m_updateRequested = true;
@@ -490,6 +519,8 @@ void LocatorWidget::updateCompletionList(const QString &text)
return;
}
+ m_showProgressTimer.start();
+ m_needsClearResult = true;
QString searchText;
const QList<ILocatorFilter *> filters = filtersFor(text, searchText);
@@ -499,9 +530,15 @@ void LocatorWidget::updateCompletionList(const QString &text)
m_entriesWatcher->setFuture(future);
}
-void LocatorWidget::updateEntries()
+void LocatorWidget::handleSearchFinished()
{
+ m_showProgressTimer.stop();
+ setProgressIndicatorVisible(false);
m_updateRequested = false;
+ if (m_acceptRequested) {
+ acceptCurrentEntry();
+ return;
+ }
if (m_entriesWatcher->future().isCanceled()) {
const QString text = m_requestedCompletionText;
m_requestedCompletionText.clear();
@@ -509,15 +546,10 @@ void LocatorWidget::updateEntries()
return;
}
- const QList<LocatorFilterEntry> entries = m_entriesWatcher->future().results();
- m_locatorModel->setEntries(entries);
- if (m_locatorModel->rowCount() > 0)
- m_completionList->setCurrentIndex(m_locatorModel->index(0, 0));
-#if 0
- m_completionList->updatePreferredSize();
-#endif
- if (m_acceptRequested)
- acceptCurrentEntry();
+ if (m_needsClearResult) {
+ m_locatorModel->clear();
+ m_needsClearResult = false;
+ }
}
void LocatorWidget::scheduleAcceptCurrentEntry()
@@ -526,6 +558,8 @@ void LocatorWidget::scheduleAcceptCurrentEntry()
// don't just accept the selected entry, since the list is not up to date
// accept will be called after the update finished
m_acceptRequested = true;
+ // do not wait for the rest of the search to finish
+ m_entriesWatcher->future().cancel();
} else {
acceptCurrentEntry();
}
@@ -596,7 +630,22 @@ void LocatorWidget::showEvent(QShowEvent *event)
void LocatorWidget::showConfigureDialog()
{
- ICore::showOptionsDialog(Core::Constants::SETTINGS_CATEGORY_CORE, Constants::FILTER_OPTIONS_PAGE);
+ ICore::showOptionsDialog(Constants::SETTINGS_CATEGORY_CORE, Constants::FILTER_OPTIONS_PAGE);
+}
+
+void LocatorWidget::addSearchResults(int firstIndex, int endIndex)
+{
+ if (m_needsClearResult) {
+ m_locatorModel->clear();
+ m_needsClearResult = false;
+ }
+ const bool selectFirst = m_locatorModel->rowCount() == 0;
+ QList<LocatorFilterEntry> entries;
+ for (int i = firstIndex; i < endIndex; ++i)
+ entries.append(m_entriesWatcher->resultAt(i));
+ m_locatorModel->addEntries(entries);
+ if (selectFirst)
+ m_completionList->setCurrentIndex(m_locatorModel->index(0, 0));
}
} // namespace Core
diff --git a/src/plugins/coreplugin/locator/locatorwidget.h b/src/plugins/coreplugin/locator/locatorwidget.h
index eaac00f4d5a..5dd597cb133 100644
--- a/src/plugins/coreplugin/locator/locatorwidget.h
+++ b/src/plugins/coreplugin/locator/locatorwidget.h
@@ -71,7 +71,8 @@ private slots:
void acceptCurrentEntry();
void filterSelected();
void showConfigureDialog();
- void updateEntries();
+ void addSearchResults(int firstIndex, int endIndex);
+ void handleSearchFinished();
void scheduleAcceptCurrentEntry();
void setFocusToCurrentMode();
@@ -83,6 +84,7 @@ private:
void showCompletionList();
void updateCompletionList(const QString &text);
QList<ILocatorFilter*> filtersFor(const QString &text, QString &searchText);
+ void setProgressIndicatorVisible(bool visible);
Locator *m_locatorPlugin;
LocatorModel *m_locatorModel;
@@ -94,11 +96,14 @@ private:
Utils::FancyLineEdit *m_fileLineEdit;
QTimer *m_showPopupTimer;
QFutureWatcher<LocatorFilterEntry> *m_entriesWatcher;
- QMap<Core::Id, QAction *> m_filterActionMap;
+ QMap<Id, QAction *> m_filterActionMap;
QString m_requestedCompletionText;
+ bool m_needsClearResult;
bool m_updateRequested;
bool m_acceptRequested;
bool m_possibleToolTipRequest;
+ QWidget *m_progressIndicator;
+ QTimer m_showProgressTimer;
};
} // namespace Internal
diff --git a/src/plugins/coreplugin/locator/opendocumentsfilter.cpp b/src/plugins/coreplugin/locator/opendocumentsfilter.cpp
index 87b1e8d257f..433f8cc3a56 100644
--- a/src/plugins/coreplugin/locator/opendocumentsfilter.cpp
+++ b/src/plugins/coreplugin/locator/opendocumentsfilter.cpp
@@ -47,6 +47,7 @@ OpenDocumentsFilter::OpenDocumentsFilter()
setId("Open documents");
setDisplayName(tr("Open Documents"));
setShortcutString(QString(QLatin1Char('o')));
+ setPriority(High);
setIncludedByDefault(true);
connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
@@ -55,7 +56,7 @@ OpenDocumentsFilter::OpenDocumentsFilter()
this, SLOT(refreshInternally()));
}
-QList<LocatorFilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry_)
+QList<LocatorFilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry_)
{
QList<LocatorFilterEntry> goodEntries;
QList<LocatorFilterEntry> betterEntries;
diff --git a/src/plugins/coreplugin/locator/opendocumentsfilter.h b/src/plugins/coreplugin/locator/opendocumentsfilter.h
index 00a712abd89..d77a77ef4d6 100644
--- a/src/plugins/coreplugin/locator/opendocumentsfilter.h
+++ b/src/plugins/coreplugin/locator/opendocumentsfilter.h
@@ -43,24 +43,24 @@
namespace Core {
namespace Internal {
-class OpenDocumentsFilter : public Core::ILocatorFilter
+class OpenDocumentsFilter : public ILocatorFilter
{
Q_OBJECT
public:
OpenDocumentsFilter();
- QList<Core::LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry);
- void accept(Core::LocatorFilterEntry selection) const;
+ QList<LocatorFilterEntry> matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry);
+ void accept(LocatorFilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
public slots:
void refreshInternally();
private:
- QList<Core::DocumentModel::Entry> editors() const;
+ QList<DocumentModel::Entry> editors() const;
mutable QMutex m_mutex;
- QList<Core::DocumentModel::Entry> m_editors;
+ QList<DocumentModel::Entry> m_editors;
};
} // namespace Internal
diff --git a/src/plugins/coreplugin/mainwindow.cpp b/src/plugins/coreplugin/mainwindow.cpp
index fa40cb76bb0..23b39ba8a03 100644
--- a/src/plugins/coreplugin/mainwindow.cpp
+++ b/src/plugins/coreplugin/mainwindow.cpp
@@ -117,7 +117,6 @@ MainWindow::MainWindow() :
this)),
m_printer(0),
m_windowSupport(0),
- m_actionManager(new ActionManager(this)),
m_editorManager(0),
m_externalToolManager(0),
m_progressManager(new ProgressManagerPrivate),
@@ -146,8 +145,6 @@ MainWindow::MainWindow() :
m_toggleSideBarAction(0),
m_toggleSideBarButton(new QToolButton)
{
- ActionManager::initialize(); // must be done before registering any actions
-
(void) new DocumentManager(this);
OutputPaneManager::create();
@@ -157,7 +154,7 @@ MainWindow::MainWindow() :
if (Utils::HostOsInfo::isLinuxHost())
QApplication::setWindowIcon(QIcon(QLatin1String(Constants::ICON_QTLOGO_128)));
QCoreApplication::setApplicationName(QLatin1String("QtCreator"));
- QCoreApplication::setApplicationVersion(QLatin1String(Core::Constants::IDE_VERSION_LONG));
+ QCoreApplication::setApplicationVersion(QLatin1String(Constants::IDE_VERSION_LONG));
QCoreApplication::setOrganizationName(QLatin1String(Constants::IDE_SETTINGSVARIANT_STR));
QString baseName = QApplication::style()->objectName();
// Sometimes we get the standard windows 95 style as a fallback
@@ -253,11 +250,11 @@ MainWindow::~MainWindow()
delete m_windowSupport;
m_windowSupport = 0;
- ExtensionSystem::PluginManager::removeObject(m_shortcutSettings);
- ExtensionSystem::PluginManager::removeObject(m_generalSettings);
- ExtensionSystem::PluginManager::removeObject(m_toolSettings);
- ExtensionSystem::PluginManager::removeObject(m_mimeTypeSettings);
- ExtensionSystem::PluginManager::removeObject(m_systemEditor);
+ PluginManager::removeObject(m_shortcutSettings);
+ PluginManager::removeObject(m_generalSettings);
+ PluginManager::removeObject(m_toolSettings);
+ PluginManager::removeObject(m_mimeTypeSettings);
+ PluginManager::removeObject(m_systemEditor);
delete m_externalToolManager;
m_externalToolManager = 0;
delete m_messageManager;
@@ -283,7 +280,7 @@ MainWindow::~MainWindow()
OutputPaneManager::destroy();
// Now that the OutputPaneManager is gone, is a good time to delete the view
- ExtensionSystem::PluginManager::removeObject(m_outputView);
+ PluginManager::removeObject(m_outputView);
delete m_outputView;
delete m_editorManager;
@@ -292,7 +289,7 @@ MainWindow::~MainWindow()
m_progressManager = 0;
delete m_statusBarManager;
m_statusBarManager = 0;
- ExtensionSystem::PluginManager::removeObject(m_coreImpl);
+ PluginManager::removeObject(m_coreImpl);
delete m_coreImpl;
m_coreImpl = 0;
@@ -317,23 +314,23 @@ bool MainWindow::init(QString *errorMessage)
if (!MimeDatabase::addMimeTypes(QLatin1String(":/core/editormanager/BinFiles.mimetypes.xml"), errorMessage))
return false;
- ExtensionSystem::PluginManager::addObject(m_coreImpl);
+ PluginManager::addObject(m_coreImpl);
m_statusBarManager->init();
m_modeManager->init();
m_progressManager->init(); // needs the status bar manager
- ExtensionSystem::PluginManager::addObject(m_generalSettings);
- ExtensionSystem::PluginManager::addObject(m_shortcutSettings);
- ExtensionSystem::PluginManager::addObject(m_toolSettings);
- ExtensionSystem::PluginManager::addObject(m_mimeTypeSettings);
- ExtensionSystem::PluginManager::addObject(m_systemEditor);
+ PluginManager::addObject(m_generalSettings);
+ PluginManager::addObject(m_shortcutSettings);
+ PluginManager::addObject(m_toolSettings);
+ PluginManager::addObject(m_mimeTypeSettings);
+ PluginManager::addObject(m_systemEditor);
// Add widget to the bottom, we create the view here instead of inside the
// OutputPaneManager, since the StatusBarManager needs to be initialized before
- m_outputView = new Core::StatusBarWidget;
+ m_outputView = new StatusBarWidget;
m_outputView->setWidget(OutputPaneManager::instance()->buttonsWidget());
- m_outputView->setPosition(Core::StatusBarWidget::Second);
- ExtensionSystem::PluginManager::addObject(m_outputView);
+ m_outputView->setPosition(StatusBarWidget::Second);
+ PluginManager::addObject(m_outputView);
MessageManager::init();
return true;
}
@@ -345,7 +342,7 @@ void MainWindow::extensionsInitialized()
m_statusBarManager->extensionsInitalized();
OutputPaneManager::instance()->init();
m_vcsManager->extensionsInitialized();
- m_navigationWidget->setFactories(ExtensionSystem::PluginManager::getObjects<INavigationWidgetFactory>());
+ m_navigationWidget->setFactories(PluginManager::getObjects<INavigationWidgetFactory>());
readSettings();
updateContext();
@@ -367,7 +364,7 @@ void MainWindow::closeEvent(QCloseEvent *event)
}
const QList<ICoreListener *> listeners =
- ExtensionSystem::PluginManager::getObjects<ICoreListener>();
+ PluginManager::getObjects<ICoreListener>();
foreach (ICoreListener *listener, listeners) {
if (!listener->coreAboutToClose()) {
event->ignore();
@@ -743,7 +740,7 @@ void MainWindow::registerDefaultActions()
void MainWindow::newFile()
{
- showNewItemDialog(tr("New", "Title of dialog"), IWizardFactory::allWizardFactories(), QString());
+ showNewItemDialog(tr("New File or Project", "Title of dialog"), IWizardFactory::allWizardFactories(), QString());
}
void MainWindow::openFile()
@@ -776,7 +773,7 @@ static IDocumentFactory *findDocumentFactory(const QList<IDocumentFactory*> &fil
*/
IDocument *MainWindow::openFiles(const QStringList &fileNames, ICore::OpenFilesFlags flags)
{
- QList<IDocumentFactory*> documentFactories = ExtensionSystem::PluginManager::getObjects<IDocumentFactory>();
+ QList<IDocumentFactory*> documentFactories = PluginManager::getObjects<IDocumentFactory>();
IDocument *res = 0;
foreach (const QString &fileName, fileNames) {
@@ -791,7 +788,7 @@ IDocument *MainWindow::openFiles(const QStringList &fileNames, ICore::OpenFilesF
if (!res)
res = document;
if (flags & ICore::SwitchMode)
- ModeManager::activateMode(Id(Core::Constants::MODE_EDIT));
+ ModeManager::activateMode(Id(Constants::MODE_EDIT));
}
} else {
QFlags<EditorManager::OpenEditorFlag> emFlags;
@@ -1000,7 +997,7 @@ void MainWindow::writeSettings()
settings->endGroup();
DocumentManager::saveSettings();
- m_actionManager->saveSettings(settings);
+ ActionManager::saveSettings(settings);
EditorManagerPrivate::saveSettings();
m_navigationWidget->saveSettings(settings);
}
@@ -1043,7 +1040,7 @@ void MainWindow::updateContext()
uniquecontexts.add(id);
}
- m_actionManager->setContext(uniquecontexts);
+ ActionManager::setContext(uniquecontexts);
emit m_coreImpl->contextChanged(m_activeContext, m_additionalContexts);
}
@@ -1068,7 +1065,7 @@ void MainWindow::aboutToShowRecentFiles()
if (hasRecentFiles) {
menu->addSeparator();
QAction *action = menu->addAction(QCoreApplication::translate(
- "Core", Core::Constants::TR_CLEAR_MENU));
+ "Core", Constants::TR_CLEAR_MENU));
connect(action, SIGNAL(triggered()), DocumentManager::instance(), SLOT(clearRecentFiles()));
}
}
diff --git a/src/plugins/coreplugin/mainwindow.h b/src/plugins/coreplugin/mainwindow.h
index b6ed8b14052..eb5794303c4 100644
--- a/src/plugins/coreplugin/mainwindow.h
+++ b/src/plugins/coreplugin/mainwindow.h
@@ -49,7 +49,6 @@ QT_END_NAMESPACE
namespace Core {
-class ActionManager;
class StatusBarWidget;
class EditorManager;
class ExternalToolManager;
@@ -69,7 +68,6 @@ class VcsManager;
namespace Internal {
-class ActionManagerPrivate;
class FancyTabWidget;
class GeneralSettings;
class ProgressManagerPrivate;
@@ -94,10 +92,10 @@ public:
void aboutToShutdown();
IContext *contextObject(QWidget *widget);
- void addContextObject(IContext *contex);
- void removeContextObject(IContext *contex);
+ void addContextObject(IContext *context);
+ void removeContextObject(IContext *context);
- Core::IDocument *openFiles(const QStringList &fileNames, ICore::OpenFilesFlags flags);
+ IDocument *openFiles(const QStringList &fileNames, ICore::OpenFilesFlags flags);
inline SettingsDatabase *settingsDatabase() const { return m_settingsDatabase; }
virtual QPrinter *printer() const;
@@ -168,7 +166,6 @@ private:
SettingsDatabase *m_settingsDatabase;
mutable QPrinter *m_printer;
WindowSupport *m_windowSupport;
- ActionManager *m_actionManager;
EditorManager *m_editorManager;
ExternalToolManager *m_externalToolManager;
MessageManager *m_messageManager;
@@ -182,7 +179,7 @@ private:
FancyTabWidget *m_modeStack;
NavigationWidget *m_navigationWidget;
RightPaneWidget *m_rightPaneWidget;
- Core::StatusBarWidget *m_outputView;
+ StatusBarWidget *m_outputView;
VersionDialog *m_versionDialog;
QPointer<NewDialog> m_newDialog;
diff --git a/src/plugins/coreplugin/manhattanstyle.cpp b/src/plugins/coreplugin/manhattanstyle.cpp
index eb62f88a651..3b917c36dac 100644
--- a/src/plugins/coreplugin/manhattanstyle.cpp
+++ b/src/plugins/coreplugin/manhattanstyle.cpp
@@ -82,7 +82,7 @@ bool panelWidget(const QWidget *widget)
if ((widget->window()->windowFlags() & Qt::WindowType_Mask) == Qt::Dialog)
return false;
- if (qobject_cast<const Utils::FancyMainWindow *>(widget))
+ if (qobject_cast<const FancyMainWindow *>(widget))
return true;
if (qobject_cast<const QTabBar *>(widget))
@@ -134,8 +134,8 @@ public:
};
ManhattanStylePrivate::ManhattanStylePrivate() :
- lineeditImage(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/inputfield.png"))),
- lineeditImage_disabled(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/inputfield_disabled.png"))),
+ lineeditImage(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/inputfield.png"))),
+ lineeditImage_disabled(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/inputfield_disabled.png"))),
extButtonPixmap(QLatin1String(":/core/images/extension.png")),
closeButtonPixmap(QLatin1String(Core::Constants::ICON_CLOSE_BUTTON))
{
@@ -278,18 +278,18 @@ void ManhattanStyle::polish(QWidget *widget)
widget->setAttribute(Qt::WA_LayoutUsesWidgetRect, true);
if (qobject_cast<QToolButton*>(widget)) {
widget->setAttribute(Qt::WA_Hover);
- widget->setMaximumHeight(Utils::StyleHelper::navigationWidgetHeight() - 2);
+ widget->setMaximumHeight(StyleHelper::navigationWidgetHeight() - 2);
} else if (qobject_cast<QLineEdit*>(widget)) {
widget->setAttribute(Qt::WA_Hover);
- widget->setMaximumHeight(Utils::StyleHelper::navigationWidgetHeight() - 2);
+ widget->setMaximumHeight(StyleHelper::navigationWidgetHeight() - 2);
} else if (qobject_cast<QLabel*>(widget)) {
widget->setPalette(panelPalette(widget->palette(), lightColored(widget)));
} else if (widget->property("panelwidget_singlerow").toBool()) {
- widget->setFixedHeight(Utils::StyleHelper::navigationWidgetHeight());
+ widget->setFixedHeight(StyleHelper::navigationWidgetHeight());
} else if (qobject_cast<QStatusBar*>(widget)) {
- widget->setFixedHeight(Utils::StyleHelper::navigationWidgetHeight() + 2);
+ widget->setFixedHeight(StyleHelper::navigationWidgetHeight() + 2);
} else if (qobject_cast<QComboBox*>(widget)) {
- widget->setMaximumHeight(Utils::StyleHelper::navigationWidgetHeight() - 2);
+ widget->setMaximumHeight(StyleHelper::navigationWidgetHeight() - 2);
widget->setAttribute(Qt::WA_Hover);
}
}
@@ -456,12 +456,12 @@ void ManhattanStyle::drawPrimitive(PrimitiveElement element, const QStyleOption
painter->fillRect(filledRect, option->palette.base());
if (option->state & State_Enabled)
- Utils::StyleHelper::drawCornerImage(d->lineeditImage, painter, option->rect, 5, 5, 5, 5);
+ StyleHelper::drawCornerImage(d->lineeditImage, painter, option->rect, 5, 5, 5, 5);
else
- Utils::StyleHelper::drawCornerImage(d->lineeditImage_disabled, painter, option->rect, 5, 5, 5, 5);
+ StyleHelper::drawCornerImage(d->lineeditImage_disabled, painter, option->rect, 5, 5, 5, 5);
if (option->state & State_HasFocus || option->state & State_MouseOver) {
- QColor hover = Utils::StyleHelper::baseColor();
+ QColor hover = StyleHelper::baseColor();
if (state & State_HasFocus)
hover.setAlpha(100);
else
@@ -518,12 +518,12 @@ void ManhattanStyle::drawPrimitive(PrimitiveElement element, const QStyleOption
{
if (creatorTheme()->widgetStyle() == Theme::StyleDefault) {
painter->save();
- QLinearGradient grad = Utils::StyleHelper::statusBarGradient(rect);
+ QLinearGradient grad = StyleHelper::statusBarGradient(rect);
painter->fillRect(rect, grad);
painter->setPen(QColor(255, 255, 255, 60));
painter->drawLine(rect.topLeft() + QPoint(0,1),
rect.topRight()+ QPoint(0,1));
- painter->setPen(Utils::StyleHelper::borderColor().darker(110)); //TODO: make themable
+ painter->setPen(StyleHelper::borderColor().darker(110)); //TODO: make themable
painter->drawLine(rect.topLeft(), rect.topRight());
painter->restore();
} else {
@@ -534,7 +534,7 @@ void ManhattanStyle::drawPrimitive(PrimitiveElement element, const QStyleOption
case PE_IndicatorToolBarSeparator:
{
- QColor separatorColor = Utils::StyleHelper::borderColor();
+ QColor separatorColor = StyleHelper::borderColor();
separatorColor.setAlpha(100);
painter->setPen(separatorColor);
const int margin = 6;
@@ -578,10 +578,10 @@ void ManhattanStyle::drawPrimitive(PrimitiveElement element, const QStyleOption
}
painter->setPen(Qt::NoPen);
- QColor dark = Utils::StyleHelper::borderColor();
+ QColor dark = StyleHelper::borderColor();
dark.setAlphaF(0.4);
- QColor light = Utils::StyleHelper::baseColor();
+ QColor light = StyleHelper::baseColor();
light.setAlphaF(0.4);
painter->fillPath(path, light);
@@ -601,7 +601,7 @@ void ManhattanStyle::drawPrimitive(PrimitiveElement element, const QStyleOption
case PE_IndicatorArrowRight:
case PE_IndicatorArrowLeft:
{
- Utils::StyleHelper::drawArrow(element, painter, option);
+ StyleHelper::drawArrow(element, painter, option);
}
break;
@@ -622,7 +622,7 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
if (creatorTheme()->widgetStyle() == Theme::StyleFlat)
painter->fillRect(option->rect, creatorTheme()->color(Theme::BackgroundColorSelected));
else
- painter->fillRect(option->rect, Utils::StyleHelper::borderColor());
+ painter->fillRect(option->rect, StyleHelper::borderColor());
break;
case CE_TabBarTabShape:
@@ -648,14 +648,14 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
case CE_MenuBarItem:
painter->save();
if (const QStyleOptionMenuItem *mbi = qstyleoption_cast<const QStyleOptionMenuItem *>(option)) {
- QColor highlightOutline = Utils::StyleHelper::borderColor().lighter(120);
+ QColor highlightOutline = StyleHelper::borderColor().lighter(120);
const bool act = mbi->state & (State_Sunken | State_Selected);
const bool dis = !(mbi->state & State_Enabled);
if (creatorTheme()->widgetStyle() == Theme::StyleFlat)
painter->fillRect(option->rect, creatorTheme()->color(Theme::MenuBarItemBackgroundColor));
else
- Utils::StyleHelper::menuGradient(painter, option->rect, option->rect);
+ StyleHelper::menuGradient(painter, option->rect, option->rect);
QStyleOptionMenuItem item = *mbi;
item.rect = mbi->rect;
@@ -668,7 +668,7 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
if (act) {
// Fill|
- QColor baseColor = Utils::StyleHelper::baseColor();
+ QColor baseColor = StyleHelper::baseColor();
QLinearGradient grad(option->rect.topLeft(), option->rect.bottomLeft());
grad.setColorAt(0, baseColor.lighter(120));
grad.setColorAt(1, baseColor.lighter(130));
@@ -795,9 +795,9 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
case CE_MenuBarEmptyArea: {
if (creatorTheme()->widgetStyle() == Theme::StyleDefault) {
- Utils::StyleHelper::menuGradient(painter, option->rect, option->rect);
+ StyleHelper::menuGradient(painter, option->rect, option->rect);
painter->save();
- painter->setPen(Utils::StyleHelper::borderColor());
+ painter->setPen(StyleHelper::borderColor());
painter->drawLine(option->rect.bottomLeft() + QPointF(0.5, 0.5),
option->rect.bottomRight() + QPointF(0.5, 0.5));
painter->restore();
@@ -827,16 +827,16 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
if (creatorTheme()->widgetStyle() == Theme::StyleFlat)
painter->fillRect (rect, creatorTheme()->color(Theme::ToolBarBackgroundColor));
else
- Utils::StyleHelper::horizontalGradient(painter, gradientSpan, rect, drawLightColored);
+ StyleHelper::horizontalGradient(painter, gradientSpan, rect, drawLightColored);
} else {
if (creatorTheme()->widgetStyle() == Theme::StyleFlat)
painter->fillRect (rect, creatorTheme()->color(Theme::ToolBarBackgroundColor));
else
- Utils::StyleHelper::verticalGradient(painter, gradientSpan, rect, drawLightColored);
+ StyleHelper::verticalGradient(painter, gradientSpan, rect, drawLightColored);
}
if (!drawLightColored) {
- painter->setPen(Utils::StyleHelper::borderColor());
+ painter->setPen(StyleHelper::borderColor());
}
else
painter->setPen(QColor(0x888888));
@@ -845,7 +845,7 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
// Note: This is a hack to determine if the
// toolbar should draw the top or bottom outline
// (needed for the find toolbar for instance)
- QColor lighter(Utils::StyleHelper::sidebarHighlight());
+ QColor lighter(StyleHelper::sidebarHighlight());
if (drawLightColored)
lighter = QColor(255, 255, 255, 180);
if (widget && widget->property("topBorder").toBool()) {
@@ -931,7 +931,7 @@ void ManhattanStyle::drawComplexControl(ComplexControl control, const QStyleOpti
if (mflags & (State_Sunken)) {
QColor shade(0, 0, 0, 50);
painter->fillRect(tool.rect.adjusted(0, -1, 1, 1), shade);
- } else if (!Utils::HostOsInfo::isMacHost() && (mflags & State_MouseOver)) {
+ } else if (!HostOsInfo::isMacHost() && (mflags & State_MouseOver)) {
QColor shade(255, 255, 255, 50);
painter->fillRect(tool.rect.adjusted(0, -1, 1, 1), shade);
}
diff --git a/src/plugins/coreplugin/messagebox.cpp b/src/plugins/coreplugin/messagebox.cpp
new file mode 100644
index 00000000000..2fbc0da573e
--- /dev/null
+++ b/src/plugins/coreplugin/messagebox.cpp
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "messagebox.h"
+
+#include <QMessageBox>
+
+#include "icore.h"
+
+namespace Core {
+namespace AsynchronousMessageBox {
+
+namespace {
+
+void message(QMessageBox::Icon icon, const QString &title, const QString &desciption)
+{
+ QMessageBox *messageBox = new QMessageBox(icon,
+ title,
+ desciption,
+ QMessageBox::Ok,
+ Core::ICore::dialogParent());
+
+ messageBox->setAttribute(Qt::WA_DeleteOnClose);
+ messageBox->setModal(true);
+ messageBox->show();
+}
+}
+
+void warning(const QString &title, const QString &desciption)
+{
+ message(QMessageBox::Warning, title, desciption);
+}
+
+void information(const QString &title, const QString &desciption)
+{
+ message(QMessageBox::Information, title, desciption);
+}
+
+void critical(const QString &title, const QString &desciption)
+{
+ message(QMessageBox::Critical, title, desciption);
+}
+}
+
+}
diff --git a/src/plugins/coreplugin/messagebox.h b/src/plugins/coreplugin/messagebox.h
new file mode 100644
index 00000000000..2452943f20a
--- /dev/null
+++ b/src/plugins/coreplugin/messagebox.h
@@ -0,0 +1,50 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 MESSAGEBOX_H
+#define MESSAGEBOX_H
+
+#include "core_global.h"
+
+QT_BEGIN_NAMESPACE
+class QString;
+QT_END_NAMESPACE
+
+namespace Core {
+namespace AsynchronousMessageBox {
+
+ CORE_EXPORT void warning(const QString &title, const QString &desciption);
+ CORE_EXPORT void information(const QString &title, const QString &desciption);
+ CORE_EXPORT void critical(const QString &title, const QString &desciption);
+}
+}
+
+#endif // MESSAGEBOX_H
+
diff --git a/src/plugins/coreplugin/messagemanager.cpp b/src/plugins/coreplugin/messagemanager.cpp
index 4a8e558cc76..1895e563a8d 100644
--- a/src/plugins/coreplugin/messagemanager.cpp
+++ b/src/plugins/coreplugin/messagemanager.cpp
@@ -47,7 +47,7 @@ MessageManager::MessageManager()
{
m_instance = this;
m_messageOutputWindow = 0;
- qRegisterMetaType<Core::MessageManager::PrintToOutputPaneFlags>();
+ qRegisterMetaType<MessageManager::PrintToOutputPaneFlags>();
}
MessageManager::~MessageManager()
@@ -85,7 +85,7 @@ void MessageManager::write(const QString &text, PrintToOutputPaneFlags flags)
} else if (flags & Silent) {
// Do nothing
} else {
- m_messageOutputWindow->popup(Core::IOutputPane::Flag(int(flags)));
+ m_messageOutputWindow->popup(IOutputPane::Flag(int(flags)));
}
m_messageOutputWindow->append(text + QLatin1Char('\n'));
diff --git a/src/plugins/coreplugin/messageoutputwindow.cpp b/src/plugins/coreplugin/messageoutputwindow.cpp
index 960e2ee36dc..605c6e82661 100644
--- a/src/plugins/coreplugin/messageoutputwindow.cpp
+++ b/src/plugins/coreplugin/messageoutputwindow.cpp
@@ -36,11 +36,12 @@
#include <aggregation/aggregate.h>
-using namespace Core::Internal;
+namespace Core {
+namespace Internal {
MessageOutputWindow::MessageOutputWindow()
{
- m_widget = new Core::OutputWindow(Core::Context(Core::Constants::C_GENERAL_OUTPUT_PANE));
+ m_widget = new OutputWindow(Context(Constants::C_GENERAL_OUTPUT_PANE));
m_widget->setReadOnly(true);
// Let selected text be colored as if the text edit was editable,
// otherwise the highlight for searching is too light
@@ -52,7 +53,7 @@ MessageOutputWindow::MessageOutputWindow()
m_widget->setPalette(p);
Aggregation::Aggregate *agg = new Aggregation::Aggregate;
agg->add(m_widget);
- agg->add(new Core::BaseTextFind(m_widget));
+ agg->add(new BaseTextFind(m_widget));
}
MessageOutputWindow::~MessageOutputWindow()
@@ -129,3 +130,6 @@ bool MessageOutputWindow::canNavigate() const
{
return false;
}
+
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/messageoutputwindow.h b/src/plugins/coreplugin/messageoutputwindow.h
index 56ac0a54751..b1d3d8a4670 100644
--- a/src/plugins/coreplugin/messageoutputwindow.h
+++ b/src/plugins/coreplugin/messageoutputwindow.h
@@ -38,7 +38,7 @@ class OutputWindow;
namespace Internal {
-class MessageOutputWindow : public Core::IOutputPane
+class MessageOutputWindow : public IOutputPane
{
Q_OBJECT
diff --git a/src/plugins/coreplugin/mimedatabase.cpp b/src/plugins/coreplugin/mimedatabase.cpp
index 048f499de54..f1b950c91f6 100644
--- a/src/plugins/coreplugin/mimedatabase.cpp
+++ b/src/plugins/coreplugin/mimedatabase.cpp
@@ -1801,7 +1801,7 @@ QList<MimeGlobPattern> MimeDatabasePrivate::toGlobPatterns(const QStringList &pa
{
QList<MimeGlobPattern> globPatterns;
foreach (const QString &pattern, patterns)
- globPatterns.append(Core::MimeGlobPattern(pattern, weight));
+ globPatterns.append(MimeGlobPattern(pattern, weight));
return globPatterns;
}
diff --git a/src/plugins/coreplugin/mimetypemagicdialog.cpp b/src/plugins/coreplugin/mimetypemagicdialog.cpp
index 14985aceb07..a265fe54958 100644
--- a/src/plugins/coreplugin/mimetypemagicdialog.cpp
+++ b/src/plugins/coreplugin/mimetypemagicdialog.cpp
@@ -61,7 +61,7 @@ void MimeTypeMagicDialog::validateAccept()
{
if (ui.valueLineEdit->text().isEmpty()
|| (ui.byteRadioButton->isChecked()
- && !Core::MagicByteRule::validateByteSequence(ui.valueLineEdit->text()))) {
+ && !MagicByteRule::validateByteSequence(ui.valueLineEdit->text()))) {
QMessageBox::critical(0, tr("Error"), tr("Not a valid byte pattern."));
return;
}
@@ -71,7 +71,7 @@ void MimeTypeMagicDialog::validateAccept()
void MimeTypeMagicDialog::setMagicData(const MagicData &data)
{
ui.valueLineEdit->setText(data.m_value);
- if (data.m_type == Core::MagicStringRule::kMatchType)
+ if (data.m_type == MagicStringRule::kMatchType)
ui.stringRadioButton->setChecked(true);
else
ui.byteRadioButton->setChecked(true);
@@ -85,9 +85,9 @@ MagicData MimeTypeMagicDialog::magicData() const
MagicData data;
data.m_value = ui.valueLineEdit->text();
if (ui.stringRadioButton->isChecked())
- data.m_type = Core::MagicStringRule::kMatchType;
+ data.m_type = MagicStringRule::kMatchType;
else
- data.m_type = Core::MagicByteRule::kMatchType;
+ data.m_type = MagicByteRule::kMatchType;
data.m_start = ui.startRangeSpinBox->value();
data.m_end = ui.endRangeSpinBox->value();
data.m_priority = ui.prioritySpinBox->value();
diff --git a/src/plugins/coreplugin/mimetypesettings.cpp b/src/plugins/coreplugin/mimetypesettings.cpp
index 3b8966ed362..df6b0871fcc 100644
--- a/src/plugins/coreplugin/mimetypesettings.cpp
+++ b/src/plugins/coreplugin/mimetypesettings.cpp
@@ -543,12 +543,12 @@ MimeTypeSettings::MimeTypeSettings(QObject *parent)
: IOptionsPage(parent)
, d(new MimeTypeSettingsPrivate)
{
- setId(Core::Constants::SETTINGS_ID_MIMETYPES);
+ setId(Constants::SETTINGS_ID_MIMETYPES);
setDisplayName(tr("MIME Types"));
- setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
+ setCategory(Constants::SETTINGS_CATEGORY_CORE);
setDisplayCategory(QCoreApplication::translate("Core",
- Core::Constants::SETTINGS_TR_CATEGORY_CORE));
- setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
+ Constants::SETTINGS_TR_CATEGORY_CORE));
+ setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CORE_ICON));
}
MimeTypeSettings::~MimeTypeSettings()
diff --git a/src/plugins/coreplugin/navigationsubwidget.cpp b/src/plugins/coreplugin/navigationsubwidget.cpp
index 75e6a5962a6..00bbd969e00 100644
--- a/src/plugins/coreplugin/navigationsubwidget.cpp
+++ b/src/plugins/coreplugin/navigationsubwidget.cpp
@@ -41,6 +41,7 @@
#include <QDebug>
#include <QHBoxLayout>
+#include <QMenu>
#include <QResizeEvent>
#include <QToolButton>
@@ -75,12 +76,18 @@ NavigationSubWidget::NavigationSubWidget(NavigationWidget *parentWidget, int pos
QToolButton *splitAction = new QToolButton();
splitAction->setIcon(QIcon(QLatin1String(Constants::ICON_SPLIT_HORIZONTAL)));
splitAction->setToolTip(tr("Split"));
- QToolButton *close = new QToolButton();
- close->setIcon(QIcon(QLatin1String(Constants::ICON_BUTTON_CLOSE)));
- close->setToolTip(tr("Close"));
+ splitAction->setPopupMode(QToolButton::InstantPopup);
+ splitAction->setProperty("noArrow", true);
+ m_splitMenu = new QMenu(splitAction);
+ splitAction->setMenu(m_splitMenu);
+ connect(m_splitMenu, &QMenu::aboutToShow, this, &NavigationSubWidget::populateSplitMenu);
+
+ m_closeButton = new QToolButton();
+ m_closeButton->setIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
+ m_closeButton->setToolTip(tr("Close"));
toolBarLayout->addWidget(splitAction);
- toolBarLayout->addWidget(close);
+ toolBarLayout->addWidget(m_closeButton);
QVBoxLayout *lay = new QVBoxLayout();
lay->setMargin(0);
@@ -88,8 +95,7 @@ NavigationSubWidget::NavigationSubWidget(NavigationWidget *parentWidget, int pos
setLayout(lay);
lay->addWidget(m_toolBar);
- connect(splitAction, SIGNAL(clicked()), this, SIGNAL(splitMe()));
- connect(close, SIGNAL(clicked()), this, SIGNAL(closeMe()));
+ connect(m_closeButton, SIGNAL(clicked()), this, SIGNAL(closeMe()));
setFactoryIndex(factoryIndex);
@@ -136,6 +142,18 @@ void NavigationSubWidget::comboBoxIndexChanged(int factoryIndex)
restoreSettings();
}
+void NavigationSubWidget::populateSplitMenu()
+{
+ m_splitMenu->clear();
+ QAbstractItemModel *factoryModel = m_parentWidget->factoryModel();
+ int count = factoryModel->rowCount();
+ for (int i = 0; i < count; ++i) {
+ QModelIndex index = factoryModel->index(i, 0);
+ QAction *action = m_splitMenu->addAction(factoryModel->data(index).toString());
+ connect(action, &QAction::triggered, this, [this, i]() { emit splitMe(i); });
+ }
+}
+
void NavigationSubWidget::setFocusWidget()
{
if (m_navigationWidget)
@@ -171,6 +189,11 @@ Core::Command *NavigationSubWidget::command(const QString &title) const
return 0;
}
+void NavigationSubWidget::setCloseIcon(const QIcon &icon)
+{
+ m_closeButton->setIcon(icon);
+}
+
int NavigationSubWidget::factoryIndex() const
{
return m_navigationComboBox->currentIndex();
diff --git a/src/plugins/coreplugin/navigationsubwidget.h b/src/plugins/coreplugin/navigationsubwidget.h
index 359a13533b1..6d49c850269 100644
--- a/src/plugins/coreplugin/navigationsubwidget.h
+++ b/src/plugins/coreplugin/navigationsubwidget.h
@@ -36,6 +36,7 @@
#include <QList>
QT_BEGIN_NAMESPACE
+class QMenu;
class QToolButton;
QT_END_NAMESPACE
@@ -68,18 +69,23 @@ public:
void saveSettings();
void restoreSettings();
- Core::Command *command(const QString &title) const;
+ Command *command(const QString &title) const;
+ void setCloseIcon(const QIcon &icon);
signals:
- void splitMe();
+ void splitMe(int factoryIndex);
void closeMe();
private slots:
void comboBoxIndexChanged(int);
private:
+ void populateSplitMenu();
+
NavigationWidget *m_parentWidget;
QComboBox *m_navigationComboBox;
+ QMenu *m_splitMenu;
+ QToolButton *m_closeButton;
QWidget *m_navigationWidget;
INavigationWidgetFactory *m_navigationWidgetFactory;
Utils::StyledBar *m_toolBar;
@@ -100,7 +106,7 @@ protected:
bool event(QEvent *event);
private:
- virtual const Core::Command *command(const QString &text) const = 0;
+ virtual const Command *command(const QString &text) const = 0;
};
@@ -113,7 +119,7 @@ public:
m_navSubWidget(navSubWidget) {}
private:
- virtual const Core::Command *command(const QString &text) const
+ virtual const Command *command(const QString &text) const
{ return m_navSubWidget->command(text); }
NavigationSubWidget *m_navSubWidget;
diff --git a/src/plugins/coreplugin/navigationwidget.cpp b/src/plugins/coreplugin/navigationwidget.cpp
index 42bf121e328..790657dbd8d 100644
--- a/src/plugins/coreplugin/navigationwidget.cpp
+++ b/src/plugins/coreplugin/navigationwidget.cpp
@@ -38,6 +38,7 @@
#include "actionmanager/actionmanager.h"
#include "actionmanager/command.h"
#include "id.h"
+#include "imode.h"
#include <QDebug>
#include <QSettings>
@@ -58,13 +59,13 @@ NavigationWidgetPlaceHolder* NavigationWidgetPlaceHolder::current()
return m_current;
}
-NavigationWidgetPlaceHolder::NavigationWidgetPlaceHolder(Core::IMode *mode, QWidget *parent)
+NavigationWidgetPlaceHolder::NavigationWidgetPlaceHolder(IMode *mode, QWidget *parent)
:QWidget(parent), m_mode(mode)
{
setLayout(new QVBoxLayout);
layout()->setMargin(0);
- connect(Core::ModeManager::instance(), SIGNAL(currentModeAboutToChange(Core::IMode*)),
- this, SLOT(currentModeAboutToChange(Core::IMode*)));
+ connect(ModeManager::instance(), &ModeManager::currentModeAboutToChange,
+ this, &NavigationWidgetPlaceHolder::currentModeAboutToChange);
}
NavigationWidgetPlaceHolder::~NavigationWidgetPlaceHolder()
@@ -107,7 +108,7 @@ void NavigationWidgetPlaceHolder::applyStoredSize(int width)
// m_current points to the current PlaceHolder, or zero if there
// is no PlaceHolder in this mode
// And that the parent of the NavigationWidget gets the correct parent
-void NavigationWidgetPlaceHolder::currentModeAboutToChange(Core::IMode *mode)
+void NavigationWidgetPlaceHolder::currentModeAboutToChange(IMode *mode)
{
NavigationWidget *navigationWidget = NavigationWidget::instance();
@@ -137,8 +138,8 @@ struct NavigationWidgetPrivate
~NavigationWidgetPrivate() { delete m_factoryModel; }
QList<Internal::NavigationSubWidget *> m_subWidgets;
- QHash<QAction *, Core::Id> m_actionMap;
- QHash<Core::Id, Core::Command *> m_commandMap;
+ QHash<QAction *, Id> m_actionMap;
+ QHash<Id, Command *> m_commandMap;
QStandardItemModel *m_factoryModel;
bool m_shown;
@@ -180,7 +181,7 @@ NavigationWidget *NavigationWidget::instance()
void NavigationWidget::setFactories(const QList<INavigationWidgetFactory *> &factories)
{
- Context navicontext(Core::Constants::C_NAVIGATION_PANE);
+ Context navicontext(Constants::C_NAVIGATION_PANE);
foreach (INavigationWidgetFactory *factory, factories) {
const Id id = factory->id();
@@ -245,12 +246,19 @@ Internal::NavigationSubWidget *NavigationWidget::insertSubItem(int position,int
d->m_subWidgets.at(pos)->setPosition(pos + 1);
}
+ if (!d->m_subWidgets.isEmpty()) // Make all icons the bottom icon
+ d->m_subWidgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
+
Internal::NavigationSubWidget *nsw = new Internal::NavigationSubWidget(this, position, index);
- connect(nsw, SIGNAL(splitMe()), this, SLOT(splitSubWidget()));
+ connect(nsw, &Internal::NavigationSubWidget::splitMe,
+ this, &NavigationWidget::splitSubWidget);
connect(nsw, SIGNAL(closeMe()), this, SLOT(closeSubWidget()));
insertWidget(position, nsw);
d->m_subWidgets.insert(position, nsw);
-
+ if (d->m_subWidgets.size() == 1)
+ d->m_subWidgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_LEFT)));
+ else
+ d->m_subWidgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_TOP)));
return nsw;
}
@@ -280,11 +288,11 @@ void NavigationWidget::activateSubWidget(Id factoryId)
}
}
-void NavigationWidget::splitSubWidget()
+void NavigationWidget::splitSubWidget(int factoryIndex)
{
Internal::NavigationSubWidget *original = qobject_cast<Internal::NavigationSubWidget *>(sender());
int pos = indexOf(original) + 1;
- insertSubItem(pos, original->factoryIndex());
+ insertSubItem(pos, factoryIndex);
}
void NavigationWidget::closeSubWidget()
@@ -295,6 +303,11 @@ void NavigationWidget::closeSubWidget()
d->m_subWidgets.removeOne(subWidget);
subWidget->hide();
subWidget->deleteLater();
+ // update close button of top item
+ if (d->m_subWidgets.size() == 1)
+ d->m_subWidgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_LEFT)));
+ else
+ d->m_subWidgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_TOP)));
} else {
setShown(false);
}
@@ -417,7 +430,7 @@ void NavigationWidget::setSuppressed(bool b)
int NavigationWidget::factoryIndex(Id id)
{
for (int row = 0; row < d->m_factoryModel->rowCount(); ++row) {
- if (d->m_factoryModel->data(d->m_factoryModel->index(row, 0), FactoryIdRole).value<Core::Id>() == id)
+ if (d->m_factoryModel->data(d->m_factoryModel->index(row, 0), FactoryIdRole).value<Id>() == id)
return row;
}
return -1;
diff --git a/src/plugins/coreplugin/navigationwidget.h b/src/plugins/coreplugin/navigationwidget.h
index 4a85e2e4100..f83356d6d9e 100644
--- a/src/plugins/coreplugin/navigationwidget.h
+++ b/src/plugins/coreplugin/navigationwidget.h
@@ -56,16 +56,15 @@ class CORE_EXPORT NavigationWidgetPlaceHolder : public QWidget
friend class Core::NavigationWidget;
public:
- explicit NavigationWidgetPlaceHolder(Core::IMode *mode, QWidget *parent = 0);
+ explicit NavigationWidgetPlaceHolder(IMode *mode, QWidget *parent = 0);
virtual ~NavigationWidgetPlaceHolder();
static NavigationWidgetPlaceHolder* current();
void applyStoredSize(int width);
-private slots:
- void currentModeAboutToChange(Core::IMode *);
-
private:
- Core::IMode *m_mode;
+ void currentModeAboutToChange(IMode *);
+
+ IMode *m_mode;
static NavigationWidgetPlaceHolder* m_current;
};
@@ -104,7 +103,7 @@ public:
// Called from the place holders
void placeHolderChanged(NavigationWidgetPlaceHolder *holder);
- QHash<Id, Core::Command *> commandMap() const;
+ QHash<Id, Command *> commandMap() const;
QAbstractItemModel *factoryModel() const;
protected:
@@ -112,7 +111,7 @@ protected:
private slots:
void activateSubWidget();
- void splitSubWidget();
+ void splitSubWidget(int factoryIndex);
void closeSubWidget();
private:
diff --git a/src/plugins/coreplugin/outputpane.cpp b/src/plugins/coreplugin/outputpane.cpp
index eca9b11e682..cea6faa4249 100644
--- a/src/plugins/coreplugin/outputpane.cpp
+++ b/src/plugins/coreplugin/outputpane.cpp
@@ -28,33 +28,33 @@
**
****************************************************************************/
+#include "imode.h"
+#include "modemanager.h"
#include "outputpane.h"
#include "outputpanemanager.h"
-#include "modemanager.h"
-
#include <QSplitter>
#include <QVBoxLayout>
namespace Core {
struct OutputPanePlaceHolderPrivate {
- explicit OutputPanePlaceHolderPrivate(Core::IMode *mode, QSplitter *parent);
+ explicit OutputPanePlaceHolderPrivate(IMode *mode, QSplitter *parent);
- Core::IMode *m_mode;
+ IMode *m_mode;
QSplitter *m_splitter;
int m_lastNonMaxSize;
static OutputPanePlaceHolder* m_current;
};
-OutputPanePlaceHolderPrivate::OutputPanePlaceHolderPrivate(Core::IMode *mode, QSplitter *parent) :
+OutputPanePlaceHolderPrivate::OutputPanePlaceHolderPrivate(IMode *mode, QSplitter *parent) :
m_mode(mode), m_splitter(parent), m_lastNonMaxSize(0)
{
}
OutputPanePlaceHolder *OutputPanePlaceHolderPrivate::m_current = 0;
-OutputPanePlaceHolder::OutputPanePlaceHolder(Core::IMode *mode, QSplitter* parent)
+OutputPanePlaceHolder::OutputPanePlaceHolder(IMode *mode, QSplitter* parent)
: QWidget(parent), d(new OutputPanePlaceHolderPrivate(mode, parent))
{
setVisible(false);
@@ -65,8 +65,8 @@ OutputPanePlaceHolder::OutputPanePlaceHolder(Core::IMode *mode, QSplitter* paren
sp.setHorizontalStretch(0);
setSizePolicy(sp);
layout()->setMargin(0);
- connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
- this, SLOT(currentModeChanged(Core::IMode*)));
+ connect(ModeManager::instance(), &ModeManager::currentModeChanged,
+ this, &OutputPanePlaceHolder::currentModeChanged);
}
OutputPanePlaceHolder::~OutputPanePlaceHolder()
@@ -80,7 +80,7 @@ OutputPanePlaceHolder::~OutputPanePlaceHolder()
delete d;
}
-void OutputPanePlaceHolder::currentModeChanged(Core::IMode *mode)
+void OutputPanePlaceHolder::currentModeChanged(IMode *mode)
{
if (d->m_current == this) {
d->m_current = 0;
diff --git a/src/plugins/coreplugin/outputpane.h b/src/plugins/coreplugin/outputpane.h
index 32a6fe23ecb..c47df26e64b 100644
--- a/src/plugins/coreplugin/outputpane.h
+++ b/src/plugins/coreplugin/outputpane.h
@@ -52,7 +52,7 @@ class CORE_EXPORT OutputPanePlaceHolder : public QWidget
friend class Core::Internal::OutputPaneManager; // needs to set m_visible and thus access m_current
public:
- explicit OutputPanePlaceHolder(Core::IMode *mode, QSplitter *parent = 0);
+ explicit OutputPanePlaceHolder(IMode *mode, QSplitter *parent = 0);
~OutputPanePlaceHolder();
static OutputPanePlaceHolder *getCurrent();
@@ -63,10 +63,8 @@ public:
void setDefaultHeight(int height);
void ensureSizeHintAsMinimum();
-private slots:
- void currentModeChanged(Core::IMode *);
-
private:
+ void currentModeChanged(IMode *);
bool canMaximizeOrMinimize() const;
void maximizeOrMinimize(bool maximize);
diff --git a/src/plugins/coreplugin/outputpanemanager.cpp b/src/plugins/coreplugin/outputpanemanager.cpp
index 12d96d3b7e3..e95ded4b2ab 100644
--- a/src/plugins/coreplugin/outputpanemanager.cpp
+++ b/src/plugins/coreplugin/outputpanemanager.cpp
@@ -150,7 +150,7 @@ OutputPaneManager::OutputPaneManager(QWidget *parent) :
m_minMaxAction->setIcon(m_maximizeIcon);
m_minMaxAction->setText(tr("Maximize Output Pane"));
- m_closeButton->setIcon(QIcon(QLatin1String(Constants::ICON_BUTTON_CLOSE)));
+ m_closeButton->setIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
connect(m_closeButton, SIGNAL(clicked()), this, SLOT(slotHide()));
connect(ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
@@ -158,12 +158,12 @@ OutputPaneManager::OutputPaneManager(QWidget *parent) :
QVBoxLayout *mainlayout = new QVBoxLayout;
mainlayout->setSpacing(0);
mainlayout->setMargin(0);
- m_toolBar = new Utils::StyledBar;
+ m_toolBar = new StyledBar;
QHBoxLayout *toolLayout = new QHBoxLayout(m_toolBar);
toolLayout->setMargin(0);
toolLayout->setSpacing(0);
toolLayout->addWidget(m_titleLabel);
- toolLayout->addWidget(new Utils::StyledSeparator);
+ toolLayout->addWidget(new StyledSeparator);
m_clearButton = new QToolButton;
toolLayout->addWidget(m_clearButton);
m_prevToolButton = new QToolButton;
@@ -175,7 +175,7 @@ OutputPaneManager::OutputPaneManager(QWidget *parent) :
toolLayout->addWidget(m_closeButton);
mainlayout->addWidget(m_toolBar);
mainlayout->addWidget(m_outputWidgetPane, 10);
- mainlayout->addWidget(new Core::FindToolBarPlaceHolder(this));
+ mainlayout->addWidget(new FindToolBarPlaceHolder(this));
setLayout(mainlayout);
m_buttonsWidget = new QWidget;
@@ -196,7 +196,7 @@ QWidget *OutputPaneManager::buttonsWidget()
// Return shortcut as Ctrl+<number>
static inline int paneShortCut(int number)
{
- const int modifier = Utils::HostOsInfo::isMacHost() ? Qt::CTRL : Qt::ALT;
+ const int modifier = HostOsInfo::isMacHost() ? Qt::CTRL : Qt::ALT;
return modifier | (Qt::Key_0 + number);
}
@@ -313,7 +313,7 @@ void OutputPaneManager::shortcutTriggered()
QTC_ASSERT(action, return);
int idx = m_actions.indexOf(action);
QTC_ASSERT(idx != -1, return);
- Core::IOutputPane *outputPane = m_panes.at(idx);
+ IOutputPane *outputPane = m_panes.at(idx);
// Now check the special case, the output window is already visible,
// we are already on that page but the outputpane doesn't have focus
// then just give it focus.
@@ -413,7 +413,7 @@ void OutputPaneManager::slotHide()
QTC_ASSERT(idx >= 0, return);
m_buttons.at(idx)->setChecked(false);
m_panes.value(idx)->visibilityChanged(false);
- if (IEditor *editor = Core::EditorManager::currentEditor()) {
+ if (IEditor *editor = EditorManager::currentEditor()) {
QWidget *w = editor->widget()->focusWidget();
if (!w)
w = editor->widget();
@@ -662,11 +662,11 @@ QSize OutputPaneToggleButton::sizeHint() const
void OutputPaneToggleButton::paintEvent(QPaintEvent*)
{
- static const QImage panelButton(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button.png")));
- static const QImage panelButtonHover(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_hover.png")));
- static const QImage panelButtonPressed(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_pressed.png")));
- static const QImage panelButtonChecked(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_checked.png")));
- static const QImage panelButtonCheckedHover(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_checked_hover.png")));
+ static const QImage panelButton(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button.png")));
+ static const QImage panelButtonHover(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_hover.png")));
+ static const QImage panelButtonPressed(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_pressed.png")));
+ static const QImage panelButtonChecked(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_checked.png")));
+ static const QImage panelButtonCheckedHover(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_button_checked_hover.png")));
const QFontMetrics fm = fontMetrics();
const int baseLine = (height() - fm.height() + 1) / 2 + fm.ascent();
@@ -676,7 +676,7 @@ void OutputPaneToggleButton::paintEvent(QPaintEvent*)
QStyleOption styleOption;
styleOption.initFrom(this);
- const bool hovered = !Utils::HostOsInfo::isMacHost() && (styleOption.state & QStyle::State_MouseOver);
+ const bool hovered = !HostOsInfo::isMacHost() && (styleOption.state & QStyle::State_MouseOver);
const QImage *image = 0;
if (creatorTheme()->widgetStyle() == Theme::StyleDefault) {
@@ -687,7 +687,7 @@ void OutputPaneToggleButton::paintEvent(QPaintEvent*)
else
image = hovered ? &panelButtonHover : &panelButton;
if (image)
- Utils::StyleHelper::drawCornerImage(*image, &p, rect(), numberAreaWidth, buttonBorderWidth, buttonBorderWidth, buttonBorderWidth);
+ StyleHelper::drawCornerImage(*image, &p, rect(), numberAreaWidth, buttonBorderWidth, buttonBorderWidth, buttonBorderWidth);
} else {
QColor c;
if (isChecked()) {
@@ -775,8 +775,8 @@ void OutputPaneManageButton::paintEvent(QPaintEvent*)
{
QPainter p(this);
if (creatorTheme()->widgetStyle() == Theme::StyleDefault) {
- static const QImage button(Utils::StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_manage_button.png")));
- Utils::StyleHelper::drawCornerImage(button, &p, rect(), buttonBorderWidth, buttonBorderWidth, buttonBorderWidth, buttonBorderWidth);
+ static const QImage button(StyleHelper::dpiSpecificImageFile(QStringLiteral(":/core/images/panel_manage_button.png")));
+ StyleHelper::drawCornerImage(button, &p, rect(), buttonBorderWidth, buttonBorderWidth, buttonBorderWidth, buttonBorderWidth);
}
QStyle *s = style();
QStyleOption arrowOpt;
diff --git a/src/plugins/coreplugin/outputwindow.cpp b/src/plugins/coreplugin/outputwindow.cpp
index f0f5e1fe57b..50914b7fc88 100644
--- a/src/plugins/coreplugin/outputwindow.cpp
+++ b/src/plugins/coreplugin/outputwindow.cpp
@@ -45,7 +45,7 @@ namespace Core {
/*******************/
-OutputWindow::OutputWindow(Core::Context context, QWidget *parent)
+OutputWindow::OutputWindow(Context context, QWidget *parent)
: QPlainTextEdit(parent)
, m_formatter(0)
, m_enforceNewline(false)
@@ -60,7 +60,7 @@ OutputWindow::OutputWindow(Core::Context context, QWidget *parent)
setMouseTracking(true);
setUndoRedoEnabled(false);
- m_outputWindowContext = new Core::IContext;
+ m_outputWindowContext = new IContext;
m_outputWindowContext->setContext(context);
m_outputWindowContext->setWidget(this);
ICore::addContextObject(m_outputWindowContext);
@@ -72,12 +72,12 @@ OutputWindow::OutputWindow(Core::Context context, QWidget *parent)
QAction *pasteAction = new QAction(this);
QAction *selectAllAction = new QAction(this);
- ActionManager::registerAction(undoAction, Core::Constants::UNDO, context);
- ActionManager::registerAction(redoAction, Core::Constants::REDO, context);
- ActionManager::registerAction(cutAction, Core::Constants::CUT, context);
- ActionManager::registerAction(copyAction, Core::Constants::COPY, context);
- ActionManager::registerAction(pasteAction, Core::Constants::PASTE, context);
- ActionManager::registerAction(selectAllAction, Core::Constants::SELECTALL, context);
+ ActionManager::registerAction(undoAction, Constants::UNDO, context);
+ ActionManager::registerAction(redoAction, Constants::REDO, context);
+ ActionManager::registerAction(cutAction, Constants::CUT, context);
+ ActionManager::registerAction(copyAction, Constants::COPY, context);
+ ActionManager::registerAction(pasteAction, Constants::PASTE, context);
+ ActionManager::registerAction(selectAllAction, Constants::SELECTALL, context);
connect(undoAction, SIGNAL(triggered()), this, SLOT(undo()));
connect(redoAction, SIGNAL(triggered()), this, SLOT(redo()));
@@ -99,7 +99,7 @@ OutputWindow::OutputWindow(Core::Context context, QWidget *parent)
OutputWindow::~OutputWindow()
{
- Core::ICore::removeContextObject(m_outputWindowContext);
+ ICore::removeContextObject(m_outputWindowContext);
delete m_outputWindowContext;
}
@@ -203,7 +203,7 @@ void OutputWindow::setMaxLineCount(int count)
void OutputWindow::appendMessage(const QString &output, OutputFormat format)
{
- const QString out = Utils::SynchronousProcess::normalizeNewlines(output);
+ const QString out = SynchronousProcess::normalizeNewlines(output);
setMaximumBlockCount(m_maxLineCount);
const bool atBottom = isScrollbarAtBottom();
@@ -253,7 +253,7 @@ void OutputWindow::appendMessage(const QString &output, OutputFormat format)
// TODO rename
void OutputWindow::appendText(const QString &textIn, const QTextCharFormat &format)
{
- const QString text = Utils::SynchronousProcess::normalizeNewlines(textIn);
+ const QString text = SynchronousProcess::normalizeNewlines(textIn);
if (m_maxLineCount > 0 && document()->blockCount() >= m_maxLineCount)
return;
const bool atBottom = isScrollbarAtBottom();
diff --git a/src/plugins/coreplugin/outputwindow.h b/src/plugins/coreplugin/outputwindow.h
index 151b9cea503..aefbc831073 100644
--- a/src/plugins/coreplugin/outputwindow.h
+++ b/src/plugins/coreplugin/outputwindow.h
@@ -47,7 +47,7 @@ class CORE_EXPORT OutputWindow : public QPlainTextEdit
Q_OBJECT
public:
- OutputWindow(Core::Context context, QWidget *parent = 0);
+ OutputWindow(Context context, QWidget *parent = 0);
~OutputWindow();
Utils::OutputFormatter* formatter() const;
@@ -83,7 +83,7 @@ private:
void enableUndoRedo();
QString doNewlineEnforcement(const QString &out);
- Core::IContext *m_outputWindowContext;
+ IContext *m_outputWindowContext;
Utils::OutputFormatter *m_formatter;
bool m_enforceNewline;
diff --git a/src/plugins/coreplugin/patchtool.cpp b/src/plugins/coreplugin/patchtool.cpp
index 26e9c0f2a43..f57a5865442 100644
--- a/src/plugins/coreplugin/patchtool.cpp
+++ b/src/plugins/coreplugin/patchtool.cpp
@@ -46,7 +46,7 @@ namespace Core {
static QString readLegacyCommand()
{
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
s->beginGroup(QLatin1String(legacySettingsGroupC));
const bool legacyExists = s->contains(QLatin1String(patchCommandKeyC));
@@ -63,7 +63,7 @@ static QString readLegacyCommand()
QString PatchTool::patchCommand()
{
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
const QString defaultCommand = readLegacyCommand(); // replace it with QLatin1String(patchCommandDefaultC) when dropping legacy stuff
@@ -76,7 +76,7 @@ QString PatchTool::patchCommand()
void PatchTool::setPatchCommand(const QString &newCommand)
{
- QSettings *s = Core::ICore::settings();
+ QSettings *s = ICore::settings();
s->beginGroup(QLatin1String(settingsGroupC));
s->setValue(QLatin1String(patchCommandKeyC), newCommand);
s->endGroup();
diff --git a/src/plugins/coreplugin/plugindialog.cpp b/src/plugins/coreplugin/plugindialog.cpp
index 249d4beff39..ee7440db14a 100644
--- a/src/plugins/coreplugin/plugindialog.cpp
+++ b/src/plugins/coreplugin/plugindialog.cpp
@@ -44,9 +44,10 @@
#include <QLabel>
#include <QDebug>
-using namespace Core::Internal;
+namespace Core {
+namespace Internal {
-bool PluginDialog::m_isRestartRequired = false;
+static bool s_isRestartRequired = false;
PluginDialog::PluginDialog(QWidget *parent)
: QDialog(parent),
@@ -64,7 +65,7 @@ PluginDialog::PluginDialog(QWidget *parent)
m_closeButton->setDefault(true);
m_restartRequired = new QLabel(tr("Restart required."), this);
- if (!m_isRestartRequired)
+ if (!s_isRestartRequired)
m_restartRequired->setVisible(false);
QHBoxLayout *hl = new QHBoxLayout;
@@ -77,19 +78,21 @@ PluginDialog::PluginDialog(QWidget *parent)
vl->addLayout(hl);
-
resize(650, 400);
setWindowTitle(tr("Installed Plugins"));
- connect(m_view, SIGNAL(currentPluginChanged(ExtensionSystem::PluginSpec*)),
- this, SLOT(updateButtons()));
- connect(m_view, SIGNAL(pluginActivated(ExtensionSystem::PluginSpec*)),
- this, SLOT(openDetails(ExtensionSystem::PluginSpec*)));
- connect(m_view, SIGNAL(pluginSettingsChanged(ExtensionSystem::PluginSpec*)),
- this, SLOT(updateRestartRequired()));
- connect(m_detailsButton, SIGNAL(clicked()), this, SLOT(openDetails()));
- connect(m_errorDetailsButton, SIGNAL(clicked()), this, SLOT(openErrorDetails()));
- connect(m_closeButton, SIGNAL(clicked()), this, SLOT(closeDialog()));
+ connect(m_view, &ExtensionSystem::PluginView::currentPluginChanged,
+ this, &PluginDialog::updateButtons);
+ connect(m_view, &ExtensionSystem::PluginView::pluginActivated,
+ this, &PluginDialog::openDetails);
+ connect(m_view, &ExtensionSystem::PluginView::pluginSettingsChanged,
+ this, &PluginDialog::updateRestartRequired);
+ connect(m_detailsButton, &QAbstractButton::clicked,
+ [this] { openDetails(m_view->currentPlugin()); });
+ connect(m_errorDetailsButton, &QAbstractButton::clicked,
+ this, &PluginDialog::openErrorDetails);
+ connect(m_closeButton, &QAbstractButton::clicked,
+ this, &PluginDialog::closeDialog);
updateButtons();
}
@@ -102,7 +105,7 @@ void PluginDialog::closeDialog()
void PluginDialog::updateRestartRequired()
{
// just display the notice all the time after once changing something
- m_isRestartRequired = true;
+ s_isRestartRequired = true;
m_restartRequired->setVisible(true);
}
@@ -118,12 +121,6 @@ void PluginDialog::updateButtons()
}
}
-
-void PluginDialog::openDetails()
-{
- openDetails(m_view->currentPlugin());
-}
-
void PluginDialog::openDetails(ExtensionSystem::PluginSpec *spec)
{
if (!spec)
@@ -137,8 +134,8 @@ void PluginDialog::openDetails(ExtensionSystem::PluginSpec *spec)
details->update(spec);
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Close, Qt::Horizontal, &dialog);
layout->addWidget(buttons);
- connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
- connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
+ connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
dialog.resize(400, 500);
dialog.exec();
}
@@ -157,9 +154,11 @@ void PluginDialog::openErrorDetails()
errors->update(spec);
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Close, Qt::Horizontal, &dialog);
layout->addWidget(buttons);
- connect(buttons, SIGNAL(accepted()), &dialog, SLOT(accept()));
- connect(buttons, SIGNAL(rejected()), &dialog, SLOT(reject()));
+ connect(buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
dialog.resize(500, 300);
dialog.exec();
}
+} // namespace Internal
+} // namespace Core
diff --git a/src/plugins/coreplugin/plugindialog.h b/src/plugins/coreplugin/plugindialog.h
index 17cc6cd7fdc..a581c42e56c 100644
--- a/src/plugins/coreplugin/plugindialog.h
+++ b/src/plugins/coreplugin/plugindialog.h
@@ -53,22 +53,19 @@ class PluginDialog : public QDialog
public:
explicit PluginDialog(QWidget *parent);
-private slots:
+private:
void updateRestartRequired();
void updateButtons();
- void openDetails();
void openDetails(ExtensionSystem::PluginSpec *spec);
void openErrorDetails();
void closeDialog();
-private:
ExtensionSystem::PluginView *m_view;
QPushButton *m_detailsButton;
QPushButton *m_errorDetailsButton;
QPushButton *m_closeButton;
QLabel *m_restartRequired;
- static bool m_isRestartRequired;
};
} // namespace Internal
diff --git a/src/plugins/coreplugin/progressmanager/futureprogress.cpp b/src/plugins/coreplugin/progressmanager/futureprogress.cpp
index fc0dbd6e014..e068d0ad2c4 100644
--- a/src/plugins/coreplugin/progressmanager/futureprogress.cpp
+++ b/src/plugins/coreplugin/progressmanager/futureprogress.cpp
@@ -301,7 +301,7 @@ void FutureProgress::paintEvent(QPaintEvent *)
if (creatorTheme()->widgetStyle() == Theme::StyleFlat) {
p.fillRect(rect(), creatorTheme()->color(Theme::FutureProgressBackgroundColor));
} else {
- QLinearGradient grad = Utils::StyleHelper::statusBarGradient(rect());
+ QLinearGradient grad = StyleHelper::statusBarGradient(rect());
p.fillRect(rect(), grad);
}
}
@@ -379,7 +379,7 @@ void FutureProgressPrivate::fadeAway()
QSequentialAnimationGroup *group = new QSequentialAnimationGroup(this);
QPropertyAnimation *animation = new QPropertyAnimation(opacityEffect, "opacity");
- animation->setDuration(Utils::StyleHelper::progressFadeAnimationDuration);
+ animation->setDuration(StyleHelper::progressFadeAnimationDuration);
animation->setEndValue(0.);
group->addAnimation(animation);
animation = new QPropertyAnimation(m_q, "maximumHeight");
diff --git a/src/plugins/coreplugin/progressmanager/progressbar.cpp b/src/plugins/coreplugin/progressmanager/progressbar.cpp
index fce9939a62e..31c63b3d4c4 100644
--- a/src/plugins/coreplugin/progressmanager/progressbar.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressbar.cpp
@@ -216,7 +216,7 @@ void ProgressBar::mousePressEvent(QMouseEvent *event)
QFont ProgressBar::titleFont() const
{
QFont boldFont(font());
- boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
+ boldFont.setPointSizeF(StyleHelper::sidebarFontSize());
boldFont.setBold(true);
return boldFont;
}
@@ -232,7 +232,7 @@ void ProgressBar::paintEvent(QPaintEvent *)
// TODO use Utils::StyleHelper white
if (bar.isNull())
- bar.load(Utils::StyleHelper::dpiSpecificImageFile(QLatin1String(":/core/images/progressbar.png")));
+ bar.load(StyleHelper::dpiSpecificImageFile(QLatin1String(":/core/images/progressbar.png")));
double range = maximum() - minimum();
double percent = 0.;
@@ -256,10 +256,10 @@ void ProgressBar::paintEvent(QPaintEvent *)
// Draw separator
int separatorHeight = m_separatorVisible ? SEPARATOR_HEIGHT : 0;
if (m_separatorVisible) {
- p.setPen(Utils::StyleHelper::sidebarShadow());
+ p.setPen(StyleHelper::sidebarShadow());
p.drawLine(0,0, size().width(), 0);
- p.setPen(Utils::StyleHelper::sidebarHighlight());
+ p.setPen(StyleHelper::sidebarHighlight());
p.drawLine(1, 1, size().width(), 1);
}
@@ -291,7 +291,7 @@ void ProgressBar::paintEvent(QPaintEvent *)
size().width() - 2 * INDENT + 1, m_progressHeight);
if (creatorTheme()->flag(Theme::DrawProgressBarSunken))
- Utils::StyleHelper::drawCornerImage(bar, &p, rect, 3, 3, 3, 3);
+ StyleHelper::drawCornerImage(bar, &p, rect, 3, 3, 3, 3);
// draw inner rect
QColor c = creatorTheme()->color(Theme::ProgressBarColorNormal);
@@ -357,7 +357,7 @@ void ProgressBar::paintEvent(QPaintEvent *)
p.drawLine(cancelVisualRect.topLeft() + QPointF(0.5, 0.5), cancelVisualRect.bottomLeft() + QPointF(0.5, -0.5));
p.setPen(QPen(QColor(255, 255, 255, 30)));
p.drawLine(cancelVisualRect.topLeft() + QPointF(1.5, 0.5), cancelVisualRect.bottomLeft() + QPointF(1.5, -0.5));
- p.setPen(QPen(hover ? Utils::StyleHelper::panelTextColor() : QColor(180, 180, 180), 1.2, Qt::SolidLine, Qt::FlatCap));
+ p.setPen(QPen(hover ? StyleHelper::panelTextColor() : QColor(180, 180, 180), 1.2, Qt::SolidLine, Qt::FlatCap));
p.setRenderHint(QPainter::Antialiasing, true);
p.drawLine(cancelVisualRect.topLeft() + QPointF(4.0, 2.0), cancelVisualRect.bottomRight() + QPointF(-3.0, -2.0));
p.drawLine(cancelVisualRect.bottomLeft() + QPointF(4.0, -2.0), cancelVisualRect.topRight() + QPointF(-3.0, 2.0));
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager.cpp b/src/plugins/coreplugin/progressmanager/progressmanager.cpp
index 65bad8a577d..06c197c8eca 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressmanager.cpp
@@ -306,7 +306,7 @@ void ProgressManagerPrivate::init()
{
readSettings();
- m_statusBarWidgetContainer = new Core::StatusBarWidget;
+ m_statusBarWidgetContainer = new StatusBarWidget;
m_statusBarWidget = new QWidget;
QHBoxLayout *layout = new QHBoxLayout(m_statusBarWidget);
layout->setContentsMargins(0, 0, 0, 0);
@@ -329,7 +329,7 @@ void ProgressManagerPrivate::init()
ToggleButton *toggleButton = new ToggleButton(m_statusBarWidget);
layout->addWidget(toggleButton);
m_statusBarWidgetContainer->setWidget(m_statusBarWidget);
- m_statusBarWidgetContainer->setPosition(Core::StatusBarWidget::RightCorner);
+ m_statusBarWidgetContainer->setPosition(StatusBarWidget::RightCorner);
ExtensionSystem::PluginManager::addObject(m_statusBarWidgetContainer);
m_statusBarWidget->installEventFilter(this);
@@ -343,7 +343,7 @@ void ProgressManagerPrivate::init()
Command *cmd = ActionManager::registerAction(toggleProgressView,
"QtCreator.ToggleProgressDetails",
Context(Constants::C_GLOBAL));
- cmd->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
+ cmd->setDefaultKeySequence(QKeySequence(HostOsInfo::isMacHost()
? tr("Ctrl+Shift+0")
: tr("Alt+Shift+0")));
connect(toggleProgressView, SIGNAL(toggled(bool)), this, SLOT(progressDetailsToggled(bool)));
@@ -532,7 +532,7 @@ void ProgressManagerPrivate::fadeAwaySummaryProgress()
{
stopFadeOfSummaryProgress();
m_opacityAnimation = new QPropertyAnimation(m_opacityEffect, "opacity");
- m_opacityAnimation->setDuration(Utils::StyleHelper::progressFadeAnimationDuration);
+ m_opacityAnimation->setDuration(StyleHelper::progressFadeAnimationDuration);
m_opacityAnimation->setEndValue(0.);
connect(m_opacityAnimation, SIGNAL(finished()), this, SLOT(summaryProgressFinishedFading()));
m_opacityAnimation->start(QAbstractAnimation::DeleteWhenStopped);
@@ -725,7 +725,7 @@ void ToggleButton::paintEvent(QPaintEvent *event)
QStyleOption arrowOpt;
arrowOpt.initFrom(this);
arrowOpt.rect.adjust(2, 0, -1, -2);
- Utils::StyleHelper::drawArrow(QStyle::PE_IndicatorArrowUp, &p, &arrowOpt);
+ StyleHelper::drawArrow(QStyle::PE_IndicatorArrowUp, &p, &arrowOpt);
}
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager.h b/src/plugins/coreplugin/progressmanager/progressmanager.h
index 69789dfffda..f39ca6fe0fc 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager.h
+++ b/src/plugins/coreplugin/progressmanager/progressmanager.h
@@ -55,9 +55,9 @@ public:
static QObject *instance();
static FutureProgress *addTask(const QFuture<void> &future, const QString &title,
- Core::Id type, ProgressFlags flags = 0);
+ Id type, ProgressFlags flags = 0);
static FutureProgress *addTimedTask(const QFutureInterface<void> &fi, const QString &title,
- Core::Id type, int expectedSeconds, ProgressFlags flags = 0);
+ Id type, int expectedSeconds, ProgressFlags flags = 0);
static void setApplicationLabel(const QString &text);
public slots:
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager_p.h b/src/plugins/coreplugin/progressmanager/progressmanager_p.h
index 122d27d4c31..dd161e86b4b 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager_p.h
+++ b/src/plugins/coreplugin/progressmanager/progressmanager_p.h
@@ -105,7 +105,7 @@ private:
QList<FutureProgress *> m_taskList;
QMap<QFutureWatcher<void> *, Id> m_runningTasks;
QFutureWatcher<void> *m_applicationTask;
- Core::StatusBarWidget *m_statusBarWidgetContainer;
+ StatusBarWidget *m_statusBarWidgetContainer;
QWidget *m_statusBarWidget;
QWidget *m_summaryProgressWidget;
QHBoxLayout *m_summaryProgressLayout;
diff --git a/src/plugins/coreplugin/rightpane.cpp b/src/plugins/coreplugin/rightpane.cpp
index 8d0719c0adf..e431548f310 100644
--- a/src/plugins/coreplugin/rightpane.cpp
+++ b/src/plugins/coreplugin/rightpane.cpp
@@ -30,6 +30,7 @@
#include "rightpane.h"
+#include <coreplugin/imode.h>
#include <coreplugin/modemanager.h>
#include <QSettings>
@@ -49,13 +50,13 @@ RightPanePlaceHolder* RightPanePlaceHolder::current()
return m_current;
}
-RightPanePlaceHolder::RightPanePlaceHolder(Core::IMode *mode, QWidget *parent)
+RightPanePlaceHolder::RightPanePlaceHolder(IMode *mode, QWidget *parent)
:QWidget(parent), m_mode(mode)
{
setLayout(new QVBoxLayout);
layout()->setMargin(0);
- connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
- this, SLOT(currentModeChanged(Core::IMode*)));
+ connect(ModeManager::instance(), &ModeManager::currentModeChanged,
+ this, &RightPanePlaceHolder::currentModeChanged);
}
RightPanePlaceHolder::~RightPanePlaceHolder()
@@ -96,7 +97,7 @@ void RightPanePlaceHolder::applyStoredSize(int width)
// m_current points to the current PlaceHolder, or zero if there
// is no PlaceHolder in this mode
// And that the parent of the RightPaneWidget gets the correct parent
-void RightPanePlaceHolder::currentModeChanged(Core::IMode *mode)
+void RightPanePlaceHolder::currentModeChanged(IMode *mode)
{
if (m_current == this) {
m_current = 0;
diff --git a/src/plugins/coreplugin/rightpane.h b/src/plugins/coreplugin/rightpane.h
index b4e8ded441c..9f3da2c38b1 100644
--- a/src/plugins/coreplugin/rightpane.h
+++ b/src/plugins/coreplugin/rightpane.h
@@ -51,16 +51,14 @@ class CORE_EXPORT RightPanePlaceHolder : public QWidget
Q_OBJECT
public:
- explicit RightPanePlaceHolder(Core::IMode *mode, QWidget *parent = 0);
+ explicit RightPanePlaceHolder(IMode *mode, QWidget *parent = 0);
~RightPanePlaceHolder();
static RightPanePlaceHolder *current();
-private slots:
- void currentModeChanged(Core::IMode *);
-
private:
+ void currentModeChanged(IMode *);
void applyStoredSize(int width);
- Core::IMode *m_mode;
+ IMode *m_mode;
static RightPanePlaceHolder* m_current;
};
diff --git a/src/plugins/coreplugin/sidebar.cpp b/src/plugins/coreplugin/sidebar.cpp
index 2ad2f103e16..6365fbfc7e4 100644
--- a/src/plugins/coreplugin/sidebar.cpp
+++ b/src/plugins/coreplugin/sidebar.cpp
@@ -30,6 +30,7 @@
#include "sidebar.h"
#include "sidebarwidget.h"
+#include "coreconstants.h"
#include "actionmanager/command.h"
#include <utils/algorithm.h>
@@ -202,12 +203,19 @@ SideBarItem *SideBar::item(const QString &id)
Internal::SideBarWidget *SideBar::insertSideBarWidget(int position, const QString &id)
{
+ if (!d->m_widgets.isEmpty())
+ d->m_widgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
+
Internal::SideBarWidget *item = new Internal::SideBarWidget(this, id);
connect(item, SIGNAL(splitMe()), this, SLOT(splitSubWidget()));
connect(item, SIGNAL(closeMe()), this, SLOT(closeSubWidget()));
connect(item, SIGNAL(currentWidgetChanged()), this, SLOT(updateWidgets()));
insertWidget(position, item);
d->m_widgets.insert(position, item);
+ if (d->m_widgets.size() == 1)
+ d->m_widgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_LEFT)));
+ else
+ d->m_widgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_TOP)));
updateWidgets();
return item;
}
@@ -235,6 +243,11 @@ void SideBar::closeSubWidget()
if (!widget)
return;
removeSideBarWidget(widget);
+ // update close button of top item
+ if (d->m_widgets.size() == 1)
+ d->m_widgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_LEFT)));
+ else
+ d->m_widgets.at(0)->setCloseIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_TOP)));
updateWidgets();
} else {
if (d->m_closeWhenEmpty) {
@@ -334,12 +347,12 @@ void SideBar::activateItem(const QString &id)
d->m_itemMap.value(id)->widget()->setFocus();
}
-void SideBar::setShortcutMap(const QMap<QString, Core::Command*> &shortcutMap)
+void SideBar::setShortcutMap(const QMap<QString, Command*> &shortcutMap)
{
d->m_shortcutMap = shortcutMap;
}
-QMap<QString, Core::Command*> SideBar::shortcutMap() const
+QMap<QString, Command*> SideBar::shortcutMap() const
{
return d->m_shortcutMap;
}
diff --git a/src/plugins/coreplugin/sidebar.h b/src/plugins/coreplugin/sidebar.h
index 02fa0749d40..e01808318d2 100644
--- a/src/plugins/coreplugin/sidebar.h
+++ b/src/plugins/coreplugin/sidebar.h
@@ -111,8 +111,8 @@ public:
void closeAllWidgets();
void activateItem(const QString &id);
- void setShortcutMap(const QMap<QString, Core::Command *> &shortcutMap);
- QMap<QString, Core::Command *> shortcutMap() const;
+ void setShortcutMap(const QMap<QString, Command *> &shortcutMap);
+ QMap<QString, Command *> shortcutMap() const;
signals:
void sideBarClosed();
diff --git a/src/plugins/coreplugin/sidebarwidget.cpp b/src/plugins/coreplugin/sidebarwidget.cpp
index 137ad191b4a..8fce8187ab4 100644
--- a/src/plugins/coreplugin/sidebarwidget.cpp
+++ b/src/plugins/coreplugin/sidebarwidget.cpp
@@ -53,7 +53,7 @@ public:
explicit SideBarComboBox(SideBarWidget *sideBarWidget) : m_sideBarWidget(sideBarWidget) {}
private:
- virtual const Core::Command *command(const QString &text) const
+ virtual const Command *command(const QString &text) const
{ return m_sideBarWidget->command(text); }
SideBarWidget *m_sideBarWidget;
@@ -80,11 +80,11 @@ SideBarWidget::SideBarWidget(SideBar *sideBar, const QString &id)
connect(m_splitAction, SIGNAL(triggered()), this, SIGNAL(splitMe()));
m_toolbar->addAction(m_splitAction);
- QAction *closeAction = new QAction(tr("Close"), m_toolbar);
- closeAction->setToolTip(tr("Close"));
- closeAction->setIcon(QIcon(QLatin1String(Constants::ICON_BUTTON_CLOSE)));
- connect(closeAction, SIGNAL(triggered()), this, SIGNAL(closeMe()));
- m_toolbar->addAction(closeAction);
+ m_closeAction = new QAction(tr("Close"), m_toolbar);
+ m_closeAction->setToolTip(tr("Close"));
+ m_closeAction->setIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
+ connect(m_closeAction, SIGNAL(triggered()), this, SIGNAL(closeMe()));
+ m_toolbar->addAction(m_closeAction);
QVBoxLayout *lay = new QVBoxLayout();
lay->setMargin(0);
@@ -200,17 +200,22 @@ void SideBarWidget::setCurrentIndex(int)
emit currentWidgetChanged();
}
-Core::Command *SideBarWidget::command(const QString &title) const
+Command *SideBarWidget::command(const QString &title) const
{
const QString id = m_sideBar->idForTitle(title);
if (id.isEmpty())
return 0;
- const QMap<QString, Core::Command*> shortcutMap = m_sideBar->shortcutMap();
- QMap<QString, Core::Command*>::const_iterator r = shortcutMap.find(id);
+ const QMap<QString, Command*> shortcutMap = m_sideBar->shortcutMap();
+ QMap<QString, Command*>::const_iterator r = shortcutMap.find(id);
if (r != shortcutMap.end())
return r.value();
return 0;
}
+void SideBarWidget::setCloseIcon(const QIcon &icon)
+{
+ m_closeAction->setIcon(icon);
+}
+
} // namespace Internal
} // namespace Core
diff --git a/src/plugins/coreplugin/sidebarwidget.h b/src/plugins/coreplugin/sidebarwidget.h
index 51fb23bcb54..c1b8f0f0f10 100644
--- a/src/plugins/coreplugin/sidebarwidget.h
+++ b/src/plugins/coreplugin/sidebarwidget.h
@@ -62,7 +62,9 @@ public:
void updateAvailableItems();
void removeCurrentItem();
- Core::Command *command(const QString &title) const;
+ Command *command(const QString &title) const;
+
+ void setCloseIcon(const QIcon &icon);
signals:
void splitMe();
@@ -77,6 +79,7 @@ private:
SideBarItem *m_currentItem;
QToolBar *m_toolbar;
QAction *m_splitAction;
+ QAction *m_closeAction;
QList<QAction *> m_addedToolBarActions;
SideBar *m_sideBar;
};
diff --git a/src/plugins/coreplugin/testdatadir.cpp b/src/plugins/coreplugin/testdatadir.cpp
index 88ba2d4ef6f..06a0dc979c4 100644
--- a/src/plugins/coreplugin/testdatadir.cpp
+++ b/src/plugins/coreplugin/testdatadir.cpp
@@ -51,6 +51,11 @@ QString TestDataDir::file(const QString &fileName) const
return directory() + QLatin1Char('/') + fileName;
}
+QString TestDataDir::path() const
+{
+ return m_directory;
+}
+
QString TestDataDir::directory(const QString &subdir, bool clean) const
{
QString path = m_directory;
diff --git a/src/plugins/coreplugin/testdatadir.h b/src/plugins/coreplugin/testdatadir.h
index e1168c177a5..c72c9302c21 100644
--- a/src/plugins/coreplugin/testdatadir.h
+++ b/src/plugins/coreplugin/testdatadir.h
@@ -51,11 +51,12 @@ class CORE_EXPORT TestDataDir
{
public:
TestDataDir(const QString &directory);
- QString file(const QString &fileName) const;
-protected:
+ QString file(const QString &fileName) const;
QString directory(const QString &subdir = QString(), bool clean = true) const;
+ QString path() const;
+
private:
QString m_directory;
};
diff --git a/src/plugins/coreplugin/themesettings.cpp b/src/plugins/coreplugin/themesettings.cpp
index 1541d7c412a..8a2ded94780 100644
--- a/src/plugins/coreplugin/themesettings.cpp
+++ b/src/plugins/coreplugin/themesettings.cpp
@@ -40,11 +40,11 @@ namespace Internal {
ThemeSettings::ThemeSettings() :
m_widget(0)
{
- setId(Core::Constants::SETTINGS_ID_ENVIRONMENT);
+ setId(Constants::SETTINGS_ID_ENVIRONMENT);
setDisplayName(tr("Theme"));
- setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
- setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
- setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
+ setCategory(Constants::SETTINGS_CATEGORY_CORE);
+ setDisplayCategory(QCoreApplication::translate("Core", Constants::SETTINGS_TR_CATEGORY_CORE));
+ setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CORE_ICON));
}
ThemeSettings::~ThemeSettings()
diff --git a/src/plugins/coreplugin/themesettingswidget.cpp b/src/plugins/coreplugin/themesettingswidget.cpp
index e7ae25c2481..2e05925e78a 100644
--- a/src/plugins/coreplugin/themesettingswidget.cpp
+++ b/src/plugins/coreplugin/themesettingswidget.cpp
@@ -292,7 +292,7 @@ void ThemeSettingsWidget::confirmDeleteTheme()
QMessageBox *messageBox = new QMessageBox(QMessageBox::Warning,
tr("Delete Theme"),
- tr("Are you sure you want to delete the theme '%1' permanently?").arg(entry.displayName()),
+ tr("Are you sure you want to delete the theme \"%1\" permanently?").arg(entry.displayName()),
QMessageBox::Discard | QMessageBox::Cancel,
d->m_ui->deleteButton->window());
@@ -446,8 +446,8 @@ void ThemeSettingsWidget::apply()
w->update();
// save filename of selected theme in global config
- QSettings *settings = Core::ICore::settings();
- settings->setValue(QLatin1String(Core::Constants::SETTINGS_THEME), themeName);
+ QSettings *settings = ICore::settings();
+ settings->setValue(QLatin1String(Constants::SETTINGS_THEME), themeName);
}
} // namespace Internal
diff --git a/src/plugins/coreplugin/toolsettings.cpp b/src/plugins/coreplugin/toolsettings.cpp
index fce3947f1e5..33c6abb7f13 100644
--- a/src/plugins/coreplugin/toolsettings.cpp
+++ b/src/plugins/coreplugin/toolsettings.cpp
@@ -49,11 +49,11 @@ using namespace Core::Internal;
ToolSettings::ToolSettings(QObject *parent) :
IOptionsPage(parent)
{
- setId(Core::Constants::SETTINGS_ID_TOOLS);
+ setId(Constants::SETTINGS_ID_TOOLS);
setDisplayName(tr("External Tools"));
- setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
+ setCategory(Constants::SETTINGS_CATEGORY_CORE);
setDisplayCategory(QCoreApplication::translate("Core", Constants::SETTINGS_TR_CATEGORY_CORE));
- setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
+ setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CORE_ICON));
}
@@ -149,7 +149,7 @@ void ToolSettings::apply()
if (tool->preset() && (*tool) != (*(tool->preset()))) {
// check if we need to choose a new file name
if (tool->preset()->fileName() == tool->fileName()) {
- const QString &fileName = QFileInfo(tool->preset()->fileName()).fileName();
+ const QString &fileName = Utils::FileName::fromString(tool->preset()->fileName()).fileName();
const QString &newFilePath = getUserFilePath(fileName);
// TODO error handling if newFilePath.isEmpty() (i.e. failed to find a unused name)
tool->setFileName(newFilePath);
diff --git a/src/plugins/coreplugin/variablechooser.cpp b/src/plugins/coreplugin/variablechooser.cpp
index d62eee7675f..20f987d8e23 100644
--- a/src/plugins/coreplugin/variablechooser.cpp
+++ b/src/plugins/coreplugin/variablechooser.cpp
@@ -72,7 +72,7 @@ public:
setAttribute(Qt::WA_MacShowFocusRect, false);
setIndentation(indentation() * 7/10);
header()->hide();
- new Utils::HeaderViewStretcher(header(), 0);
+ new HeaderViewStretcher(header(), 0);
}
void contextMenuEvent(QContextMenuEvent *ev);
@@ -89,7 +89,7 @@ public:
void createIconButton()
{
- m_iconButton = new Utils::IconButton;
+ m_iconButton = new IconButton;
m_iconButton->setPixmap(QPixmap(QLatin1String(":/core/images/replace.png")));
m_iconButton->setToolTip(tr("Insert variable"));
m_iconButton->hide();
@@ -115,7 +115,7 @@ public:
QPointer<QLineEdit> m_lineEdit;
QPointer<QTextEdit> m_textEdit;
QPointer<QPlainTextEdit> m_plainTextEdit;
- QPointer<Utils::IconButton> m_iconButton;
+ QPointer<IconButton> m_iconButton;
VariableTreeView *m_variableTree;
QLabel *m_variableDescription;
diff --git a/src/plugins/coreplugin/vcsmanager.cpp b/src/plugins/coreplugin/vcsmanager.cpp
index baba43fc6e0..e59d5266cfc 100644
--- a/src/plugins/coreplugin/vcsmanager.cpp
+++ b/src/plugins/coreplugin/vcsmanager.cpp
@@ -223,6 +223,18 @@ void VcsManager::extensionsInitialized()
}
}
+QList<IVersionControl *> VcsManager::versionControls()
+{
+ return ExtensionSystem::PluginManager::getObjects<IVersionControl>();
+}
+
+IVersionControl *VcsManager::versionControl(Id id)
+{
+ return Utils::findOrDefault(versionControls(), [id](const Core::IVersionControl *vc) {
+ return vc->id() == id;
+ });
+}
+
void VcsManager::resetVersionControlForDirectory(const QString &inputDirectory)
{
if (inputDirectory.isEmpty())
@@ -330,7 +342,7 @@ IVersionControl* VcsManager::findVersionControlForDirectory(const QString &input
.arg(versionControl->displayName()),
InfoBarEntry::GlobalSuppressionEnabled);
d->m_unconfiguredVcs = versionControl;
- info.setCustomButtonInfo(Core::ICore::msgShowOptionsDialog(), []() {
+ info.setCustomButtonInfo(ICore::msgShowOptionsDialog(), []() {
QTC_ASSERT(d->m_unconfiguredVcs, return);
ICore::showOptionsDialog(Id(VcsBase::Constants::VCS_SETTINGS_CATEGORY),
d->m_unconfiguredVcs->id());
@@ -367,23 +379,6 @@ bool VcsManager::promptToDelete(const QString &fileName)
return true;
}
-IVersionControl *VcsManager::checkout(const QString &versionControlType,
- const QString &directory,
- const QByteArray &url)
-{
- foreach (IVersionControl *versionControl, allVersionControls()) {
- if (versionControl->displayName() == versionControlType
- && versionControl->supportsOperation(Core::IVersionControl::CheckoutOperation)) {
- if (versionControl->vcsCheckout(directory, url)) {
- d->cache(versionControl, directory, directory);
- return versionControl;
- }
- return 0;
- }
- }
- return 0;
-}
-
bool VcsManager::promptToDelete(IVersionControl *vc, const QString &fileName)
{
QTC_ASSERT(vc, return true);
@@ -441,7 +436,7 @@ QStringList VcsManager::additionalToolsPath()
void VcsManager::promptToAdd(const QString &directory, const QStringList &fileNames)
{
IVersionControl *vc = findVersionControlForDirectory(directory);
- if (!vc || !vc->supportsOperation(Core::IVersionControl::AddOperation))
+ if (!vc || !vc->supportsOperation(IVersionControl::AddOperation))
return;
QStringList unmanagedFiles;
@@ -453,7 +448,7 @@ void VcsManager::promptToAdd(const QString &directory, const QStringList &fileNa
if (unmanagedFiles.isEmpty())
return;
- Internal::AddToVcsDialog dlg(Core::ICore::mainWindow(), VcsManager::msgAddToVcsTitle(),
+ Internal::AddToVcsDialog dlg(ICore::mainWindow(), VcsManager::msgAddToVcsTitle(),
unmanagedFiles, vc->displayName());
if (dlg.exec() == QDialog::Accepted) {
QStringList notAddedToVc;
@@ -463,7 +458,7 @@ void VcsManager::promptToAdd(const QString &directory, const QStringList &fileNa
}
if (!notAddedToVc.isEmpty()) {
- QMessageBox::warning(Core::ICore::mainWindow(), VcsManager::msgAddToVcsFailedTitle(),
+ QMessageBox::warning(ICore::mainWindow(), VcsManager::msgAddToVcsFailedTitle(),
VcsManager::msgToAddToVcsFailed(notAddedToVc, vc));
}
}
diff --git a/src/plugins/coreplugin/vcsmanager.h b/src/plugins/coreplugin/vcsmanager.h
index 02b52f2c1ec..1cc5350e332 100644
--- a/src/plugins/coreplugin/vcsmanager.h
+++ b/src/plugins/coreplugin/vcsmanager.h
@@ -32,6 +32,7 @@
#define VCSMANAGER_H
#include "core_global.h"
+#include "id.h"
#include <QString>
#include <QObject>
@@ -63,6 +64,9 @@ public:
static void extensionsInitialized();
+ static QList<IVersionControl *> versionControls();
+ static IVersionControl *versionControl(Id id);
+
static void resetVersionControlForDirectory(const QString &inputDirectory);
static IVersionControl *findVersionControlForDirectory(const QString &directory,
QString *topLevelDirectory = 0);
@@ -70,10 +74,6 @@ public:
static QStringList repositories(const IVersionControl *);
- static IVersionControl *checkout(const QString &versionControlType,
- const QString &directory,
- const QByteArray &url);
-
// 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
diff --git a/src/plugins/coreplugin/windowsupport.cpp b/src/plugins/coreplugin/windowsupport.cpp
index 9f999818954..ae229fef26c 100644
--- a/src/plugins/coreplugin/windowsupport.cpp
+++ b/src/plugins/coreplugin/windowsupport.cpp
@@ -116,6 +116,11 @@ bool WindowSupport::eventFilter(QObject *obj, QEvent *event)
updateFullScreenAction();
} else if (event->type() == QEvent::WindowActivate) {
WindowList::setActiveWindow(m_window);
+ } else if (event->type() == QEvent::Hide) {
+ // minimized windows are hidden, but we still want to show them
+ WindowList::setWindowVisible(m_window, m_window->isMinimized());
+ } else if (event->type() == QEvent::Show) {
+ WindowList::setWindowVisible(m_window, true);
}
return false;
}
@@ -165,6 +170,7 @@ void WindowList::addWindow(QWidget *window)
Context(Constants::C_GLOBAL));
cmd->setAttribute(Command::CA_UpdateText);
ActionManager::actionContainer(Constants::M_WINDOW)->addAction(cmd, Constants::G_WINDOW_LIST);
+ action->setVisible(window->isVisible() || window->isMinimized()); // minimized windows are hidden but should be shown
QObject::connect(window, &QWidget::windowTitleChanged, [window]() { WindowList::updateTitle(window); });
if (m_dockMenu)
m_dockMenu->addAction(action);
@@ -215,5 +221,13 @@ void WindowList::setActiveWindow(QWidget *window)
m_windowActions.at(i)->setChecked(m_windows.at(i) == window);
}
+void WindowList::setWindowVisible(QWidget *window, bool visible)
+{
+ int index = m_windows.indexOf(window);
+ QTC_ASSERT(index >= 0, return);
+ QTC_ASSERT(index < m_windowActions.size(), return);
+ m_windowActions.at(index)->setVisible(visible);
+}
+
} // Internal
} // Core
diff --git a/src/plugins/coreplugin/windowsupport.h b/src/plugins/coreplugin/windowsupport.h
index 899e1417d04..f33091cc923 100644
--- a/src/plugins/coreplugin/windowsupport.h
+++ b/src/plugins/coreplugin/windowsupport.h
@@ -50,6 +50,7 @@ public:
static void addWindow(QWidget *window);
static void removeWindow(QWidget *window);
static void setActiveWindow(QWidget *window);
+ static void setWindowVisible(QWidget *window, bool visible);
private:
static void activateWindow(QAction *action);
diff --git a/src/plugins/cpaster/cpasterplugin.cpp b/src/plugins/cpaster/cpasterplugin.cpp
index 5fa7546f744..570d3b80127 100644
--- a/src/plugins/cpaster/cpasterplugin.cpp
+++ b/src/plugins/cpaster/cpasterplugin.cpp
@@ -122,10 +122,10 @@ bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMe
Q_UNUSED(errorMessage)
// Create the globalcontext list to register actions accordingly
- Core::Context globalcontext(Core::Constants::C_GLOBAL);
+ Context globalcontext(Core::Constants::C_GLOBAL);
// Create the settings Page
- m_settings->fromSettings(Core::ICore::settings());
+ m_settings->fromSettings(ICore::settings());
SettingsPage *settingsPage = new SettingsPage(m_settings);
addAutoReleasedObject(settingsPage);
@@ -147,36 +147,35 @@ bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMe
}
m_urlOpen = new UrlOpenProtocol;
- connect(m_urlOpen, SIGNAL(fetchDone(QString,QString,bool)),
- this, SLOT(finishFetch(QString,QString,bool)));
+ connect(m_urlOpen, &Protocol::fetchDone, this, &CodepasterPlugin::finishFetch);
//register actions
- Core::ActionContainer *toolsContainer =
- Core::ActionManager::actionContainer(Core::Constants::M_TOOLS);
+ ActionContainer *toolsContainer =
+ ActionManager::actionContainer(Core::Constants::M_TOOLS);
- Core::ActionContainer *cpContainer =
- Core::ActionManager::createMenu("CodePaster");
+ ActionContainer *cpContainer =
+ ActionManager::createMenu("CodePaster");
cpContainer->menu()->setTitle(tr("&Code Pasting"));
toolsContainer->addMenu(cpContainer);
- Core::Command *command;
+ Command *command;
m_postEditorAction = new QAction(tr("Paste Snippet..."), this);
- command = Core::ActionManager::registerAction(m_postEditorAction, "CodePaster.Post", globalcontext);
+ command = ActionManager::registerAction(m_postEditorAction, "CodePaster.Post", globalcontext);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+C,Meta+P") : tr("Alt+C,Alt+P")));
connect(m_postEditorAction, &QAction::triggered, this, &CodepasterPlugin::pasteSnippet);
cpContainer->addAction(command);
m_fetchAction = new QAction(tr("Fetch Snippet..."), this);
- command = Core::ActionManager::registerAction(m_fetchAction, "CodePaster.Fetch", globalcontext);
+ command = ActionManager::registerAction(m_fetchAction, "CodePaster.Fetch", globalcontext);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+C,Meta+F") : tr("Alt+C,Alt+F")));
- connect(m_fetchAction, SIGNAL(triggered()), this, SLOT(fetch()));
+ connect(m_fetchAction, &QAction::triggered, this, &CodepasterPlugin::fetch);
cpContainer->addAction(command);
m_fetchUrlAction = new QAction(tr("Fetch from URL..."), this);
- command = Core::ActionManager::registerAction(m_fetchUrlAction, "CodePaster.FetchUrl", globalcontext);
- connect(m_fetchUrlAction, SIGNAL(triggered()), this, SLOT(fetchUrl()));
+ command = ActionManager::registerAction(m_fetchUrlAction, "CodePaster.FetchUrl", globalcontext);
+ connect(m_fetchUrlAction, &QAction::triggered, this, &CodepasterPlugin::fetchUrl);
cpContainer->addAction(command);
addAutoReleasedObject(new CodePasterService);
@@ -275,7 +274,7 @@ void CodepasterPlugin::post(QString data, const QString &mimeType)
if (dialogResult == QDialog::Accepted
&& m_settings->protocol != view.protocol()) {
m_settings->protocol = view.protocol();
- m_settings->toSettings(Core::ICore::settings());
+ m_settings->toSettings(ICore::settings());
}
}
@@ -306,7 +305,7 @@ void CodepasterPlugin::fetch()
// Save new protocol in case user changed it.
if (m_settings->protocol != dialog.protocol()) {
m_settings->protocol = dialog.protocol();
- m_settings->toSettings(Core::ICore::settings());
+ m_settings->toSettings(ICore::settings());
}
const QString pasteID = dialog.pasteId();
@@ -321,7 +320,7 @@ void CodepasterPlugin::finishPost(const QString &link)
{
if (m_settings->copyToClipboard)
QApplication::clipboard()->setText(link);
- MessageManager::write(link, m_settings->displayOutput ? Core::MessageManager::ModeSwitch : Core::MessageManager::Silent);
+ MessageManager::write(link, m_settings->displayOutput ? MessageManager::ModeSwitch : MessageManager::Silent);
}
// Extract the characters that can be used for a file name from a title
@@ -348,8 +347,9 @@ static inline QString tempFilePattern(const QString &prefix, const QString &exte
{
// Get directory
QString pattern = QDir::tempPath();
- if (!pattern.endsWith(QDir::separator()))
- pattern.append(QDir::separator());
+ const QChar slash = QLatin1Char('/');
+ if (!pattern.endsWith(slash))
+ pattern.append(slash);
// Prefix, placeholder, extension
pattern += prefix;
pattern += QLatin1String("_XXXXXX.");
@@ -392,7 +392,7 @@ void CodepasterPlugin::finishFetch(const QString &titleDescription,
const QString fileName = saver.fileName();
m_fetchedSnippets.push_back(fileName);
// Open editor with title.
- Core::IEditor *editor = EditorManager::openEditor(fileName);
+ IEditor *editor = EditorManager::openEditor(fileName);
QTC_ASSERT(editor, return);
editor->document()->setDisplayName(titleDescription);
}
diff --git a/src/plugins/cpaster/frontend/argumentscollector.cpp b/src/plugins/cpaster/frontend/argumentscollector.cpp
index f066f0e50cd..08a7f12331e 100644
--- a/src/plugins/cpaster/frontend/argumentscollector.cpp
+++ b/src/plugins/cpaster/frontend/argumentscollector.cpp
@@ -30,7 +30,8 @@
#include "argumentscollector.h"
-#include <QFileInfo>
+#include <utils/fileutils.h>
+
#include <QCoreApplication>
static QString pasteRequestString() { return QLatin1String("paste"); }
@@ -72,7 +73,7 @@ bool ArgumentsCollector::collect(const QStringList &args)
QString ArgumentsCollector::usageString() const
{
QString usage = QString::fromLatin1("Usage:\n\t%1 <request> [ <request options>]\n\t")
- .arg(QFileInfo(QCoreApplication::applicationFilePath()).fileName());
+ .arg(Utils::FileName::fromString(QCoreApplication::applicationFilePath()).fileName());
usage += QString::fromLatin1("Possible requests: \"%1\", \"%2\", \"%3\"\n\t")
.arg(pasteRequestString(), listProtocolsRequestString(), helpRequestString());
usage += QString::fromLatin1("Possible options for request \"%1\": \"%2 <file>\" (default: stdin), "
diff --git a/src/plugins/cpaster/kdepasteprotocol.cpp b/src/plugins/cpaster/kdepasteprotocol.cpp
index 5591af3645a..498fb98125c 100644
--- a/src/plugins/cpaster/kdepasteprotocol.cpp
+++ b/src/plugins/cpaster/kdepasteprotocol.cpp
@@ -133,7 +133,7 @@ void StickyNotesPasteProtocol::paste(const QString &text,
}
m_pasteReply = httpPost(m_hostUrl + QLatin1String("api/json/create"), pasteData);
- connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
+ connect(m_pasteReply, &QNetworkReply::finished, this, &StickyNotesPasteProtocol::pasteFinished);
if (debug)
qDebug() << "paste: sending " << m_pasteReply << pasteData;
}
@@ -196,7 +196,8 @@ void StickyNotesPasteProtocol::fetch(const QString &id)
qDebug() << "fetch: sending " << url;
m_fetchReply = httpGet(url);
- connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished()));
+ connect(m_fetchReply, &QNetworkReply::finished,
+ this, &StickyNotesPasteProtocol::fetchFinished);
}
// Parse: '<result><id>143228</id><author>foo</author><timestamp>1320661026</timestamp><language>text</language>
@@ -227,7 +228,8 @@ void StickyNotesPasteProtocol::list()
// Trailing slash is important to prevent redirection.
QString url = m_hostUrl + QLatin1String("api/json/list");
m_listReply = httpGet(url);
- connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished()));
+ connect(m_listReply, &QNetworkReply::finished,
+ this, &StickyNotesPasteProtocol::listFinished);
if (debug)
qDebug() << "list: sending " << url << m_listReply;
}
diff --git a/src/plugins/cpaster/pastebindotcaprotocol.cpp b/src/plugins/cpaster/pastebindotcaprotocol.cpp
index a92c477fb49..8e8a53db85d 100644
--- a/src/plugins/cpaster/pastebindotcaprotocol.cpp
+++ b/src/plugins/cpaster/pastebindotcaprotocol.cpp
@@ -98,7 +98,8 @@ void PasteBinDotCaProtocol::fetch(const QString &id)
link.insert(0, url);
}
m_fetchReply = httpGet(link);
- connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished()));
+ connect(m_fetchReply, &QNetworkReply::finished,
+ this, &PasteBinDotCaProtocol::fetchFinished);
m_fetchId = id;
}
@@ -138,7 +139,8 @@ void PasteBinDotCaProtocol::paste(const QString &text,
// fire request
const QString link = QLatin1String(internalUrlC) + QLatin1String("quiet-paste.php");
m_pasteReply = httpPost(link, data);
- connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
+ connect(m_pasteReply, &QNetworkReply::finished,
+ this, &PasteBinDotCaProtocol::pasteFinished);
}
void PasteBinDotCaProtocol::pasteFinished()
@@ -177,7 +179,7 @@ void PasteBinDotCaProtocol::list()
{
QTC_ASSERT(!m_listReply, return);
m_listReply = httpGet(QLatin1String(urlC));
- connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished()));
+ connect(m_listReply, &QNetworkReply::finished, this, &PasteBinDotCaProtocol::listFinished);
}
bool PasteBinDotCaProtocol::checkConfiguration(QString *errorMessage)
diff --git a/src/plugins/cpaster/pastebindotcomprotocol.cpp b/src/plugins/cpaster/pastebindotcomprotocol.cpp
index 9446384acef..e06ac4f6aeb 100644
--- a/src/plugins/cpaster/pastebindotcomprotocol.cpp
+++ b/src/plugins/cpaster/pastebindotcomprotocol.cpp
@@ -136,7 +136,7 @@ void PasteBinDotComProtocol::paste(const QString &text,
pasteData += QUrl::toPercentEncoding(fixNewLines(text));
// fire request
m_pasteReply = httpPost(QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_API), pasteData);
- connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
+ connect(m_pasteReply, &QNetworkReply::finished, this, &PasteBinDotComProtocol::pasteFinished);
if (debug)
qDebug() << "paste: sending " << m_pasteReply << pasteData;
}
@@ -167,7 +167,7 @@ void PasteBinDotComProtocol::fetch(const QString &id)
qDebug() << "fetch: sending " << link;
m_fetchReply = httpGet(link);
- connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished()));
+ connect(m_fetchReply, &QNetworkReply::finished, this, &PasteBinDotComProtocol::fetchFinished);
m_fetchId = id;
}
@@ -212,7 +212,7 @@ void PasteBinDotComProtocol::list()
const QString url = QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_ARCHIVE);
m_listReply = httpGet(url);
- connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished()));
+ connect(m_listReply, &QNetworkReply::finished, this, &PasteBinDotComProtocol::listFinished);
if (debug)
qDebug() << "list: sending " << url << m_listReply;
}
diff --git a/src/plugins/cpaster/pasteview.cpp b/src/plugins/cpaster/pasteview.cpp
index 4b8ad3d39cb..3bd9b7f4a43 100644
--- a/src/plugins/cpaster/pasteview.cpp
+++ b/src/plugins/cpaster/pasteview.cpp
@@ -55,12 +55,12 @@ PasteView::PasteView(const QList<Protocol *> &protocols,
m_ui.setupUi(this);
m_ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Paste"));
- connect(m_ui.uiPatchList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(contentChanged()));
+ connect(m_ui.uiPatchList, &QListWidget::itemChanged, this, &PasteView::contentChanged);
foreach (const Protocol *p, protocols)
m_ui.protocolBox->addItem(p->name());
- connect(m_ui.protocolBox, SIGNAL(currentIndexChanged(int)),
- this, SLOT(protocolChanged(int)));
+ connect(m_ui.protocolBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &PasteView::protocolChanged);
}
PasteView::~PasteView()
diff --git a/src/plugins/cpaster/protocol.cpp b/src/plugins/cpaster/protocol.cpp
index 94393ee39bf..dcc8c330332 100644
--- a/src/plugins/cpaster/protocol.cpp
+++ b/src/plugins/cpaster/protocol.cpp
@@ -223,7 +223,7 @@ bool NetworkProtocol::httpStatus(QString url, QString *errorMessage, bool useHtt
// User canceled, discard and be happy.
if (!reply->isFinished()) {
QNetworkReply *replyPtr = reply.take();
- connect(replyPtr, SIGNAL(finished()), replyPtr, SLOT(deleteLater()));
+ connect(replyPtr, &QNetworkReply::finished, replyPtr, &QNetworkReply::deleteLater);
return false;
}
// Passed
diff --git a/src/plugins/cpaster/urlopenprotocol.cpp b/src/plugins/cpaster/urlopenprotocol.cpp
index 55e79d8c076..65eda4efe10 100644
--- a/src/plugins/cpaster/urlopenprotocol.cpp
+++ b/src/plugins/cpaster/urlopenprotocol.cpp
@@ -55,7 +55,8 @@ void UrlOpenProtocol::fetch(const QString &url)
{
QTC_ASSERT(!m_fetchReply, return);
m_fetchReply = httpGet(url);
- connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished()));
+ connect(m_fetchReply, &QNetworkReply::finished,
+ this, &UrlOpenProtocol::fetchFinished);
}
void UrlOpenProtocol::fetchFinished()
diff --git a/src/plugins/cppeditor/cppcodemodelinspectordialog.cpp b/src/plugins/cppeditor/cppcodemodelinspectordialog.cpp
index 36f2943d8ff..5f3fe6d6364 100644
--- a/src/plugins/cppeditor/cppcodemodelinspectordialog.cpp
+++ b/src/plugins/cppeditor/cppcodemodelinspectordialog.cpp
@@ -52,6 +52,7 @@
#include <QPushButton>
#include <QSortFilterProxyModel>
+using namespace CPlusPlus;
using namespace CppTools;
namespace CMI = CppCodeModelInspector;
@@ -71,22 +72,22 @@ TextEditor::BaseTextEditor *currentEditor()
QString fileInCurrentEditor()
{
if (TextEditor::BaseTextEditor *editor = currentEditor())
- return editor->document()->filePath();
+ return editor->document()->filePath().toString();
return QString();
}
-class DepthFinder : public CPlusPlus::SymbolVisitor {
+class DepthFinder : public SymbolVisitor {
public:
DepthFinder() : m_symbol(0), m_depth(-1), m_foundDepth(-1), m_stop(false) {}
- int operator()(const CPlusPlus::Document::Ptr &document, CPlusPlus::Symbol *symbol)
+ int operator()(const Document::Ptr &document, Symbol *symbol)
{
m_symbol = symbol;
accept(document->globalNamespace());
return m_foundDepth;
}
- bool preVisit(CPlusPlus::Symbol *symbol)
+ bool preVisit(Symbol *symbol)
{
if (m_stop)
return false;
@@ -103,14 +104,14 @@ public:
return false;
}
- void postVisit(CPlusPlus::Symbol *symbol)
+ void postVisit(Symbol *symbol)
{
if (symbol->asScope())
--m_depth;
}
private:
- CPlusPlus::Symbol *m_symbol;
+ Symbol *m_symbol;
int m_depth;
int m_foundDepth;
bool m_stop;
@@ -291,8 +292,8 @@ class SnapshotModel : public QAbstractListModel
Q_OBJECT
public:
SnapshotModel(QObject *parent);
- void configure(const CPlusPlus::Snapshot &snapshot);
- void setGlobalSnapshot(const CPlusPlus::Snapshot &snapshot);
+ void configure(const Snapshot &snapshot);
+ void setGlobalSnapshot(const Snapshot &snapshot);
QModelIndex indexForDocument(const QString &filePath);
@@ -304,22 +305,22 @@ public:
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
- QList<CPlusPlus::Document::Ptr> m_documents;
- CPlusPlus::Snapshot m_globalSnapshot;
+ QList<Document::Ptr> m_documents;
+ Snapshot m_globalSnapshot;
};
SnapshotModel::SnapshotModel(QObject *parent) : QAbstractListModel(parent)
{
}
-void SnapshotModel::configure(const CPlusPlus::Snapshot &snapshot)
+void SnapshotModel::configure(const Snapshot &snapshot)
{
emit layoutAboutToBeChanged();
m_documents = CMI::Utils::snapshotToList(snapshot);
emit layoutChanged();
}
-void SnapshotModel::setGlobalSnapshot(const CPlusPlus::Snapshot &snapshot)
+void SnapshotModel::setGlobalSnapshot(const Snapshot &snapshot)
{
m_globalSnapshot = snapshot;
}
@@ -327,7 +328,7 @@ void SnapshotModel::setGlobalSnapshot(const CPlusPlus::Snapshot &snapshot)
QModelIndex SnapshotModel::indexForDocument(const QString &filePath)
{
for (int i = 0, total = m_documents.size(); i < total; ++i) {
- const CPlusPlus::Document::Ptr document = m_documents.at(i);
+ const Document::Ptr document = m_documents.at(i);
if (document->fileName() == filePath)
return index(i, FilePathColumn);
}
@@ -348,11 +349,11 @@ QVariant SnapshotModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole) {
const int column = index.column();
- CPlusPlus::Document::Ptr document = m_documents.at(index.row());
+ Document::Ptr document = m_documents.at(index.row());
if (column == SymbolCountColumn) {
return document->control()->symbolCount();
} else if (column == SharedColumn) {
- CPlusPlus::Document::Ptr globalDocument = m_globalSnapshot.document(document->fileName());
+ Document::Ptr globalDocument = m_globalSnapshot.document(document->fileName());
const bool isShared
= globalDocument && globalDocument->fingerprint() == document->fingerprint();
return CMI::Utils::toString(isShared);
@@ -382,8 +383,8 @@ QVariant SnapshotModel::headerData(int section, Qt::Orientation orientation, int
// --- IncludesModel ------------------------------------------------------------------------------
-static bool includesSorter(const CPlusPlus::Document::Include &i1,
- const CPlusPlus::Document::Include &i2)
+static bool includesSorter(const Document::Include &i1,
+ const Document::Include &i2)
{
return i1.line() < i2.line();
}
@@ -393,7 +394,7 @@ class IncludesModel : public QAbstractListModel
Q_OBJECT
public:
IncludesModel(QObject *parent);
- void configure(const QList<CPlusPlus::Document::Include> &includes);
+ void configure(const QList<Document::Include> &includes);
void clear();
enum Columns { ResolvedOrNotColumn, LineNumberColumn, FilePathsColumn, ColumnCount };
@@ -404,14 +405,14 @@ public:
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
- QList<CPlusPlus::Document::Include> m_includes;
+ QList<Document::Include> m_includes;
};
IncludesModel::IncludesModel(QObject *parent) : QAbstractListModel(parent)
{
}
-void IncludesModel::configure(const QList<CPlusPlus::Document::Include> &includes)
+void IncludesModel::configure(const QList<Document::Include> &includes)
{
emit layoutAboutToBeChanged();
m_includes = includes;
@@ -444,7 +445,7 @@ QVariant IncludesModel::data(const QModelIndex &index, int role) const
static const QBrush greenBrush(QColor(0, 139, 69));
static const QBrush redBrush(QColor(205, 38, 38));
- const CPlusPlus::Document::Include include = m_includes.at(index.row());
+ const Document::Include include = m_includes.at(index.row());
const QString resolvedFileName = QDir::toNativeSeparators(include.resolvedFileName());
const bool isResolved = !resolvedFileName.isEmpty();
@@ -484,8 +485,8 @@ QVariant IncludesModel::headerData(int section, Qt::Orientation orientation, int
// --- DiagnosticMessagesModel --------------------------------------------------------------------
-static bool diagnosticMessagesModelSorter(const CPlusPlus::Document::DiagnosticMessage &m1,
- const CPlusPlus::Document::DiagnosticMessage &m2)
+static bool diagnosticMessagesModelSorter(const Document::DiagnosticMessage &m1,
+ const Document::DiagnosticMessage &m2)
{
return m1.line() < m2.line();
}
@@ -495,7 +496,7 @@ class DiagnosticMessagesModel : public QAbstractListModel
Q_OBJECT
public:
DiagnosticMessagesModel(QObject *parent);
- void configure(const QList<CPlusPlus::Document::DiagnosticMessage> &messages);
+ void configure(const QList<Document::DiagnosticMessage> &messages);
void clear();
enum Columns { LevelColumn, LineColumnNumberColumn, MessageColumn, ColumnCount };
@@ -506,7 +507,7 @@ public:
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
- QList<CPlusPlus::Document::DiagnosticMessage> m_messages;
+ QList<Document::DiagnosticMessage> m_messages;
};
DiagnosticMessagesModel::DiagnosticMessagesModel(QObject *parent) : QAbstractListModel(parent)
@@ -514,7 +515,7 @@ DiagnosticMessagesModel::DiagnosticMessagesModel(QObject *parent) : QAbstractLis
}
void DiagnosticMessagesModel::configure(
- const QList<CPlusPlus::Document::DiagnosticMessage> &messages)
+ const QList<Document::DiagnosticMessage> &messages)
{
emit layoutAboutToBeChanged();
m_messages = messages;
@@ -548,9 +549,9 @@ QVariant DiagnosticMessagesModel::data(const QModelIndex &index, int role) const
static const QBrush redBrush(QColor(205, 38, 38));
static const QBrush darkRedBrushQColor(QColor(139, 0, 0));
- const CPlusPlus::Document::DiagnosticMessage message = m_messages.at(index.row());
- const CPlusPlus::Document::DiagnosticMessage::Level level
- = static_cast<CPlusPlus::Document::DiagnosticMessage::Level>(message.level());
+ const Document::DiagnosticMessage message = m_messages.at(index.row());
+ const Document::DiagnosticMessage::Level level
+ = static_cast<Document::DiagnosticMessage::Level>(message.level());
if (role == Qt::DisplayRole) {
const int column = index.column();
@@ -564,11 +565,11 @@ QVariant DiagnosticMessagesModel::data(const QModelIndex &index, int role) const
}
} else if (role == Qt::ForegroundRole) {
switch (level) {
- case CPlusPlus::Document::DiagnosticMessage::Warning:
+ case Document::DiagnosticMessage::Warning:
return yellowOrangeBrush;
- case CPlusPlus::Document::DiagnosticMessage::Error:
+ case Document::DiagnosticMessage::Error:
return redBrush;
- case CPlusPlus::Document::DiagnosticMessage::Fatal:
+ case Document::DiagnosticMessage::Fatal:
return darkRedBrushQColor;
default:
return QVariant();
@@ -603,7 +604,7 @@ class MacrosModel : public QAbstractListModel
Q_OBJECT
public:
MacrosModel(QObject *parent);
- void configure(const QList<CPlusPlus::Macro> &macros);
+ void configure(const QList<Macro> &macros);
void clear();
enum Columns { LineNumberColumn, MacroColumn, ColumnCount };
@@ -614,14 +615,14 @@ public:
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
- QList<CPlusPlus::Macro> m_macros;
+ QList<Macro> m_macros;
};
MacrosModel::MacrosModel(QObject *parent) : QAbstractListModel(parent)
{
}
-void MacrosModel::configure(const QList<CPlusPlus::Macro> &macros)
+void MacrosModel::configure(const QList<Macro> &macros)
{
emit layoutAboutToBeChanged();
m_macros = macros;
@@ -649,7 +650,7 @@ QVariant MacrosModel::data(const QModelIndex &index, int role) const
{
const int column = index.column();
if (role == Qt::DisplayRole || (role == Qt::ToolTipRole && column == MacroColumn)) {
- const CPlusPlus::Macro macro = m_macros.at(index.row());
+ const Macro macro = m_macros.at(index.row());
if (column == LineNumberColumn)
return macro.line();
else if (column == MacroColumn)
@@ -682,7 +683,7 @@ class SymbolsModel : public QAbstractItemModel
Q_OBJECT
public:
SymbolsModel(QObject *parent);
- void configure(const CPlusPlus::Document::Ptr &document);
+ void configure(const Document::Ptr &document);
void clear();
enum Columns { SymbolColumn, LineNumberColumn, ColumnCount };
@@ -695,14 +696,14 @@ public:
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
private:
- CPlusPlus::Document::Ptr m_document;
+ Document::Ptr m_document;
};
SymbolsModel::SymbolsModel(QObject *parent) : QAbstractItemModel(parent)
{
}
-void SymbolsModel::configure(const CPlusPlus::Document::Ptr &document)
+void SymbolsModel::configure(const Document::Ptr &document)
{
QTC_CHECK(document);
emit layoutAboutToBeChanged();
@@ -717,23 +718,23 @@ void SymbolsModel::clear()
emit layoutChanged();
}
-static CPlusPlus::Symbol *indexToSymbol(const QModelIndex &index)
+static Symbol *indexToSymbol(const QModelIndex &index)
{
- if (CPlusPlus::Symbol *symbol = static_cast<CPlusPlus::Symbol*>(index.internalPointer()))
+ if (Symbol *symbol = static_cast<Symbol*>(index.internalPointer()))
return symbol;
return 0;
}
-static CPlusPlus::Scope *indexToScope(const QModelIndex &index)
+static Scope *indexToScope(const QModelIndex &index)
{
- if (CPlusPlus::Symbol *symbol = indexToSymbol(index))
+ if (Symbol *symbol = indexToSymbol(index))
return symbol->asScope();
return 0;
}
QModelIndex SymbolsModel::index(int row, int column, const QModelIndex &parent) const
{
- CPlusPlus::Scope *scope = 0;
+ Scope *scope = 0;
if (parent.isValid())
scope = indexToScope(parent);
else if (m_document)
@@ -752,8 +753,8 @@ QModelIndex SymbolsModel::parent(const QModelIndex &child) const
if (!child.isValid())
return QModelIndex();
- if (CPlusPlus::Symbol *symbol = indexToSymbol(child)) {
- if (CPlusPlus::Scope *scope = symbol->enclosingScope()) {
+ if (Symbol *symbol = indexToSymbol(child)) {
+ if (Scope *scope = symbol->enclosingScope()) {
const int row = DepthFinder()(m_document, scope);
return createIndex(row, 0, scope);
}
@@ -765,7 +766,7 @@ QModelIndex SymbolsModel::parent(const QModelIndex &child) const
int SymbolsModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid()) {
- if (CPlusPlus::Scope *scope = indexToScope(parent))
+ if (Scope *scope = indexToScope(parent))
return scope->memberCount();
} else {
if (m_document)
@@ -783,15 +784,15 @@ QVariant SymbolsModel::data(const QModelIndex &index, int role) const
{
const int column = index.column();
if (role == Qt::DisplayRole) {
- CPlusPlus::Symbol *symbol = indexToSymbol(index);
+ Symbol *symbol = indexToSymbol(index);
if (!symbol)
return QVariant();
if (column == LineNumberColumn) {
return symbol->line();
} else if (column == SymbolColumn) {
- QString name = CPlusPlus::Overview().prettyName(symbol->name());
+ QString name = Overview().prettyName(symbol->name());
if (name.isEmpty())
- name = QLatin1String("<no name>");
+ name = QLatin1String(symbol->isBlock() ? "<block>" : "<no name>");
return name;
}
}
@@ -820,7 +821,7 @@ class TokensModel : public QAbstractListModel
Q_OBJECT
public:
TokensModel(QObject *parent);
- void configure(CPlusPlus::TranslationUnit *translationUnit);
+ void configure(TranslationUnit *translationUnit);
void clear();
enum Columns { SpelledColumn, KindColumn, IndexColumn, OffsetColumn, LineColumnNumberColumn,
@@ -834,7 +835,7 @@ public:
private:
struct TokenInfo {
- CPlusPlus::Token token;
+ Token token;
unsigned line;
unsigned column;
};
@@ -845,7 +846,7 @@ TokensModel::TokensModel(QObject *parent) : QAbstractListModel(parent)
{
}
-void TokensModel::configure(CPlusPlus::TranslationUnit *translationUnit)
+void TokensModel::configure(TranslationUnit *translationUnit)
{
if (!translationUnit)
return;
@@ -883,11 +884,11 @@ QVariant TokensModel::data(const QModelIndex &index, int role) const
const int column = index.column();
if (role == Qt::DisplayRole) {
const TokenInfo info = m_tokenInfos.at(index.row());
- const CPlusPlus::Token token = info.token;
+ const Token token = info.token;
if (column == SpelledColumn)
return QString::fromUtf8(token.spell());
else if (column == KindColumn)
- return CMI::Utils::toString(static_cast<CPlusPlus::Kind>(token.kind()));
+ return CMI::Utils::toString(static_cast<Kind>(token.kind()));
else if (column == IndexColumn)
return index.row();
else if (column == OffsetColumn)
@@ -1087,10 +1088,11 @@ void WorkingCopyModel::configure(const WorkingCopy &workingCopy)
{
emit layoutAboutToBeChanged();
m_workingCopyList.clear();
- QHashIterator<QString, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
+ QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
while (it.hasNext()) {
it.next();
- m_workingCopyList << WorkingCopyEntry(it.key(), it.value().first, it.value().second);
+ m_workingCopyList << WorkingCopyEntry(it.key().toString(), it.value().first,
+ it.value().second);
}
emit layoutChanged();
}
@@ -1151,10 +1153,10 @@ class SnapshotInfo
{
public:
enum Type { GlobalSnapshot, EditorSnapshot };
- SnapshotInfo(const CPlusPlus::Snapshot &snapshot, Type type)
+ SnapshotInfo(const Snapshot &snapshot, Type type)
: snapshot(snapshot), type(type) {}
- CPlusPlus::Snapshot snapshot;
+ Snapshot snapshot;
Type type;
};
@@ -1340,7 +1342,7 @@ void CppCodeModelInspectorDialog::onWorkingCopyDocumentSelected(const QModelInde
void CppCodeModelInspectorDialog::refresh()
{
- CppTools::CppModelManager *cmmi = CppTools::CppModelManager::instance();
+ CppModelManager *cmmi = CppModelManager::instance();
const int oldSnapshotIndex = m_ui->snapshotSelector->currentIndex();
const bool selectEditorRelevant
@@ -1350,7 +1352,7 @@ void CppCodeModelInspectorDialog::refresh()
m_snapshotInfos->clear();
m_ui->snapshotSelector->clear();
- const CPlusPlus::Snapshot globalSnapshot = cmmi->snapshot();
+ const Snapshot globalSnapshot = cmmi->snapshot();
CppCodeModelInspector::Dumper dumper(globalSnapshot);
m_snapshotModel->setGlobalSnapshot(globalSnapshot);
@@ -1361,12 +1363,12 @@ void CppCodeModelInspectorDialog::refresh()
dumper.dumpSnapshot(globalSnapshot, globalSnapshotTitle, /*isGlobalSnapshot=*/ true);
TextEditor::BaseTextEditor *editor = currentEditor();
- EditorDocumentHandle *editorDocument = 0;
+ CppTools::CppEditorDocumentHandle *cppEditorDocument = 0;
if (editor) {
- const QString editorFilePath = editor->document()->filePath();
- editorDocument = cmmi->editorDocument(editorFilePath);
+ const QString editorFilePath = editor->document()->filePath().toString();
+ cppEditorDocument = cmmi->cppEditorDocument(editorFilePath);
if (auto *documentProcessor = BaseEditorDocumentProcessor::get(editorFilePath)) {
- const CPlusPlus::Snapshot editorSnapshot = documentProcessor->snapshot();
+ const Snapshot editorSnapshot = documentProcessor->snapshot();
m_snapshotInfos->append(SnapshotInfo(editorSnapshot, SnapshotInfo::EditorSnapshot));
const QString editorSnapshotTitle
= QString::fromLatin1("Current Editor's Snapshot (%1 Documents)")
@@ -1377,7 +1379,7 @@ void CppCodeModelInspectorDialog::refresh()
CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(editor->editorWidget());
if (cppEditorWidget) {
SemanticInfo semanticInfo = cppEditorWidget->semanticInfo();
- CPlusPlus::Snapshot snapshot;
+ Snapshot snapshot;
// Add semantic info snapshot
snapshot = semanticInfo.snapshot;
@@ -1388,7 +1390,7 @@ void CppCodeModelInspectorDialog::refresh()
// Add a pseudo snapshot containing only the semantic info document since this document
// is not part of the semantic snapshot.
- snapshot = CPlusPlus::Snapshot();
+ snapshot = Snapshot();
snapshot.insert(cppEditorWidget->semanticInfo().doc);
m_snapshotInfos->append(SnapshotInfo(snapshot, SnapshotInfo::EditorSnapshot));
const QString snapshotTitle
@@ -1415,8 +1417,8 @@ void CppCodeModelInspectorDialog::refresh()
onSnapshotSelected(snapshotIndex);
// Project Parts
- const ProjectPart::Ptr editorsProjectPart = editorDocument
- ? editorDocument->processor()->parser()->projectPart()
+ const ProjectPart::Ptr editorsProjectPart = cppEditorDocument
+ ? cppEditorDocument->processor()->parser()->projectPart()
: ProjectPart::Ptr();
const QList<ProjectInfo> projectInfos = cmmi->projectInfos();
@@ -1501,7 +1503,7 @@ void CppCodeModelInspectorDialog::clearDocumentData()
m_docTokensModel->clear();
}
-void CppCodeModelInspectorDialog::updateDocumentData(const CPlusPlus::Document::Ptr &document)
+void CppCodeModelInspectorDialog::updateDocumentData(const Document::Ptr &document)
{
QTC_ASSERT(document, return);
diff --git a/src/plugins/cppeditor/cppdocumentationcommenthelper.cpp b/src/plugins/cppeditor/cppdocumentationcommenthelper.cpp
index 7063fc9715e..1bb5959b20a 100644
--- a/src/plugins/cppeditor/cppdocumentationcommenthelper.cpp
+++ b/src/plugins/cppeditor/cppdocumentationcommenthelper.cpp
@@ -33,11 +33,11 @@
#include "cppautocompleter.h"
#include <cpptools/cpptoolssettings.h>
+#include <cpptools/commentssettings.h>
#include <cpptools/doxygengenerator.h>
#include <texteditor/texteditor.h>
#include <QDebug>
-#include <QKeyEvent>
#include <QTextBlock>
using namespace CppTools;
@@ -53,13 +53,10 @@ bool isStartOfDoxygenComment(const QTextCursor &cursor)
+ document->characterAt(pos - 2)
+ document->characterAt(pos - 1);
- if ((comment == QLatin1String("/**"))
- || (comment == QLatin1String("/*!"))
- || (comment == QLatin1String("///"))
- || (comment == QLatin1String("//!"))) {
- return true;
- }
- return false;
+ return comment == QLatin1String("/**")
+ || comment == QLatin1String("/*!")
+ || comment == QLatin1String("///")
+ || comment == QLatin1String("//!");
}
DoxygenGenerator::DocumentationStyle doxygenStyle(const QTextCursor &cursor,
@@ -119,7 +116,7 @@ bool isNextLineCppStyleComment(const QTextCursor &cursor)
bool isCppStyleContinuation(const QTextCursor& cursor)
{
- return (isPreviousLineCppStyleComment(cursor) || isNextLineCppStyleComment(cursor));
+ return isPreviousLineCppStyleComment(cursor) || isNextLineCppStyleComment(cursor);
}
bool lineStartsWithCppDoxygenCommentAndCursorIsAfter(const QTextCursor &cursor,
@@ -160,7 +157,7 @@ bool isCursorAfterNonNestedCppStyleComment(const QTextCursor &cursor,
return !editorWidget->autoCompleter()->isInComment(cursorBeforeCppComment);
}
-bool handleDoxygenCppStyleContinuation(QTextCursor &cursor, QKeyEvent *e)
+bool handleDoxygenCppStyleContinuation(QTextCursor &cursor)
{
const int blockPos = cursor.positionInBlock();
const QString &text = cursor.block().text();
@@ -186,12 +183,10 @@ bool handleDoxygenCppStyleContinuation(QTextCursor &cursor, QKeyEvent *e)
newLine.append(QLatin1Char(' '));
cursor.insertText(newLine);
- e->accept();
return true;
}
bool handleDoxygenContinuation(QTextCursor &cursor,
- QKeyEvent *e,
TextEditor::TextEditorWidget *editorWidget,
const bool enableDoxygen,
const bool leadingAsterisks)
@@ -204,7 +199,7 @@ bool handleDoxygenContinuation(QTextCursor &cursor,
if (!cursor.atEnd()) {
if (enableDoxygen && lineStartsWithCppDoxygenCommentAndCursorIsAfter(cursor, doc))
- return handleDoxygenCppStyleContinuation(cursor, e);
+ return handleDoxygenCppStyleContinuation(cursor);
if (isCursorAfterNonNestedCppStyleComment(cursor, editorWidget))
return false;
@@ -268,7 +263,6 @@ bool handleDoxygenContinuation(QTextCursor &cursor,
newLine.append(QLatin1Char(' '));
}
cursor.insertText(newLine);
- e->accept();
return true;
}
}
@@ -281,88 +275,66 @@ bool handleDoxygenContinuation(QTextCursor &cursor,
namespace CppEditor {
namespace Internal {
-CppDocumentationCommentHelper::CppDocumentationCommentHelper(
- TextEditor::TextEditorWidget *editorWidget)
- : m_editorWidget(editorWidget)
- , m_settings(CppToolsSettings::instance()->commentsSettings())
-{
- connect(CppToolsSettings::instance(),
- SIGNAL(commentsSettingsChanged(CppTools::CommentsSettings)),
- this,
- SLOT(onCommentsSettingsChanged(CppTools::CommentsSettings)));
-}
-
-bool CppDocumentationCommentHelper::handleKeyPressEvent(QKeyEvent *e) const
+bool trySplitComment(TextEditor::TextEditorWidget *editorWidget)
{
- if (!m_settings.m_enableDoxygen && !m_settings.m_leadingAsterisks)
+ const CommentsSettings &settings = CppToolsSettings::instance()->commentsSettings();
+ if (!settings.m_enableDoxygen && !settings.m_leadingAsterisks)
return false;
- if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
- QTextCursor cursor = m_editorWidget->textCursor();
- if (!m_editorWidget->autoCompleter()->isInComment(cursor))
- return false;
+ QTextCursor cursor = editorWidget->textCursor();
+ if (!editorWidget->autoCompleter()->isInComment(cursor))
+ return false;
- // We are interested on two particular cases:
- // 1) The cursor is right after a /**, /*!, /// or ///! and the user pressed enter.
- // If Doxygen is enabled we need to generate an entire comment block.
- // 2) The cursor is already in the middle of a multi-line comment and the user pressed
- // enter. If leading asterisk(s) is set we need to write a comment continuation
- // with those.
-
- if (m_settings.m_enableDoxygen && cursor.positionInBlock() >= 3) {
- const int pos = cursor.position();
- if (isStartOfDoxygenComment(cursor)) {
- QTextDocument *textDocument = m_editorWidget->document();
- DoxygenGenerator::DocumentationStyle style = doxygenStyle(cursor, textDocument);
-
- // Check if we're already in a CppStyle Doxygen comment => continuation
- // Needs special handling since CppStyle does not have start and end markers
- if ((style == DoxygenGenerator::CppStyleA || style == DoxygenGenerator::CppStyleB)
- && isCppStyleContinuation(cursor)) {
- return handleDoxygenCppStyleContinuation(cursor, e);
- }
+ // We are interested on two particular cases:
+ // 1) The cursor is right after a /**, /*!, /// or ///! and the user pressed enter.
+ // If Doxygen is enabled we need to generate an entire comment block.
+ // 2) The cursor is already in the middle of a multi-line comment and the user pressed
+ // enter. If leading asterisk(s) is set we need to write a comment continuation
+ // with those.
+
+ if (settings.m_enableDoxygen && cursor.positionInBlock() >= 3) {
+ const int pos = cursor.position();
+ if (isStartOfDoxygenComment(cursor)) {
+ QTextDocument *textDocument = editorWidget->document();
+ DoxygenGenerator::DocumentationStyle style = doxygenStyle(cursor, textDocument);
+
+ // Check if we're already in a CppStyle Doxygen comment => continuation
+ // Needs special handling since CppStyle does not have start and end markers
+ if ((style == DoxygenGenerator::CppStyleA || style == DoxygenGenerator::CppStyleB)
+ && isCppStyleContinuation(cursor)) {
+ return handleDoxygenCppStyleContinuation(cursor);
+ }
- DoxygenGenerator doxygen;
- doxygen.setStyle(style);
- doxygen.setAddLeadingAsterisks(m_settings.m_leadingAsterisks);
- doxygen.setGenerateBrief(m_settings.m_generateBrief);
- doxygen.setStartComment(false);
+ DoxygenGenerator doxygen;
+ doxygen.setStyle(style);
+ doxygen.setAddLeadingAsterisks(settings.m_leadingAsterisks);
+ doxygen.setGenerateBrief(settings.m_generateBrief);
+ doxygen.setStartComment(false);
- // Move until we reach any possibly meaningful content.
- while (textDocument->characterAt(cursor.position()).isSpace()
- && cursor.movePosition(QTextCursor::NextCharacter)) {
- }
+ // Move until we reach any possibly meaningful content.
+ while (textDocument->characterAt(cursor.position()).isSpace()
+ && cursor.movePosition(QTextCursor::NextCharacter)) {
+ }
- if (!cursor.atEnd()) {
- const QString &comment = doxygen.generate(cursor);
- if (!comment.isEmpty()) {
- cursor.beginEditBlock();
- cursor.setPosition(pos);
- cursor.insertText(comment);
- cursor.setPosition(pos - 3, QTextCursor::KeepAnchor);
- m_editorWidget->textDocument()->autoIndent(cursor);
- cursor.endEditBlock();
- e->accept();
- return true;
- }
+ if (!cursor.atEnd()) {
+ const QString &comment = doxygen.generate(cursor);
+ if (!comment.isEmpty()) {
+ cursor.beginEditBlock();
+ cursor.setPosition(pos);
+ cursor.insertText(comment);
+ cursor.setPosition(pos - 3, QTextCursor::KeepAnchor);
+ editorWidget->textDocument()->autoIndent(cursor);
+ cursor.endEditBlock();
+ return true;
}
-
}
- } // right after first doxygen comment
-
- return handleDoxygenContinuation(cursor,
- e,
- m_editorWidget,
- m_settings.m_enableDoxygen,
- m_settings.m_leadingAsterisks);
- }
-
- return false;
-}
+ }
+ } // right after first doxygen comment
-void CppDocumentationCommentHelper::onCommentsSettingsChanged(const CommentsSettings &settings)
-{
- m_settings = settings;
+ return handleDoxygenContinuation(cursor,
+ editorWidget,
+ settings.m_enableDoxygen,
+ settings.m_leadingAsterisks);
}
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppdocumentationcommenthelper.h b/src/plugins/cppeditor/cppdocumentationcommenthelper.h
index 436eb815674..09712aebc2f 100644
--- a/src/plugins/cppeditor/cppdocumentationcommenthelper.h
+++ b/src/plugins/cppeditor/cppdocumentationcommenthelper.h
@@ -31,35 +31,14 @@
#ifndef CPPDOCUMENTATIONCOMMENTHELPER_H
#define CPPDOCUMENTATIONCOMMENTHELPER_H
-#include <QObject>
-
-#include <cpptools/commentssettings.h>
-
-QT_FORWARD_DECLARE_CLASS(QKeyEvent)
+#include "cppeditor_global.h"
namespace TextEditor { class TextEditorWidget; }
namespace CppEditor {
namespace Internal {
-class CppDocumentationCommentHelper : public QObject
-{
- Q_OBJECT
- Q_DISABLE_COPY(CppDocumentationCommentHelper)
-
-public:
- explicit CppDocumentationCommentHelper(TextEditor::TextEditorWidget *editorWidget);
- bool handleKeyPressEvent(QKeyEvent *e) const;
-
-private slots:
- void onCommentsSettingsChanged(const CppTools::CommentsSettings &settings);
-
-private:
- CppDocumentationCommentHelper();
-
- TextEditor::TextEditorWidget *m_editorWidget;
- CppTools::CommentsSettings m_settings;
-};
+bool trySplitComment(TextEditor::TextEditorWidget *editorWidget);
} // namespace Internal
} // namespace CppEditor
diff --git a/src/plugins/cppeditor/cppdoxygen_test.cpp b/src/plugins/cppeditor/cppdoxygen_test.cpp
index 84f140a3713..d5d2afb0089 100644
--- a/src/plugins/cppeditor/cppdoxygen_test.cpp
+++ b/src/plugins/cppeditor/cppdoxygen_test.cpp
@@ -28,110 +28,43 @@
**
****************************************************************************/
-#include "cppeditorplugin.h"
+#include "cppdoxygen_test.h"
+
#include "cppeditortestcase.h"
-#include <coreplugin/editormanager/editormanager.h>
-#include <cpptools/commentssettings.h>
-#include <cpptools/cppmodelmanager.h>
#include <cpptools/cpptoolssettings.h>
-#include <cplusplus/CppDocument.h>
-#include <utils/fileutils.h>
-
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QKeyEvent>
-#include <QString>
#include <QtTest>
-/*!
- Tests for inserting doxygen comments.
- */
-using namespace Core;
-using namespace CPlusPlus;
-
namespace { typedef QByteArray _; }
-/**
- * Encapsulates the whole process of setting up an editor,
- * pressing ENTER and checking the result.
- */
-
namespace CppEditor {
namespace Internal {
namespace Tests {
-class DoxygenTestCase : public Internal::Tests::TestCase
+void DoxygenTest::initTestCase()
{
- QScopedPointer<CppTools::CommentsSettings> oldSettings;
-public:
- /// The '|' in the input denotes the cursor position.
- DoxygenTestCase(const QByteArray &original, const QByteArray &expected,
- CppTools::CommentsSettings *injectedSettings = 0)
- {
- QVERIFY(succeededSoFar());
-
- TestDocument testDocument("file.cpp", original, '|');
- QVERIFY(testDocument.hasCursorMarker());
- testDocument.m_source.remove(testDocument.m_cursorPosition, 1);
- QVERIFY(testDocument.writeToDisk());
-
- // Update Code Model
- QVERIFY(parseFiles(testDocument.filePath()));
-
- // Open Editor
- QVERIFY(openCppEditor(testDocument.filePath(), &testDocument.m_editor,
- &testDocument.m_editorWidget));
- closeEditorAtEndOfTestCase(testDocument.m_editor);
-
- if (injectedSettings) {
- auto *cts = CppTools::CppToolsSettings::instance();
- oldSettings.reset(new CppTools::CommentsSettings(cts->commentsSettings()));
- injectSettings(injectedSettings);
- }
-
- // We want to test documents that start with a comment. By default, the
- // editor will fold the very first comment it encounters, assuming
- // it is a license header. Currently unfoldAll() does not work as
- // expected (some blocks are still hidden in some test cases, so the
- // cursor movements are not as expected). For the time being, we just
- // prepend a declaration before the initial test comment.
- // testDocument.m_editorWidget->unfoldAll();
- testDocument.m_editor->setCursorPosition(testDocument.m_cursorPosition);
-
- waitForRehighlightedSemanticDocument(testDocument.m_editorWidget);
-
- // Send 'ENTER' key press
- QKeyEvent event(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
- QCoreApplication::sendEvent(testDocument.m_editorWidget, &event);
- const QByteArray result = testDocument.m_editorWidget->document()->toPlainText().toUtf8();
-
- QCOMPARE(QLatin1String(result), QLatin1String(expected));
-
- testDocument.m_editorWidget->undo();
- const QString contentsAfterUndo = testDocument.m_editorWidget->document()->toPlainText();
- QCOMPARE(contentsAfterUndo, testDocument.m_source);
- }
-
- ~DoxygenTestCase()
- {
- if (oldSettings)
- injectSettings(oldSettings.data());
- }
+ verifyCleanState();
+}
- static void injectSettings(CppTools::CommentsSettings *injection)
- {
- auto *cts = CppTools::CppToolsSettings::instance();
- QVERIFY(QMetaObject::invokeMethod(cts, "commentsSettingsChanged", Qt::DirectConnection,
- Q_ARG(CppTools::CommentsSettings, *injection)));
- }
-};
+void DoxygenTest::cleanTestCase()
+{
+ verifyCleanState();
+}
-} // namespace Tests
+void DoxygenTest::cleanup()
+{
+ if (oldSettings)
+ CppTools::CppToolsSettings::instance()->setCommentsSettings(*oldSettings);
+ QVERIFY(Core::EditorManager::closeAllEditors(false));
+ QVERIFY(TestCase::garbageCollectGlobalSnapshot());
+}
-void CppEditorPlugin::test_doxygen_comments_data()
+void DoxygenTest::testBasic_data()
{
QTest::addColumn<QByteArray>("given");
QTest::addColumn<QByteArray>("expected");
@@ -288,14 +221,14 @@ void CppEditorPlugin::test_doxygen_comments_data()
);
}
-void CppEditorPlugin::test_doxygen_comments()
+void DoxygenTest::testBasic()
{
QFETCH(QByteArray, given);
QFETCH(QByteArray, expected);
- Tests::DoxygenTestCase(given, expected);
+ runTest(given, expected);
}
-void CppEditorPlugin::test_doxygen_comments_no_leading_asterisks_data()
+void DoxygenTest::testNoLeadingAsterisks_data()
{
QTest::addColumn<QByteArray>("given");
QTest::addColumn<QByteArray>("expected");
@@ -308,7 +241,7 @@ void CppEditorPlugin::test_doxygen_comments_no_leading_asterisks_data()
);
}
-void CppEditorPlugin::test_doxygen_comments_no_leading_asterisks()
+void DoxygenTest::testNoLeadingAsterisks()
{
QFETCH(QByteArray, given);
QFETCH(QByteArray, expected);
@@ -317,8 +250,65 @@ void CppEditorPlugin::test_doxygen_comments_no_leading_asterisks()
injection.m_enableDoxygen = true;
injection.m_leadingAsterisks = false;
- Tests::DoxygenTestCase(given, expected, &injection);
+ runTest(given, expected, &injection);
}
+void DoxygenTest::verifyCleanState() const
+{
+ QVERIFY(CppTools::Tests::VerifyCleanCppModelManager::isClean());
+ QVERIFY(Core::DocumentModel::openedDocuments().isEmpty());
+ QVERIFY(Core::EditorManager::visibleEditors().isEmpty());
+}
+
+/// The '|' in the input denotes the cursor position.
+void DoxygenTest::runTest(const QByteArray &original, const QByteArray &expected,
+ CppTools::CommentsSettings *settings)
+{
+ // Write files to disk
+ CppTools::Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+ TestDocument testDocument("file.cpp", original, '|');
+ QVERIFY(testDocument.hasCursorMarker());
+ testDocument.m_source.remove(testDocument.m_cursorPosition, 1);
+ testDocument.setBaseDirectory(temporaryDir.path());
+ QVERIFY(testDocument.writeToDisk());
+
+ // Update Code Model
+ QVERIFY(TestCase::parseFiles(testDocument.filePath()));
+
+ // Open Editor
+ QVERIFY(TestCase::openCppEditor(testDocument.filePath(), &testDocument.m_editor,
+ &testDocument.m_editorWidget));
+
+ if (settings) {
+ auto *cts = CppTools::CppToolsSettings::instance();
+ oldSettings.reset(new CppTools::CommentsSettings(cts->commentsSettings()));
+ cts->setCommentsSettings(*settings);
+ }
+
+ // We want to test documents that start with a comment. By default, the
+ // editor will fold the very first comment it encounters, assuming
+ // it is a license header. Currently unfoldAll() does not work as
+ // expected (some blocks are still hidden in some test cases, so the
+ // cursor movements are not as expected). For the time being, we just
+ // prepend a declaration before the initial test comment.
+ // testDocument.m_editorWidget->unfoldAll();
+ testDocument.m_editor->setCursorPosition(testDocument.m_cursorPosition);
+
+ TestCase::waitForRehighlightedSemanticDocument(testDocument.m_editorWidget);
+
+ // Send 'ENTER' key press
+ QKeyEvent event(QEvent::KeyPress, Qt::Key_Enter, Qt::NoModifier);
+ QCoreApplication::sendEvent(testDocument.m_editorWidget, &event);
+ const QByteArray result = testDocument.m_editorWidget->document()->toPlainText().toUtf8();
+
+ QCOMPARE(QLatin1String(result), QLatin1String(expected));
+
+ testDocument.m_editorWidget->undo();
+ const QString contentsAfterUndo = testDocument.m_editorWidget->document()->toPlainText();
+ QCOMPARE(contentsAfterUndo, testDocument.m_source);
+}
+
+} // namespace Tests
} // namespace Internal
} // namespace CppEditor
diff --git a/src/plugins/genericprojectmanager/cppmodelmanagerhelper.h b/src/plugins/cppeditor/cppdoxygen_test.h
index 61fc4973cf8..b114f3e9abe 100644
--- a/src/plugins/genericprojectmanager/cppmodelmanagerhelper.h
+++ b/src/plugins/cppeditor/cppdoxygen_test.h
@@ -28,39 +28,44 @@
**
****************************************************************************/
-#ifndef CPPMODELMANAGERHELPER_H
-#define CPPMODELMANAGERHELPER_H
+#ifndef CPPDOXYGEN_TEST_H
+#define CPPDOXYGEN_TEST_H
-#include <cpptools/cppmodelmanager.h>
+#include <cpptools/commentssettings.h>
#include <QObject>
-#include <QSignalSpy>
+#include <QScopedPointer>
-namespace GenericProjectManager {
+namespace CppEditor {
namespace Internal {
namespace Tests {
-class CppModelManagerHelper : public QObject
+/// Tests for inserting doxygen comments.
+class DoxygenTest: public QObject
{
Q_OBJECT
-public:
- explicit CppModelManagerHelper(QObject *parent = 0);
- static CppTools::CppModelManager *cppModelManager();
+private slots:
+ void initTestCase();
+ void cleanTestCase();
+ void cleanup();
- enum { defaultTimeOut = 30 * 1000 }; // 30 secs
- void waitForSourceFilesRefreshed(const QString &file = QString(), int timeOut = defaultTimeOut);
- void waitForSourceFilesRefreshed(const QStringList &files, int timeOut = defaultTimeOut);
+ void testBasic_data();
+ void testBasic();
+
+ void testNoLeadingAsterisks_data();
+ void testNoLeadingAsterisks();
private:
- void onSourceFilesRefreshed(const QSet<QString> &files);
+ void verifyCleanState() const;
+ void runTest(const QByteArray &original, const QByteArray &expected,
+ CppTools::CommentsSettings *settings = 0);
- QSet<QString> m_refreshedSourceFiles;
- QSignalSpy m_spy;
+ QScopedPointer<CppTools::CommentsSettings> oldSettings;
};
-} // Tests namespace
-} // Internal namespace
-} // GenericProjectManager namespace
+} // namespace Tests
+} // namespace Internal
+} // namespace CppEditor
-#endif // CPPMODELMANAGERHELPER_H
+#endif // CPPDOXYGEN_TEST_H
diff --git a/src/plugins/cppeditor/cppeditor.cpp b/src/plugins/cppeditor/cppeditor.cpp
index 1fbb310da3b..11149398482 100644
--- a/src/plugins/cppeditor/cppeditor.cpp
+++ b/src/plugins/cppeditor/cppeditor.cpp
@@ -35,7 +35,6 @@
#include "cppdocumentationcommenthelper.h"
#include "cppeditorconstants.h"
#include "cppeditordocument.h"
-#include "cppeditoroutline.h"
#include "cppeditorplugin.h"
#include "cppfollowsymbolundercursor.h"
#include "cpphighlighter.h"
@@ -51,6 +50,7 @@
#include <cpptools/cppchecksymbols.h>
#include <cpptools/cppcodeformatter.h>
#include <cpptools/cppcompletionassistprovider.h>
+#include <cpptools/cppeditoroutline.h>
#include <cpptools/cppmodelmanager.h>
#include <cpptools/cppsemanticinfo.h>
#include <cpptools/cpptoolsconstants.h>
@@ -105,18 +105,16 @@ public:
CppEditorWidgetPrivate(CppEditorWidget *q);
public:
- QPointer<CppTools::CppModelManager> m_modelManager;
+ QPointer<CppModelManager> m_modelManager;
CppEditorDocument *m_cppEditorDocument;
CppEditorOutline *m_cppEditorOutline;
- CppDocumentationCommentHelper m_cppDocumentationCommentHelper;
-
QTimer m_updateFunctionDeclDefLinkTimer;
CppLocalRenaming m_localRenaming;
- CppTools::SemanticInfo m_lastSemanticInfo;
+ SemanticInfo m_lastSemanticInfo;
QuickFixOperations m_quickFixes;
CppUseSelectionsUpdater m_useSelectionsUpdater;
@@ -132,7 +130,6 @@ CppEditorWidgetPrivate::CppEditorWidgetPrivate(CppEditorWidget *q)
: m_modelManager(CppModelManager::instance())
, m_cppEditorDocument(qobject_cast<CppEditorDocument *>(q->textDocument()))
, m_cppEditorOutline(new CppEditorOutline(q))
- , m_cppDocumentationCommentHelper(q)
, m_localRenaming(q)
, m_useSelectionsUpdater(q)
, m_declDefLinkFinder(new FunctionDeclDefLinkFinder(q))
@@ -175,7 +172,7 @@ void CppEditorWidget::finalizeInitialization()
SLOT(updateSelectionsForVariableUnderCursor(QList<QTextEdit::ExtraSelection>)));
connect(&d->m_useSelectionsUpdater, &CppUseSelectionsUpdater::finished,
- [this] (CppTools::SemanticInfo::LocalUseMap localUses) {
+ [this] (SemanticInfo::LocalUseMap localUses) {
QTC_CHECK(isSemanticInfoValidExceptLocalUses());
d->m_lastSemanticInfo.localUsesUpdated = true;
d->m_lastSemanticInfo.localUses = localUses;
@@ -541,8 +538,12 @@ void CppEditorWidget::keyPressEvent(QKeyEvent *e)
if (handleStringSplitting(e))
return;
- if (d->m_cppDocumentationCommentHelper.handleKeyPressEvent(e))
- return;
+ if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
+ if (trySplitComment(this)) {
+ e->accept();
+ return;
+ }
+ }
TextEditorWidget::keyPressEvent(e);
}
@@ -579,38 +580,12 @@ bool CppEditorWidget::handleStringSplitting(QKeyEvent *e) const
return false;
}
-void CppEditorWidget::applyFontSettings()
-{
- // This also makes the document apply font settings
- TextEditorWidget::applyFontSettings();
-}
-
void CppEditorWidget::slotCodeStyleSettingsChanged(const QVariant &)
{
- CppTools::QtStyleCodeFormatter formatter;
+ QtStyleCodeFormatter formatter;
formatter.invalidateCache(document());
}
-CppEditorWidget::Link CppEditorWidget::linkToSymbol(CPlusPlus::Symbol *symbol)
-{
- if (!symbol)
- return Link();
-
- const QString filename = QString::fromUtf8(symbol->fileName(),
- symbol->fileNameLength());
-
- unsigned line = symbol->line();
- unsigned column = symbol->column();
-
- if (column)
- --column;
-
- if (symbol->isGenerated())
- column = 0;
-
- return Link(filename, line, column);
-}
-
void CppEditorWidget::updateSemanticInfo(const SemanticInfo &semanticInfo,
bool updateUseSelectionSynchronously)
{
@@ -636,7 +611,7 @@ AssistInterface *CppEditorWidget::createAssistInterface(AssistKind kind, AssistR
if (CppCompletionAssistProvider *cap =
qobject_cast<CppCompletionAssistProvider *>(cppEditorDocument()->completionAssistProvider())) {
return cap->createAssistInterface(
- textDocument()->filePath(),
+ textDocument()->filePath().toString(),
document(),
cppEditorDocument()->isObjCEnabled(),
position(),
@@ -690,10 +665,6 @@ void CppEditorWidget::updateFunctionDeclDefLink()
void CppEditorWidget::updateFunctionDeclDefLinkNow()
{
- static bool noTracking = qgetenv("QTC_NO_FUNCTION_DECL_DEF_LINK_TRACKING").trimmed() == "1";
- if (noTracking)
- return;
-
IEditor *editor = EditorManager::currentEditor();
if (!editor || editor->widget() != this)
return;
@@ -765,7 +736,7 @@ void CppEditorWidget::abortDeclDefLink()
void CppEditorWidget::showPreProcessorWidget()
{
- const QString &fileName = textDocument()->filePath();
+ const Utils::FileName fileName = textDocument()->filePath();
// Check if this editor belongs to a project
QList<ProjectPart::Ptr> projectParts = d->m_modelManager->projectPart(fileName);
@@ -774,7 +745,7 @@ void CppEditorWidget::showPreProcessorWidget()
if (projectParts.isEmpty())
projectParts << d->m_modelManager->fallbackProjectPart();
- CppPreProcessorDialog preProcessorDialog(this, textDocument()->filePath(), projectParts);
+ CppPreProcessorDialog preProcessorDialog(this, textDocument()->filePath().toString(), projectParts);
if (preProcessorDialog.exec() == QDialog::Accepted) {
cppEditorDocument()->setPreprocessorSettings(
preProcessorDialog.projectPart(),
diff --git a/src/plugins/cppeditor/cppeditor.h b/src/plugins/cppeditor/cppeditor.h
index e63122c949e..b07185cfb3d 100644
--- a/src/plugins/cppeditor/cppeditor.h
+++ b/src/plugins/cppeditor/cppeditor.h
@@ -35,17 +35,18 @@
#include <texteditor/texteditor.h>
-
#include <QScopedPointer>
-namespace CPlusPlus { class Symbol; }
-namespace CppTools { class SemanticInfo; }
+namespace CppTools {
+class CppEditorOutline;
+class SemanticInfo;
+}
namespace CppEditor {
namespace Internal {
class CppEditorDocument;
-class CppEditorOutline;
+
class CppEditorWidgetPrivate;
class FollowSymbolUnderCursor;
class FunctionDeclDefLink;
@@ -63,14 +64,11 @@ class CppEditorWidget : public TextEditor::TextEditorWidget
Q_OBJECT
public:
- static Link linkToSymbol(CPlusPlus::Symbol *symbol);
-
-public:
CppEditorWidget();
~CppEditorWidget();
CppEditorDocument *cppEditorDocument() const;
- CppEditorOutline *outline() const;
+ CppTools::CppEditorOutline *outline() const;
CppTools::SemanticInfo semanticInfo() const;
bool isSemanticInfoValidExceptLocalUses() const;
@@ -103,8 +101,6 @@ protected:
void keyPressEvent(QKeyEvent *e) Q_DECL_OVERRIDE;
bool handleStringSplitting(QKeyEvent *e) const;
- void applyFontSettings() Q_DECL_OVERRIDE;
-
Link findLinkAt(const QTextCursor &, bool resolveTarget = true,
bool inNextSplit = false) Q_DECL_OVERRIDE;
diff --git a/src/plugins/cppeditor/cppeditor.pro b/src/plugins/cppeditor/cppeditor.pro
index a4c0bf2a5ea..b616682dce1 100644
--- a/src/plugins/cppeditor/cppeditor.pro
+++ b/src/plugins/cppeditor/cppeditor.pro
@@ -11,7 +11,6 @@ HEADERS += \
cppeditordocument.h \
cppeditorconstants.h \
cppeditorenums.h \
- cppeditoroutline.h \
cppeditorplugin.h \
cppelementevaluator.h \
cppfollowsymbolundercursor.h \
@@ -42,7 +41,6 @@ SOURCES += \
cppdocumentationcommenthelper.cpp \
cppeditor.cpp \
cppeditordocument.cpp \
- cppeditoroutline.cpp \
cppeditorplugin.cpp \
cppelementevaluator.cpp \
cppfollowsymbolundercursor.cpp \
@@ -76,6 +74,7 @@ RESOURCES += \
equals(TEST, 1) {
HEADERS += \
cppeditortestcase.h \
+ cppdoxygen_test.h \
cppquickfix_test.h
SOURCES += \
cppdoxygen_test.cpp \
diff --git a/src/plugins/cppeditor/cppeditor.qbs b/src/plugins/cppeditor/cppeditor.qbs
index bceb436e572..cb1248508e1 100644
--- a/src/plugins/cppeditor/cppeditor.qbs
+++ b/src/plugins/cppeditor/cppeditor.qbs
@@ -27,7 +27,6 @@ QtcPlugin {
"cppeditorconstants.h",
"cppeditordocument.cpp", "cppeditordocument.h",
"cppeditorenums.h",
- "cppeditoroutline.cpp", "cppeditoroutline.h",
"cppeditorplugin.cpp", "cppeditorplugin.h",
"cppelementevaluator.cpp", "cppelementevaluator.h",
"cppfollowsymbolundercursor.cpp", "cppfollowsymbolundercursor.h",
@@ -57,7 +56,7 @@ QtcPlugin {
name: "Tests"
condition: project.testsEnabled
files: [
- "cppdoxygen_test.cpp",
+ "cppdoxygen_test.cpp", "cppdoxygen_test.h",
"cppeditortestcase.cpp", "cppeditortestcase.h",
"cppincludehierarchy_test.cpp",
"cppquickfix_test.cpp",
diff --git a/src/plugins/cppeditor/cppeditordocument.cpp b/src/plugins/cppeditor/cppeditordocument.cpp
index 92b2878a2b3..40abd27f442 100644
--- a/src/plugins/cppeditor/cppeditordocument.cpp
+++ b/src/plugins/cppeditor/cppeditordocument.cpp
@@ -63,19 +63,19 @@ namespace Internal {
enum { processDocumentIntervalInMs = 150 };
-class CppEditorDocumentHandle : public CppTools::EditorDocumentHandle
+class CppEditorDocumentHandleImpl : public CppTools::CppEditorDocumentHandle
{
public:
- CppEditorDocumentHandle(CppEditor::Internal::CppEditorDocument *cppEditorDocument)
+ CppEditorDocumentHandleImpl(CppEditorDocument *cppEditorDocument)
: m_cppEditorDocument(cppEditorDocument)
- , m_registrationFilePath(cppEditorDocument->filePath())
+ , m_registrationFilePath(cppEditorDocument->filePath().toString())
{
- mm()->registerEditorDocument(this);
+ mm()->registerCppEditorDocument(this);
}
- ~CppEditorDocumentHandle() { mm()->unregisterEditorDocument(m_registrationFilePath); }
+ ~CppEditorDocumentHandleImpl() { mm()->unregisterCppEditorDocument(m_registrationFilePath); }
- QString filePath() const { return m_cppEditorDocument->filePath(); }
+ QString filePath() const { return m_cppEditorDocument->filePath().toString(); }
QByteArray contents() const { return m_cppEditorDocument->contentsText(); }
unsigned revision() const { return m_cppEditorDocument->contentsRevision(); }
@@ -105,8 +105,8 @@ CppEditorDocument::CppEditorDocument()
connect(this, SIGNAL(aboutToReload()), this, SLOT(onAboutToReload()));
connect(this, SIGNAL(reloadFinished(bool)), this, SLOT(onReloadFinished()));
- connect(this, SIGNAL(filePathChanged(QString,QString)),
- this, SLOT(onFilePathChanged(QString,QString)));
+ connect(this, &IDocument::filePathChanged,
+ this, &CppEditorDocument::onFilePathChanged);
m_processorTimer.setSingleShot(true);
m_processorTimer.setInterval(processDocumentIntervalInMs);
@@ -196,18 +196,20 @@ void CppEditorDocument::onReloadFinished()
m_fileIsBeingReloaded = false;
}
-void CppEditorDocument::onFilePathChanged(const QString &oldPath, const QString &newPath)
+void CppEditorDocument::onFilePathChanged(const Utils::FileName &oldPath,
+ const Utils::FileName &newPath)
{
Q_UNUSED(oldPath);
if (!newPath.isEmpty()) {
- setMimeType(Core::MimeDatabase::findByFile(QFileInfo(newPath)).type());
+ setMimeType(Core::MimeDatabase::findByFile(newPath.toFileInfo()).type());
disconnect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument()));
connect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument()));
// Un-Register/Register in ModelManager
- m_editorDocumentHandle.reset(new CppEditorDocumentHandle(this));
+ m_editorDocumentHandle.reset();
+ m_editorDocumentHandle.reset(new CppEditorDocumentHandleImpl(this));
resetProcessor();
updatePreprocessorSettings();
@@ -249,8 +251,8 @@ void CppEditorDocument::updatePreprocessorSettings()
const QString prefix = QLatin1String(Constants::CPP_PREPROCESSOR_PROJECT_PREFIX);
const QString &projectFile = ProjectExplorer::SessionManager::value(
- prefix + filePath()).toString();
- const QString directivesKey = projectFile + QLatin1Char(',') + filePath();
+ prefix + filePath().toString()).toString();
+ const QString directivesKey = projectFile + QLatin1Char(',') + filePath().toString();
const QByteArray additionalDirectives = ProjectExplorer::SessionManager::value(
directivesKey).toString().toUtf8();
diff --git a/src/plugins/cppeditor/cppeditordocument.h b/src/plugins/cppeditor/cppeditordocument.h
index fa91fbc3460..543ac8cda89 100644
--- a/src/plugins/cppeditor/cppeditordocument.h
+++ b/src/plugins/cppeditor/cppeditordocument.h
@@ -49,7 +49,7 @@ class CppEditorDocument : public TextEditor::TextDocument
{
Q_OBJECT
- friend class CppEditorDocumentHandle;
+ friend class CppEditorDocumentHandleImpl;
public:
explicit CppEditorDocument();
@@ -84,7 +84,7 @@ protected:
private slots:
void invalidateFormatterCache();
- void onFilePathChanged(const QString &oldPath, const QString &newPath);
+ void onFilePathChanged(const Utils::FileName &oldPath, const Utils::FileName &newPath);
void onMimeTypeChanged();
void onAboutToReload();
@@ -117,7 +117,7 @@ private:
CppTools::CppCompletionAssistProvider *m_completionAssistProvider;
// (Un)Registration in CppModelManager
- QScopedPointer<CppTools::EditorDocumentHandle> m_editorDocumentHandle;
+ QScopedPointer<CppTools::CppEditorDocumentHandle> m_editorDocumentHandle;
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp
index 91505322bdc..918b6ba76f8 100644
--- a/src/plugins/cppeditor/cppeditorplugin.cpp
+++ b/src/plugins/cppeditor/cppeditorplugin.cpp
@@ -35,7 +35,6 @@
#include "cppeditorconstants.h"
#include "cppeditor.h"
#include "cppeditordocument.h"
-#include "cppeditoroutline.h"
#include "cpphighlighter.h"
#include "cpphoverhandler.h"
#include "cppincludehierarchy.h"
@@ -45,6 +44,10 @@
#include "cppsnippetprovider.h"
#include "cpptypehierarchy.h"
+#ifdef WITH_TESTS
+# include "cppdoxygen_test.h"
+#endif
+
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
@@ -92,7 +95,7 @@ public:
setEditorWidgetCreator([]() { return new CppEditorWidget; });
setEditorCreator([]() { return new CppEditor; });
setAutoCompleterCreator([]() { return new CppAutoCompleter; });
- setCommentStyle(Utils::CommentDefinition::CppStyle);
+ setCommentStyle(CommentDefinition::CppStyle);
setCodeFoldingSupported(true);
setMarksVisible(true);
setParenthesesMatchingEnabled(true);
@@ -104,7 +107,7 @@ public:
addHoverHandler(new CppHoverHandler);
- if (!Utils::HostOsInfo::isMacHost() && !Utils::HostOsInfo::isWindowsHost()) {
+ if (!HostOsInfo::isMacHost() && !HostOsInfo::isWindowsHost()) {
FileIconProvider::registerIconOverlayForMimeType(
QIcon(creatorTheme()->imageFile(Theme::IconOverlayCppSource, QLatin1String(":/cppeditor/images/qt_cpp.png"))),
Constants::CPP_SOURCE_MIMETYPE);
@@ -123,7 +126,6 @@ public:
CppEditorPlugin *CppEditorPlugin::m_instance = 0;
CppEditorPlugin::CppEditorPlugin() :
- m_sortedOutline(true),
m_renameSymbolUnderCursorAction(0),
m_findUsagesAction(0),
m_reparseExternallyChangedFiles(0),
@@ -144,17 +146,6 @@ CppEditorPlugin *CppEditorPlugin::instance()
return m_instance;
}
-void CppEditorPlugin::setSortedOutline(bool sorted)
-{
- m_sortedOutline = sorted;
- emit outlineSortingChanged(sorted);
-}
-
-bool CppEditorPlugin::sortedOutline() const
-{
- return m_sortedOutline;
-}
-
CppQuickFixAssistProvider *CppEditorPlugin::quickFixProvider() const
{
return m_quickFixProvider;
@@ -162,7 +153,7 @@ CppQuickFixAssistProvider *CppEditorPlugin::quickFixProvider() const
bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage)
{
- if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/cppeditor/CppEditor.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/cppeditor/CppEditor.mimetypes.xml"), errorMessage))
return false;
addAutoReleasedObject(new CppEditorFactory);
@@ -212,7 +203,7 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
new QAction(tr("Open Function Declaration/Definition in Next Split"), this);
cmd = ActionManager::registerAction(openDeclarationDefinitionInNextSplit,
Constants::OPEN_DECLARATION_DEFINITION_IN_NEXT_SPLIT, context, true);
- cmd->setDefaultKeySequence(QKeySequence(Utils::HostOsInfo::isMacHost()
+ cmd->setDefaultKeySequence(QKeySequence(HostOsInfo::isMacHost()
? tr("Meta+E, Shift+F2")
: tr("Ctrl+E, Shift+F2")));
connect(openDeclarationDefinitionInNextSplit, SIGNAL(triggered()),
@@ -234,8 +225,8 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
cppToolsMenu->addAction(cmd);
m_openIncludeHierarchyAction = new QAction(tr("Open Include Hierarchy"), this);
- cmd = Core::ActionManager::registerAction(m_openIncludeHierarchyAction, Constants::OPEN_INCLUDE_HIERARCHY, context);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+Shift+I") : tr("Ctrl+Shift+I")));
+ cmd = ActionManager::registerAction(m_openIncludeHierarchyAction, Constants::OPEN_INCLUDE_HIERARCHY, context);
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+Shift+I") : tr("Ctrl+Shift+I")));
connect(m_openIncludeHierarchyAction, SIGNAL(triggered()), this, SLOT(openIncludeHierarchy()));
contextMenu->addAction(cmd);
cppToolsMenu->addAction(cmd);
@@ -267,7 +258,7 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
cppToolsMenu->addSeparator(globalContext);
QAction *inspectCppCodeModel = new QAction(tr("Inspect C++ Code Model..."), this);
cmd = ActionManager::registerAction(inspectCppCodeModel, Constants::INSPECT_CPP_CODEMODEL, globalContext);
- cmd->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+Shift+F12") : tr("Ctrl+Shift+F12")));
+ cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+Shift+F12") : tr("Ctrl+Shift+F12")));
connect(inspectCppCodeModel, SIGNAL(triggered()), this, SLOT(inspectCppCodeModel()));
cppToolsMenu->addAction(cmd);
@@ -284,27 +275,15 @@ bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *err
connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)),
this, SLOT(onAllTasksFinished(Core::Id)));
- readSettings();
return true;
}
-void CppEditorPlugin::readSettings()
-{
- m_sortedOutline = ICore::settings()->value(QLatin1String("CppTools/SortedMethodOverview"), true).toBool();
-}
-
-void CppEditorPlugin::writeSettings()
-{
- ICore::settings()->setValue(QLatin1String("CppTools/SortedMethodOverview"), m_sortedOutline);
-}
-
void CppEditorPlugin::extensionsInitialized()
{
}
ExtensionSystem::IPlugin::ShutdownFlag CppEditorPlugin::aboutToShutdown()
{
- writeSettings();
return SynchronousShutdown;
}
@@ -343,7 +322,7 @@ void CppEditorPlugin::showPreProcessorDialog()
editorWidget->showPreProcessorWidget();
}
-void CppEditorPlugin::onTaskStarted(Core::Id type)
+void CppEditorPlugin::onTaskStarted(Id type)
{
if (type == CppTools::Constants::TASK_INDEX) {
m_renameSymbolUnderCursorAction->setEnabled(false);
@@ -354,7 +333,7 @@ void CppEditorPlugin::onTaskStarted(Core::Id type)
}
}
-void CppEditorPlugin::onAllTasksFinished(Core::Id type)
+void CppEditorPlugin::onAllTasksFinished(Id type)
{
if (type == CppTools::Constants::TASK_INDEX) {
m_renameSymbolUnderCursorAction->setEnabled(true);
@@ -375,6 +354,15 @@ void CppEditorPlugin::inspectCppCodeModel()
}
}
+#ifdef WITH_TESTS
+QList<QObject *> CppEditorPlugin::createTestObjects() const
+{
+ return QList<QObject *>()
+ << new Tests::DoxygenTest
+ ;
+}
+#endif
+
void CppEditorPlugin::openTypeHierarchy()
{
if (currentCppEditorWidget()) {
@@ -387,8 +375,8 @@ void CppEditorPlugin::openTypeHierarchy()
void CppEditorPlugin::openIncludeHierarchy()
{
if (currentCppEditorWidget()) {
- Core::NavigationWidget *navigation = Core::NavigationWidget::instance();
- navigation->activateSubWidget(Core::Id(Constants::INCLUDE_HIERARCHY_ID));
+ NavigationWidget *navigation = NavigationWidget::instance();
+ navigation->activateSubWidget(Id(Constants::INCLUDE_HIERARCHY_ID));
emit includeHierarchyRequested();
}
}
diff --git a/src/plugins/cppeditor/cppeditorplugin.h b/src/plugins/cppeditor/cppeditorplugin.h
index e46fca9aeab..1c41e495dc4 100644
--- a/src/plugins/cppeditor/cppeditorplugin.h
+++ b/src/plugins/cppeditor/cppeditorplugin.h
@@ -63,8 +63,6 @@ public:
void extensionsInitialized();
ShutdownFlag aboutToShutdown();
- bool sortedOutline() const;
-
CppQuickFixAssistProvider *quickFixProvider() const;
signals:
@@ -81,14 +79,15 @@ public slots:
void renameSymbolUnderCursor();
void switchDeclarationDefinition();
- void setSortedOutline(bool sorted);
-
private slots:
void onTaskStarted(Core::Id type);
void onAllTasksFinished(Core::Id type);
void inspectCppCodeModel();
#ifdef WITH_TESTS
+private:
+ QList<QObject *> createTestObjects() const override;
+
private slots:
// The following tests expect that no projects are loaded on start-up.
void test_SwitchMethodDeclarationDefinition_data();
@@ -119,15 +118,14 @@ private slots:
void test_FollowSymbolUnderCursor_virtualFunctionCall();
void test_FollowSymbolUnderCursor_virtualFunctionCall_multipleDocuments();
- void test_doxygen_comments_data();
- void test_doxygen_comments();
- void test_doxygen_comments_no_leading_asterisks_data();
- void test_doxygen_comments_no_leading_asterisks();
-
void test_quickfix_data();
void test_quickfix();
void test_quickfix_GenerateGetterSetter_basicGetterWithPrefixAndNamespaceToCpp();
+ void test_quickfix_GenerateGetterSetter_onlyGetter();
+ void test_quickfix_GenerateGetterSetter_onlySetter();
+ void test_quickfix_GenerateGetterSetter_offerGetterWhenSetterPresent();
+ void test_quickfix_GenerateGetterSetter_offerSetterWhenGetterPresent();
void test_quickfix_ConvertQt4Connect_connectOutOfClass();
void test_quickfix_ConvertQt4Connect_connectWithinClass_data();
@@ -154,34 +152,8 @@ private slots:
void test_quickfix_InsertDeclFromDef();
- void test_quickfix_AddIncludeForUndefinedIdentifier_onSimpleName();
- void test_quickfix_AddIncludeForUndefinedIdentifier_onNameOfQualifiedName();
- void test_quickfix_AddIncludeForUndefinedIdentifier_onBaseOfQualifiedName();
- void test_quickfix_AddIncludeForUndefinedIdentifier_onTemplateName();
- void test_quickfix_AddIncludeForUndefinedIdentifier_onTemplateNameInsideArguments();
- void test_quickfix_AddIncludeForUndefinedIdentifier_withForwardDeclaration();
- void test_quickfix_AddIncludeForUndefinedIdentifier_withForwardDeclaration2();
- void test_quickfix_AddIncludeForUndefinedIdentifier_withForwardHeader();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_ignoremoc();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_sortingTop();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_sortingMiddle();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_sortingBottom();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_appendToUnsorted();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_firstLocalIncludeAtFront();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_firstGlobalIncludeAtBack();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_preferGroupWithLongerMatchingPrefix();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_newGroupIfOnlyDifferentIncludeDirs();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedDirsSorted();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedDirsUnsorted();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes1();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes2();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes3();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes4();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_noinclude();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_onlyIncludeGuard();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_veryFirstIncludeCppStyleCommentOnTop();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_veryFirstIncludeCStyleCommentOnTop();
- void test_quickfix_AddIncludeForUndefinedIdentifier_inserting_checkQSomethingInQtIncludePaths();
+ void test_quickfix_AddIncludeForUndefinedIdentifier_data();
+ void test_quickfix_AddIncludeForUndefinedIdentifier();
void test_quickfix_AddIncludeForUndefinedIdentifier_noDoubleQtHeaderInclude();
void test_quickfix_MoveFuncDefOutside_MemberFuncToCpp();
@@ -200,6 +172,12 @@ private slots:
void test_quickfix_MoveFuncDefOutside_respectWsInOperatorNames2();
void test_quickfix_MoveFuncDefOutside_macroUses();
+ void test_quickfix_MoveAllFuncDefOutside_MemberFuncToCpp();
+ void test_quickfix_MoveAllFuncDefOutside_MemberFuncOutside();
+ void test_quickfix_MoveAllFuncDefOutside_DoNotTriggerOnBaseClass();
+ void test_quickfix_MoveAllFuncDefOutside_classWithBaseClass();
+ void test_quickfix_MoveAllFuncDefOutside_ignoreMacroCode();
+
void test_quickfix_MoveFuncDefToDecl_MemberFunc();
void test_quickfix_MoveFuncDefToDecl_MemberFuncOutside();
void test_quickfix_MoveFuncDefToDecl_MemberFuncToCppNS();
@@ -210,6 +188,7 @@ private slots:
void test_quickfix_MoveFuncDefToDecl_CtorWithInitialization();
void test_quickfix_MoveFuncDefToDecl_structWithAssignedVariable();
void test_quickfix_MoveFuncDefToDecl_macroUses();
+ void test_quickfix_MoveFuncDefToDecl_override();
void test_quickfix_AssignToLocalVariable_templates();
@@ -247,12 +226,9 @@ private slots:
private:
Core::IEditor *createEditor(QWidget *parent);
- void writeSettings();
- void readSettings();
static CppEditorPlugin *m_instance;
- bool m_sortedOutline;
QAction *m_renameSymbolUnderCursorAction;
QAction *m_findUsagesAction;
QAction *m_reparseExternallyChangedFiles;
diff --git a/src/plugins/cppeditor/cppelementevaluator.cpp b/src/plugins/cppeditor/cppelementevaluator.cpp
index 22242852bb7..d2e3544cbcf 100644
--- a/src/plugins/cppeditor/cppelementevaluator.cpp
+++ b/src/plugins/cppeditor/cppelementevaluator.cpp
@@ -30,8 +30,6 @@
#include "cppelementevaluator.h"
-#include "cppeditor.h"
-
#include <cpptools/cpptoolsreuse.h>
#include <cpptools/typehierarchybuilder.h>
@@ -40,7 +38,6 @@
#include <cplusplus/TypeOfExpression.h>
#include <QDir>
-#include <QFileInfo>
#include <QSet>
#include <QQueue>
@@ -131,7 +128,7 @@ void CppElementEvaluator::checkDiagnosticMessage(int pos)
}
}
-bool CppElementEvaluator::matchIncludeFile(const CPlusPlus::Document::Ptr &document, unsigned line)
+bool CppElementEvaluator::matchIncludeFile(const Document::Ptr &document, unsigned line)
{
foreach (const Document::Include &includeFile, document->resolvedIncludes()) {
if (includeFile.line() == line) {
@@ -142,7 +139,7 @@ bool CppElementEvaluator::matchIncludeFile(const CPlusPlus::Document::Ptr &docum
return false;
}
-bool CppElementEvaluator::matchMacroInUse(const CPlusPlus::Document::Ptr &document, unsigned pos)
+bool CppElementEvaluator::matchMacroInUse(const Document::Ptr &document, unsigned pos)
{
foreach (const Document::MacroUse &use, document->macroUses()) {
if (use.containsUtf16charOffset(pos)) {
@@ -260,7 +257,7 @@ Unknown::Unknown(const QString &type) : type(type)
CppInclude::CppInclude(const Document::Include &includeFile) :
path(QDir::toNativeSeparators(includeFile.resolvedFileName())),
- fileName(QFileInfo(includeFile.resolvedFileName()).fileName())
+ fileName(Utils::FileName::fromString(includeFile.resolvedFileName()).fileName())
{
helpCategory = TextEditor::HelpItem::Brief;
helpIdCandidates = QStringList(fileName);
@@ -302,7 +299,7 @@ CppDeclarableElement::CppDeclarableElement(Symbol *declaration)
}
tooltip = overview.prettyType(declaration->type(), qualifiedName);
- link = CppEditorWidget::linkToSymbol(declaration);
+ link = CppTools::linkToSymbol(declaration);
helpMark = name;
}
@@ -325,7 +322,7 @@ bool CppClass::operator==(const CppClass &other)
return this->declaration == other.declaration;
}
-void CppClass::lookupBases(Symbol *declaration, const CPlusPlus::LookupContext &context)
+void CppClass::lookupBases(Symbol *declaration, const LookupContext &context)
{
typedef QPair<ClassOrNamespace *, CppClass *> Data;
@@ -356,7 +353,7 @@ void CppClass::lookupBases(Symbol *declaration, const CPlusPlus::LookupContext &
}
}
-void CppClass::lookupDerived(CPlusPlus::Symbol *declaration, const CPlusPlus::Snapshot &snapshot)
+void CppClass::lookupDerived(Symbol *declaration, const Snapshot &snapshot)
{
typedef QPair<CppClass *, CppTools::TypeHierarchy> Data;
@@ -449,14 +446,14 @@ CppVariable::CppVariable(Symbol *declaration, const LookupContext &context, Scop
}
}
-CppEnumerator::CppEnumerator(CPlusPlus::EnumeratorDeclaration *declaration)
+CppEnumerator::CppEnumerator(EnumeratorDeclaration *declaration)
: CppDeclarableElement(declaration)
{
helpCategory = TextEditor::HelpItem::Enum;
Overview overview;
- Symbol *enumSymbol = declaration->enclosingScope()->asEnum();
+ Symbol *enumSymbol = declaration->enclosingScope();
const QString enumName = overview.prettyName(LookupContext::fullyQualifiedName(enumSymbol));
const QString enumeratorName = overview.prettyName(declaration->name());
QString enumeratorValue;
diff --git a/src/plugins/cppeditor/cppfollowsymbolundercursor.cpp b/src/plugins/cppeditor/cppfollowsymbolundercursor.cpp
index e1235a2f94f..b9fa4460e8f 100644
--- a/src/plugins/cppeditor/cppfollowsymbolundercursor.cpp
+++ b/src/plugins/cppeditor/cppfollowsymbolundercursor.cpp
@@ -308,7 +308,7 @@ inline LookupItem skipForwardDeclarations(const QList<LookupItem> &resolvedSymbo
}
CppEditorWidget::Link attemptFuncDeclDef(const QTextCursor &cursor,
- CppEditorWidget *, CPlusPlus::Snapshot snapshot, const CPlusPlus::Document::Ptr &document,
+ CppEditorWidget *, Snapshot snapshot, const Document::Ptr &document,
SymbolFinder *symbolFinder)
{
Link result;
@@ -366,7 +366,7 @@ CppEditorWidget::Link attemptFuncDeclDef(const QTextCursor &cursor,
}
if (target) {
- result = CppEditorWidget::linkToSymbol(target);
+ result = CppTools::linkToSymbol(target);
unsigned startLine, startColumn, endLine, endColumn;
document->translationUnit()->getTokenStartPosition(name->firstToken(), &startLine,
@@ -624,7 +624,7 @@ TextEditorWidget::Link FollowSymbolUnderCursor::findLink(const QTextCursor &curs
continue;
if (ch == QLatin1Char('(') && !expression.isEmpty()) {
tc.setPosition(pos);
- if (TextEditor::TextBlockUserData::findNextClosingParenthesis(&tc, true))
+ if (TextBlockUserData::findNextClosingParenthesis(&tc, true))
expression.append(tc.selectedText());
}
@@ -645,7 +645,7 @@ TextEditorWidget::Link FollowSymbolUnderCursor::findLink(const QTextCursor &curs
if (Symbol *d = r.declaration()) {
if (d->isDeclaration() || d->isFunction()) {
const QString fileName = QString::fromUtf8(d->fileName(), d->fileNameLength());
- if (m_widget->textDocument()->filePath() == fileName) {
+ if (m_widget->textDocument()->filePath().toString() == fileName) {
if (unsigned(lineNumber) == d->line()
&& unsigned(positionInBlock) >= d->column()) { // TODO: check the end
result = r; // take the symbol under cursor.
@@ -684,8 +684,7 @@ TextEditorWidget::Link FollowSymbolUnderCursor::findLink(const QTextCursor &curs
params.openInNextSplit = inNextSplit;
if (m_virtualFunctionAssistProvider->configure(params)) {
- m_widget->invokeAssist(TextEditor::FollowSymbol,
- m_virtualFunctionAssistProvider);
+ m_widget->invokeAssist(FollowSymbol, m_virtualFunctionAssistProvider);
m_virtualFunctionAssistProvider->clearParams();
}
@@ -714,7 +713,7 @@ TextEditorWidget::Link FollowSymbolUnderCursor::findLink(const QTextCursor &curs
}
- link = m_widget->linkToSymbol(def ? def : symbol);
+ link = CppTools::linkToSymbol(def ? def : symbol);
link.linkTextStart = beginOfToken;
link.linkTextEnd = endOfToken;
return link;
diff --git a/src/plugins/cppeditor/cppfunctiondecldeflink.cpp b/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
index c65f5a4d5a0..46bf00bc83c 100644
--- a/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
+++ b/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
@@ -46,7 +46,6 @@
#include <utils/proxyaction.h>
#include <utils/qtcassert.h>
-#include <utils/tooltip/tipcontents.h>
#include <utils/tooltip/tooltip.h>
#include <QtConcurrentRun>
@@ -310,7 +309,7 @@ void FunctionDeclDefLink::apply(CppEditorWidget *editor, bool jumpToMatch)
newTargetFile->apply();
} else {
ToolTip::show(editor->toolTipPosition(linkSelection),
- TextContent(tr("Target file was changed, could not apply changes")));
+ tr("Target file was changed, could not apply changes"));
}
}
diff --git a/src/plugins/cppeditor/cpphighlighter.cpp b/src/plugins/cppeditor/cpphighlighter.cpp
index 1001c1d838c..7370b88ef0c 100644
--- a/src/plugins/cppeditor/cpphighlighter.cpp
+++ b/src/plugins/cppeditor/cpphighlighter.cpp
@@ -45,22 +45,22 @@ using namespace TextEditor;
using namespace CPlusPlus;
CppHighlighter::CppHighlighter(QTextDocument *document) :
- TextEditor::SyntaxHighlighter(document)
+ SyntaxHighlighter(document)
{
- static QVector<TextEditor::TextStyle> categories;
+ static QVector<TextStyle> categories;
if (categories.isEmpty()) {
- categories << TextEditor::C_NUMBER
- << TextEditor::C_STRING
- << TextEditor::C_TYPE
- << TextEditor::C_KEYWORD
- << TextEditor::C_PRIMITIVE_TYPE
- << TextEditor::C_OPERATOR
- << TextEditor::C_PREPROCESSOR
- << TextEditor::C_LABEL
- << TextEditor::C_COMMENT
- << TextEditor::C_DOXYGEN_COMMENT
- << TextEditor::C_DOXYGEN_TAG
- << TextEditor::C_VISUAL_WHITESPACE;
+ categories << C_NUMBER
+ << C_STRING
+ << C_TYPE
+ << C_KEYWORD
+ << C_PRIMITIVE_TYPE
+ << C_OPERATOR
+ << C_PREPROCESSOR
+ << C_LABEL
+ << C_COMMENT
+ << C_DOXYGEN_COMMENT
+ << C_DOXYGEN_TAG
+ << C_VISUAL_WHITESPACE;
}
setTextFormatCategories(categories);
}
diff --git a/src/plugins/cppeditor/cppincludehierarchy.cpp b/src/plugins/cppeditor/cppincludehierarchy.cpp
index a339c561a00..f8dda2004c8 100644
--- a/src/plugins/cppeditor/cppincludehierarchy.cpp
+++ b/src/plugins/cppeditor/cppincludehierarchy.cpp
@@ -118,12 +118,12 @@ void CppIncludeHierarchyWidget::perform()
return;
m_model->clear();
- m_model->buildHierarchy(m_editor, widget->textDocument()->filePath());
+ m_model->buildHierarchy(m_editor, widget->textDocument()->filePath().toString());
if (m_model->isEmpty())
return;
m_inspectedFile->setText(widget->textDocument()->displayName());
- m_inspectedFile->setLink(TextEditorWidget::Link(widget->textDocument()->filePath()));
+ m_inspectedFile->setLink(TextEditorWidget::Link(widget->textDocument()->filePath().toString()));
//expand "Includes"
m_treeView->expand(m_model->index(0, 0));
diff --git a/src/plugins/cppeditor/cppincludehierarchy_test.cpp b/src/plugins/cppeditor/cppincludehierarchy_test.cpp
index a6d0ce5eb84..c5dc01e32b5 100644
--- a/src/plugins/cppeditor/cppincludehierarchy_test.cpp
+++ b/src/plugins/cppeditor/cppincludehierarchy_test.cpp
@@ -82,22 +82,24 @@ public:
QSet<QString> filePaths;
const int sourceListSize = sourceList.size();
+
+ CppTools::Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
for (int i = 0; i < sourceListSize; ++i) {
const QByteArray &source = sourceList.at(i);
// Write source to file
- const QString fileName = QString::fromLatin1("%1/file%2.h").arg(QDir::tempPath())
- .arg(i+1);
- QVERIFY(writeFile(fileName, source));
-
- filePaths << fileName;
+ const QString fileName = QString::fromLatin1("file%1.h").arg(i+1);
+ const QString absoluteFilePath = temporaryDir.createFile(fileName.toLatin1(), source);
+ filePaths << absoluteFilePath;
}
// Update Code Model
QVERIFY(parseFiles(filePaths));
// Open Editor
- const QString fileName = QDir::tempPath() + QLatin1String("/file1.h");
+ const QString fileName = temporaryDir.path() + QLatin1String("/file1.h");
CppEditor *editor;
QVERIFY(openCppEditor(fileName, &editor));
closeEditorAtEndOfTestCase(editor);
diff --git a/src/plugins/cppeditor/cppincludehierarchymodel.cpp b/src/plugins/cppeditor/cppincludehierarchymodel.cpp
index ad79234fa72..a55c60ed228 100644
--- a/src/plugins/cppeditor/cppincludehierarchymodel.cpp
+++ b/src/plugins/cppeditor/cppincludehierarchymodel.cpp
@@ -51,7 +51,7 @@ namespace {
Snapshot globalSnapshot()
{
- return CppTools::CppModelManager::instance()->snapshot();
+ return CppModelManager::instance()->snapshot();
}
} // anonymous namespace
@@ -174,7 +174,7 @@ void CppIncludeHierarchyModel::fetchMore(const QModelIndex &parent)
return;
if (parentItem->needChildrenPopulate()) {
- const QString editorFilePath = m_editor->document()->filePath();
+ const QString editorFilePath = m_editor->document()->filePath().toString();
QSet<QString> cyclic;
cyclic << editorFilePath;
CppIncludeHierarchyItem *item = parentItem->parent();
@@ -285,7 +285,7 @@ void CppIncludeHierarchyModel::buildHierarchyIncludes(const QString &currentFile
if (!m_editor)
return;
- const QString editorFilePath = m_editor->document()->filePath();
+ const QString editorFilePath = m_editor->document()->filePath().toString();
auto *documentProcessor = BaseEditorDocumentProcessor::get(editorFilePath);
QTC_ASSERT(documentProcessor, return);
const Snapshot editorDocumentSnapshot = documentProcessor->snapshot();
@@ -341,7 +341,7 @@ void CppIncludeHierarchyModel::buildHierarchyIncludedBy_helper(const QString &fi
cyclic->insert(filePath);
Snapshot::const_iterator citEnd = snapshot.end();
for (Snapshot::const_iterator cit = snapshot.begin(); cit != citEnd; ++cit) {
- const QString filePathFromSnapshot = cit.key();
+ const QString filePathFromSnapshot = cit.key().toString();
Document::Ptr doc = cit.value();
foreach (const Document::Include &includeFile, doc->resolvedIncludes()) {
const QString includedFilePath = includeFile.resolvedFileName();
diff --git a/src/plugins/cppeditor/cppinsertvirtualmethods.cpp b/src/plugins/cppeditor/cppinsertvirtualmethods.cpp
index f1293f26633..1564bc0da21 100644
--- a/src/plugins/cppeditor/cppinsertvirtualmethods.cpp
+++ b/src/plugins/cppeditor/cppinsertvirtualmethods.cpp
@@ -278,7 +278,7 @@ class InsertVirtualMethodsModel : public QAbstractItemModel
public:
InsertVirtualMethodsModel(QObject *parent = 0) : QAbstractItemModel(parent)
{
- const TextEditor::FontSettings &fs = TextEditor::TextEditorSettings::fontSettings();
+ const FontSettings &fs = TextEditorSettings::fontSettings();
formatReimpFunc = fs.formatFor(C_DISABLED_CODE);
}
@@ -509,7 +509,7 @@ public:
QHash<const Function *, FunctionItem *> virtualFunctions;
foreach (const Class *clazz, baseClasses) {
ClassItem *itemBase = new ClassItem(printer.prettyName(clazz->name()), clazz);
- for (Scope::iterator it = clazz->firstMember(); it != clazz->lastMember(); ++it) {
+ for (Scope::iterator it = clazz->memberBegin(); it != clazz->memberEnd(); ++it) {
if (const Function *func = (*it)->type()->asFunctionType()) {
// Filter virtual destructors
if (func->name()->asDestructorNameId())
@@ -735,7 +735,7 @@ public:
const QString accessSpecString =
InsertionPointLocator::accessSpecToString(funcItem->accessSpec);
if (accessSpecString != lastAccessSpecString) {
- declaration = accessSpecString + declaration;
+ declaration = accessSpecString + QLatin1String(":\n") + declaration;
if (!lastAccessSpecString.isEmpty()) // separate if not direct after the comment
declaration = QLatin1String("\n") + declaration;
lastAccessSpecString = accessSpecString;
@@ -1406,16 +1406,7 @@ void CppEditorPlugin::test_quickfix_InsertVirtualMethods_data()
"public:\n"
" virtual int virtualFuncA() = 0;\n"
"};\n"
- ) << _(
- "class BaseA {\n"
- "public:\n"
- " virtual int virtualFuncA();\n"
- "};\n\n"
- "class Derived : public Bas@eA {\n"
- "public:\n"
- " virtual int virtualFuncA() = 0;\n"
- "};\n"
- );
+ ) << _();
// Check: One pure, one not
QTest::newRow("Some_Pure")
diff --git a/src/plugins/cppeditor/cppoutline.cpp b/src/plugins/cppeditor/cppoutline.cpp
index f3a87e3abfa..b088b816ba4 100644
--- a/src/plugins/cppeditor/cppoutline.cpp
+++ b/src/plugins/cppeditor/cppoutline.cpp
@@ -30,7 +30,7 @@
#include "cppoutline.h"
-#include "cppeditoroutline.h"
+#include <cpptools/cppeditoroutline.h>
#include <cplusplus/OverviewModel.h>
diff --git a/src/plugins/cppeditor/cpppreprocessordialog.cpp b/src/plugins/cppeditor/cpppreprocessordialog.cpp
index b7e9ec81cd5..2b9210f04b3 100644
--- a/src/plugins/cppeditor/cpppreprocessordialog.cpp
+++ b/src/plugins/cppeditor/cpppreprocessordialog.cpp
@@ -53,7 +53,7 @@ CppPreProcessorDialog::CppPreProcessorDialog(QWidget *parent, const QString &fil
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
m_ui->setupUi(this);
- m_ui->editorLabel->setText(m_ui->editorLabel->text().arg(QFileInfo(m_filePath).fileName()));
+ m_ui->editorLabel->setText(m_ui->editorLabel->text().arg(Utils::FileName::fromString(m_filePath).fileName()));
m_ui->editWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
CppSnippetProvider().decorateEditor(m_ui->editWidget);
diff --git a/src/plugins/cppeditor/cppquickfix_test.cpp b/src/plugins/cppeditor/cppquickfix_test.cpp
index 14d1eca4e28..a3be1d7816d 100644
--- a/src/plugins/cppeditor/cppquickfix_test.cpp
+++ b/src/plugins/cppeditor/cppquickfix_test.cpp
@@ -107,8 +107,13 @@ BaseQuickFixTestCase::BaseQuickFixTestCase(const QList<QuickFixTestDocument::Ptr
QVERIFY2(cursorMarkersCount == 1, "Exactly one cursor marker is allowed.");
// Write documents to disk
- foreach (QuickFixTestDocument::Ptr document, m_testDocuments)
+ m_temporaryDirectory.reset(new CppTools::Tests::TemporaryDir);
+ QVERIFY(m_temporaryDirectory->isValid());
+ foreach (QuickFixTestDocument::Ptr document, m_testDocuments) {
+ if (QFileInfo(document->m_fileName).isRelative())
+ document->setBaseDirectory(m_temporaryDirectory->path());
document->writeToDisk();
+ }
// Set appropriate include paths
if (!headerPaths.isEmpty()) {
@@ -207,10 +212,10 @@ QuickFixOperationTest::QuickFixOperationTest(const QList<QuickFixTestDocument::P
// Perform operation if there is one
CppQuickFixInterface quickFixInterface(m_documentWithMarker->m_editorWidget, ExplicitlyInvoked);
- TextEditor::QuickFixOperations operations;
+ QuickFixOperations operations;
factory->match(quickFixInterface, operations);
if (operations.isEmpty()) {
- qDebug() << "Quickfix was not triggered";
+ QVERIFY(testDocuments.first()->m_expectedSource.isEmpty());
return;
}
@@ -219,19 +224,19 @@ QuickFixOperationTest::QuickFixOperationTest(const QList<QuickFixTestDocument::P
operation->perform();
// Compare all files
- foreach (const QuickFixTestDocument::Ptr testFile, m_testDocuments) {
+ foreach (const QuickFixTestDocument::Ptr testDocument, m_testDocuments) {
// Check
- QString result = testFile->m_editorWidget->document()->toPlainText();
+ QString result = testDocument->m_editorWidget->document()->toPlainText();
removeTrailingWhitespace(result);
if (!expectedFailMessage.isEmpty())
QEXPECT_FAIL("", expectedFailMessage.data(), Continue);
- QCOMPARE(result, testFile->m_expectedSource);
+ QCOMPARE(result, testDocument->m_expectedSource);
// Undo the change
for (int i = 0; i < 100; ++i)
- testFile->m_editorWidget->undo();
- result = testFile->m_editorWidget->document()->toPlainText();
- QCOMPARE(result, testFile->m_source);
+ testDocument->m_editorWidget->undo();
+ result = testDocument->m_editorWidget->document()->toPlainText();
+ QCOMPARE(result, testDocument->m_source);
}
}
@@ -254,7 +259,7 @@ QuickFixOfferedOperationsTest::QuickFixOfferedOperationsTest(
{
// Get operations
CppQuickFixInterface quickFixInterface(m_documentWithMarker->m_editorWidget, ExplicitlyInvoked);
- TextEditor::QuickFixOperations actualOperations;
+ QuickFixOperations actualOperations;
factory->match(quickFixInterface, actualOperations);
// Convert to QStringList
@@ -800,13 +805,26 @@ void CppEditorPlugin::test_quickfix_data()
<< CppQuickFixFactoryPtr(new GenerateGetterSetter)
<< _("class Something { void @a[10]; };\n") << _();
- // Check: Do not offer the quick fix if there is already a member with the
- // getter or setter name we would generate.
- QTest::newRow("GenerateGetterSetter_notTriggeringWhenGetterOrSetterExist")
+ // Check: Do not offer the quick fix if there is a getter and the variable is const
+ QTest::newRow("GenerateGetterSetter_notTriggeringWhenGetterAndConstVariable")
+ << CppQuickFixFactoryPtr(new GenerateGetterSetter) << _(
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " const int bar@;\n"
+ " int getBar() const;\n"
+ "};\n"
+ ) << _();
+
+ // Check: Do not offer the quick fix if there is a getter and a setter
+ QTest::newRow("GenerateGetterSetter_notTriggeringWhenGetterAndConstVariable")
<< CppQuickFixFactoryPtr(new GenerateGetterSetter) << _(
- "class Something {\n"
- " int @it;\n"
- " void setIt();\n"
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " const int bar@;\n"
+ " int getBar() const;\n"
+ " void setBar(int value);\n"
"};\n"
) << _();
@@ -1045,6 +1063,42 @@ void CppEditorPlugin::test_quickfix_data()
"}\n"
);
+ // Check: Add local variable for a member function, cursor in the middle (QTCREATORBUG-10355)
+ QTest::newRow("AssignToLocalVariable_memberFunction2ndGrade1")
+ << CppQuickFixFactoryPtr(new AssignToLocalVariable) << _(
+ "struct Foo {int* func();};\n"
+ "struct Baz {Foo* foo();};\n"
+ "void bar() {\n"
+ " Baz *b = new Baz;\n"
+ " b->foo@()->func();\n"
+ "}"
+ ) << _(
+ "struct Foo {int* func();};\n"
+ "struct Baz {Foo* foo();};\n"
+ "void bar() {\n"
+ " Baz *b = new Baz;\n"
+ " int *localFunc = b->foo()->func();\n"
+ "}"
+ );
+
+ // Check: Add local variable for a member function, cursor on function call (QTCREATORBUG-10355)
+ QTest::newRow("AssignToLocalVariable_memberFunction2ndGrade2")
+ << CppQuickFixFactoryPtr(new AssignToLocalVariable) << _(
+ "struct Foo {int* func();};\n"
+ "struct Baz {Foo* foo();};\n"
+ "void bar() {\n"
+ " Baz *b = new Baz;\n"
+ " b->foo()->f@unc();\n"
+ "}"
+ ) << _(
+ "struct Foo {int* func();};\n"
+ "struct Baz {Foo* foo();};\n"
+ "void bar() {\n"
+ " Baz *b = new Baz;\n"
+ " int *localFunc = b->foo()->func();\n"
+ "}"
+ );
+
// Check: Add local variable for a static member function.
QTest::newRow("AssignToLocalVariable_staticMemberFunction")
<< CppQuickFixFactoryPtr(new AssignToLocalVariable) << _(
@@ -1255,7 +1309,7 @@ void CppEditorPlugin::test_quickfix_data()
QTest::newRow("OptimizeForLoop_wrongInitializer")
<< CppQuickFixFactoryPtr(new OptimizeForLoop)
<< _("int i; void foo() {f@or (double a = 0; i < 3 + 5; ++i) {}}\n")
- << _("int i; void foo() {f@or (double a = 0; i < 3 + 5; ++i) {}}\n");
+ << _();
// Check: No trigger when numeric
QTest::newRow("OptimizeForLoop_noTriggerNumeric1")
@@ -1285,17 +1339,17 @@ void CppEditorPlugin::test_quickfix_data()
" }\n"
"\n"
"public slots:\n"
- " void setIt(int arg)\n"
+ " void setIt(int it)\n"
" {\n"
- " if (m_it == arg)\n"
+ " if (m_it == it)\n"
" return;\n"
"\n"
- " m_it = arg;\n"
- " emit itChanged(arg);\n"
+ " m_it = it;\n"
+ " emit itChanged(it);\n"
" }\n"
"\n"
"signals:\n"
- " void itChanged(int arg);\n"
+ " void itChanged(int it);\n"
"\n"
"private:\n"
" int m_it;\n"
@@ -1560,8 +1614,6 @@ void CppEditorPlugin::test_quickfix()
QFETCH(QByteArray, original);
QFETCH(QByteArray, expected);
- if (expected.isEmpty())
- expected = original;
QuickFixOperationTest(singleDocument(original, expected), factory.data());
}
@@ -1569,7 +1621,7 @@ void CppEditorPlugin::test_quickfix()
/// generated definitions should fit in the namespace.
void CppEditorPlugin::test_quickfix_GenerateGetterSetter_basicGetterWithPrefixAndNamespaceToCpp()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1592,7 +1644,7 @@ void CppEditorPlugin::test_quickfix_GenerateGetterSetter_basicGetterWithPrefixAn
" void setIt(int value);\n"
"};\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -1612,16 +1664,168 @@ void CppEditorPlugin::test_quickfix_GenerateGetterSetter_basicGetterWithPrefixAn
" it = value;\n"
"}\n\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+
+ GenerateGetterSetter factory;
+ QuickFixOperationTest(testDocuments, &factory);
+}
+
+/// Checks: Only generate getter
+void CppEditorPlugin::test_quickfix_GenerateGetterSetter_onlyGetter()
+{
+ QList<QuickFixTestDocument::Ptr> testDocuments;
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar@;\n"
+ "};\n";
+ expected =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar@;\n"
+ " int getBar() const;\n"
+ "};\n";
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
+
+ // Source File
+ original.resize(0);
+ expected =
+ "\n"
+ "int Foo::getBar() const\n"
+ "{\n"
+ " return bar;\n"
+ "}\n";
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+
+ GenerateGetterSetter factory;
+ QuickFixOperationTest(testDocuments, &factory, ProjectPart::HeaderPaths(), 1);
+}
+
+/// Checks: Only generate setter
+void CppEditorPlugin::test_quickfix_GenerateGetterSetter_onlySetter()
+{
+ QList<QuickFixTestDocument::Ptr> testDocuments;
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar@;\n"
+ "};\n";
+ expected =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar@;\n"
+ " void setBar(int value);\n"
+ "};\n";
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
+
+ // Source File
+ original.resize(0);
+ expected =
+ "\n"
+ "void Foo::setBar(int value)\n"
+ "{\n"
+ " bar = value;\n"
+ "}\n";
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+
+ GenerateGetterSetter factory;
+ QuickFixOperationTest(testDocuments, &factory, ProjectPart::HeaderPaths(), 2);
+}
+
+/// Checks: Offer a "generate getter" quick fix if there is a setter
+void CppEditorPlugin::test_quickfix_GenerateGetterSetter_offerGetterWhenSetterPresent()
+{
+ QList<QuickFixTestDocument::Ptr> testDocuments;
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar@;\n"
+ " void setBar(int value);\n"
+ "};\n";
+ expected =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar;\n"
+ " void setBar(int value);\n"
+ " int getBar() const;\n"
+ "};\n";
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
+
+ // Source File
+ original.resize(0);
+ expected =
+ "\n"
+ "int Foo::getBar() const\n"
+ "{\n"
+ " return bar;\n"
+ "}\n";
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
GenerateGetterSetter factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
+}
+
+/// Checks: Offer a "generate setter" quick fix if there is a getter
+void CppEditorPlugin::test_quickfix_GenerateGetterSetter_offerSetterWhenGetterPresent()
+{
+ QList<QuickFixTestDocument::Ptr> testDocuments;
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar@;\n"
+ " int getBar() const;\n"
+ "};\n";
+ expected =
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " int bar;\n"
+ " int getBar() const;\n"
+ " void setBar(int value);\n"
+ "};\n";
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
+
+ // Source File
+ original.resize(0);
+ expected =
+ "\n"
+ "void Foo::setBar(int value)\n"
+ "{\n"
+ " bar = value;\n"
+ "}\n";
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+
+ GenerateGetterSetter factory;
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check if definition is inserted right after class for insert definition outside
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_afterClass()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1645,7 +1849,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_afterClass()
"{\n\n}\n"
"\n"
"class Bar {};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -1655,17 +1859,17 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_afterClass()
"{\n\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory, ProjectPart::HeaderPaths(), 1);
+ QuickFixOperationTest(testDocuments, &factory, ProjectPart::HeaderPaths(), 1);
}
/// 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<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1677,7 +1881,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic1()
" Foo()@;\n"
"};\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original.resize(0);
@@ -1687,17 +1891,17 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic1()
"{\n\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// 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<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1705,7 +1909,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic2()
// Header File
original = "void f()@;\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -1724,22 +1928,22 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic2()
"\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check from source file: Insert in source file, not header file.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic3()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
// Empty Header File
- testFiles << QuickFixTestDocument::create("file.h", "", "");
+ testDocuments << QuickFixTestDocument::create("file.h", "", "");
// Source File
original =
@@ -1754,17 +1958,17 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_basic3()
"{\n\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check from header file: If the class is in a namespace, the added function definition
/// name must be qualified accordingly.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_namespace1()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1778,7 +1982,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_namespace1()
"};\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original.resize(0);
@@ -1788,17 +1992,17 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_namespace1()
"{\n\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check from header file: If the class is in namespace N and the source file has a
/// "using namespace N" line, the function definition name must be qualified accordingly.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_namespace2()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1812,7 +2016,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_namespace2()
"};\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -1826,10 +2030,10 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_headerSource_namespace2()
"{\n\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check definition insert inside class
@@ -1859,17 +2063,15 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_notTriggeringWhenDefinitio
" void b@ar();\n"
"};\n"
"void Foo::bar() {}\n";
- const QByteArray expected = original;
InsertDefFromDecl factory;
- QuickFixOperationTest(singleDocument(original, expected), &factory, ProjectPart::HeaderPaths(),
- 1);
+ QuickFixOperationTest(singleDocument(original, ""), &factory, ProjectPart::HeaderPaths(), 1);
}
/// Find right implementation file.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_findRightImplementationFile()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1884,7 +2086,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_findRightImplementationFil
"};\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File #1
original =
@@ -1894,7 +2096,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_findRightImplementationFil
"{\n\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
// Source File #2
@@ -1909,17 +2111,17 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_findRightImplementationFil
"void Foo::b()\n"
"{\n\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file2.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file2.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Ignore generated functions declarations when looking at the surrounding
/// functions declarations in order to find the right implementation file.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_ignoreSurroundingGeneratedDeclarations()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -1935,7 +2137,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_ignoreSurroundingGenerated
"};\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File #1
original =
@@ -1954,7 +2156,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_ignoreSurroundingGenerated
"void Foo::b()\n"
"{\n\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
// Source File #2
original =
@@ -1964,10 +2166,10 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_ignoreSurroundingGenerated
"{\n\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file2.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file2.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check if whitespace is respected for operator functions
@@ -2022,7 +2224,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_respectWsInOperatorNames2(
/// Case: Macro preceded by preproceesor directives and declaration.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile1()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -2030,7 +2232,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile1()
// Header File
original = "void f()@;\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -2054,17 +2256,17 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile1()
"\n"
"MACRO(int)\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &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<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -2072,7 +2274,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile2()
// Header File
original = "void f()@;\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -2094,16 +2296,16 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_macroUsesAtEndOfFile2()
"\n"
"MACRO(int)\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check if insertion happens before syntactically erroneous statements at end of file.
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_erroneousStatementAtEndOfFile()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -2111,7 +2313,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_erroneousStatementAtEndOfF
// Header File
original = "void f()@;\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -2131,16 +2333,16 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_erroneousStatementAtEndOfF
"\n"
"MissingSemicolon(int)\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Respect rvalue references
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_rvalueReference()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -2148,7 +2350,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_rvalueReference()
// Header File
original = "void f(Foo &&)@;\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original = "";
@@ -2159,16 +2361,16 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_rvalueReference()
"\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Find right implementation file. (QTCREATORBUG-10728)
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_findImplementationFile()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -2183,7 +2385,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_findImplementationFile()
"void Foo::bar()\n"
"{}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -2198,15 +2400,15 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_findImplementationFile()
"\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
void CppEditorPlugin::test_quickfix_InsertDefFromDecl_unicodeIdentifier()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -2237,7 +2439,7 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_unicodeIdentifier()
"{\n"
"\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
#undef UNICODE_U00FC
#undef UNICODE_U4E8C
@@ -2245,13 +2447,13 @@ void CppEditorPlugin::test_quickfix_InsertDefFromDecl_unicodeIdentifier()
#undef TEST_UNICODE_IDENTIFIER
InsertDefFromDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
// Function for one of InsertDeclDef section cases
void insertToSectionDeclFromDef(const QByteArray &section, int sectionIndex)
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -2267,7 +2469,7 @@ void insertToSectionDeclFromDef(const QByteArray &section, int sectionIndex)
+ section + ":\n" +
" Foo();\n"
"@};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -2278,10 +2480,10 @@ void insertToSectionDeclFromDef(const QByteArray &section, int sectionIndex)
"}\n"
;
expected = original;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
InsertDeclFromDef factory;
- QuickFixOperationTest(testFiles, &factory, ProjectPart::HeaderPaths(), sectionIndex);
+ QuickFixOperationTest(testDocuments, &factory, ProjectPart::HeaderPaths(), sectionIndex);
}
/// Check from source file: Insert in header file.
@@ -2295,19 +2497,26 @@ void CppEditorPlugin::test_quickfix_InsertDeclFromDef()
insertToSectionDeclFromDef("private slots", 5);
}
-/// Check: Add include if there is already an include
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onSimpleName()
+void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_data()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QTest::addColumn<QString>("headerPath");
+ QTest::addColumn<QuickFixTestDocuments>("testDocuments");
+ QTest::addColumn<int>("refactoringOperationIndex");
+ QTest::addColumn<QString>("includeForTestFactory");
+
+ const int firstRefactoringOperation = 0;
+ const int secondRefactoringOperation = 1;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
+ // -------------------------------------------------------------------------------------------
+
// Header File
original = "class Foo {};\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8() + "/afile.h",
- original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.h", original, expected);
// Source File
original =
@@ -2327,26 +2536,18 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onSimpleNam
" Foo foo;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Cursor is on a qualified name (1)
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onNameOfQualifiedName()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("onSimpleName")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
// Header File
original = "namespace N { class Foo {}; }\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.h", original, expected);
// Source File
original =
@@ -2366,26 +2567,18 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onNameOfQua
" N::Foo foo;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("onNameOfQualifiedName")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
- // Do not use the test factory, at least once we want to go through the "full stack".
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onBaseOfQualifiedName()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
// Header File
original = "namespace N { class Foo {}; }\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8() + "/afile.h",
- original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.h", original, expected);
// Source File
original =
@@ -2405,26 +2598,18 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onBaseOfQua
" N::Foo foo;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("onBaseOfQualifiedName")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
- // Do not use the test factory, at least once we want to go through the "full stack".
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onTemplateName()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
// Header File
original = "namespace N { template <typename T> class Foo {}; }\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.h", original, expected);
// Source File
original =
@@ -2444,26 +2629,18 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onTemplateN
" N::Foo<Bar> foo;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("onTemplateName")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
- // Do not use the test factory, at least once we want to go through the "full stack".
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onTemplateNameInsideArguments()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
// Header File
original = "namespace N { template <typename T> class Foo {}; }\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.h", original, expected);
// Source File
original =
@@ -2483,26 +2660,18 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_onTemplateN
" N::Bar<Foo> foo;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
-
- // Do not use the test factory, at least once we want to go through the "full stack".
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("onTemplateNameInsideArguments")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_withForwardDeclaration()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
// Header File
original = "class Foo {};\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.h", original, expected);
// Source File
original =
@@ -2526,26 +2695,18 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_withForward
" Foo foo;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("withForwardDeclaration")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
- // Do not use the test factory, at least once we want to go through the "full stack".
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_withForwardDeclaration2()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
// Header File
original = "template<class T> class Foo {};\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.h", original, expected);
// Source File
original =
@@ -2569,32 +2730,23 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_withForward
" Foo foo;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("withForwardDeclaration2")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
- // Do not use the test factory, at least once we want to go through the "full stack".
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_withForwardHeader()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
// Header File
original = "template<class T> class QMyClass {};\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/qmyclass.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("qmyclass.h", original, expected);
// Forward Header File
original = "#include \"qmyclass.h\"\n";
expected = original;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/QMyClass", original, expected);
+ testDocuments << QuickFixTestDocument::create("QMyClass", original, expected);
// Source File
original =
@@ -2614,21 +2766,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_withForward
" QMyClass c;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/afile.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("afile.cpp", original, expected);
+ QTest::newRow("withForwardHeader")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << secondRefactoringOperation << "";
+ testDocuments.clear();
- // Do not use the test factory, at least once we want to go through the "full stack".
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath(), 1);
-}
-
-/// Check: Ignore *.moc includes
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_ignoremoc()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"void @f();\n"
@@ -2640,20 +2784,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_i
"void f();\n"
"#include \"file.moc\";\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("insertingIgnoreMoc")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Insert include at top for a sorted group
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_sortingTop()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"y.h\"\n"
@@ -2666,20 +2803,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_s
"#include \"z.h\"\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("insertingSortingTop")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
-/// Check: Insert include in the middle for a sorted group
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_sortingMiddle()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"a.h\"\n"
@@ -2692,20 +2822,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_s
"#include \"z.h\"\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("insertingSortingMiddle")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Insert include at bottom for a sorted group
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_sortingBottom()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"a.h\"\n"
@@ -2718,20 +2841,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_s
"#include \"file.h\"\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: For an unsorted group the new include is appended
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_appendToUnsorted()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("insertingSortingBottom")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"b.h\"\n"
@@ -2744,20 +2860,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_a
"#include \"file.h\"\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8() +
- + "/file.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Insert a local include at front if there are only global includes
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_firstLocalIncludeAtFront()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_appendToUnsorted")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include <a.h>\n"
@@ -2771,20 +2880,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_f
"#include <b.h>\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_firstLocalIncludeAtFront")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Insert a global include at back if there are only local includes
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_firstGlobalIncludeAtBack()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"a.h\"\n"
@@ -2800,20 +2902,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_f
"\n"
"void f();\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<file.h>"));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("firstGlobalIncludeAtBack")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "<file.h>";
+ testDocuments.clear();
-/// Check: Prefer group with longest matching prefix
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_preferGroupWithLongerMatchingPrefix()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"prefixa.h\"\n"
@@ -2830,20 +2925,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_p
"#include \"foo.h\"\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_preferGroupWithLongerMatchingPrefix")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"prefixc.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"prefixc.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Create a new include group if there are only include groups with a different include dir
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_newGroupIfOnlyDifferentIncludeDirs()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"lib/file.h\"\n"
@@ -2857,20 +2945,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_n
"#include \"file.h\"\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_newGroupIfOnlyDifferentIncludeDirs")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Include group with mixed include dirs, sorted --> insert properly
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedDirsSorted()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include <lib/file.h>\n"
@@ -2885,20 +2966,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_m
"#include <utils/file.h>\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<firstlib/file.h>"));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_mixedDirsSorted")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "<firstlib/file.h>";
+ testDocuments.clear();
-/// Check: Include group with mixed include dirs, unsorted --> append
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedDirsUnsorted()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include <otherlib/file.h>\n"
@@ -2913,20 +2987,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_m
"#include <lastlib/file.h>\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_mixedDirsUnsorted")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "<lastlib/file.h>";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<lastlib/file.h>"));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Include group with mixed include types
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes1()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"a.h\"\n"
@@ -2939,20 +3006,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_m
"#include <global.h>\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_mixedIncludeTypes1")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"z.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"z.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Include group with mixed include types
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes2()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"z.h\"\n"
@@ -2965,20 +3025,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_m
"#include <global.h>\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_mixedIncludeTypes2")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"a.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"a.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Include group with mixed include types
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes3()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"z.h\"\n"
@@ -2991,20 +3044,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_m
"#include <global.h>\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"lib/file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Include group with mixed include types
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_mixedIncludeTypes4()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_mixedIncludeTypes3")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"lib/file.h\"";
+ testDocuments.clear();
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#include \"z.h\"\n"
@@ -3017,20 +3063,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_m
"#include <lib/file.h>\n"
"\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_mixedIncludeTypes4")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "<lib/file.h>";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("<lib/file.h>"));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Insert very first include
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_noinclude()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"void @f();\n"
@@ -3040,20 +3079,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_n
"\n"
"void f();\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
-
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_noinclude")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
-/// Check: Insert very first include after include guard
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_onlyIncludeGuard()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"#ifndef FOO_H\n"
@@ -3070,20 +3102,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_o
"void f();\n"
"#endif\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_onlyIncludeGuard")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Insert very first include if there is a c++ style comment on top
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_veryFirstIncludeCppStyleCommentOnTop()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"\n"
@@ -3099,20 +3124,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_v
"\n"
"void @f();\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_veryFirstIncludeCppStyleCommentOnTop")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: Insert very first include if there is a c style comment on top
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_veryFirstIncludeCStyleCommentOnTop()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"\n"
@@ -3132,21 +3150,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_v
"\n"
"void @f();\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_veryFirstIncludeCStyleCommentOnTop")
+ << TestIncludePaths::globalIncludePath()
+ << testDocuments << firstRefactoringOperation << "\"file.h\"";
+ testDocuments.clear();
- AddIncludeForUndefinedIdentifierTestFactory factory(QLatin1String("\"file.h\""));
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalIncludePath());
-}
-
-/// Check: If a "Qt Class" was not found by the locator, check the header files in the Qt
-/// include paths
-void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_checkQSomethingInQtIncludePaths()
-{
- QList<QuickFixTestDocument::Ptr> testFiles;
-
- QByteArray original;
- QByteArray expected;
+ // -------------------------------------------------------------------------------------------
original =
"@QDir dir;\n"
@@ -3156,29 +3166,53 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_inserting_c
"\n"
"QDir dir;\n"
;
- testFiles << QuickFixTestDocument::create(TestIncludePaths::directoryOfTestFile().toUtf8()
- + "/file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+ QTest::newRow("inserting_checkQSomethingInQtIncludePaths")
+ << TestIncludePaths::globalQtCoreIncludePath()
+ << testDocuments << firstRefactoringOperation << "";
+ testDocuments.clear();
+}
- AddIncludeForUndefinedIdentifier factory;
- QuickFixOperationTest::run(testFiles, &factory, TestIncludePaths::globalQtCoreIncludePath());
+void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier()
+{
+ QFETCH(QString, headerPath);
+ QFETCH(QuickFixTestDocuments, testDocuments);
+ QFETCH(int, refactoringOperationIndex);
+ QFETCH(QString, includeForTestFactory);
+
+ CppTools::Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+ foreach (QuickFixTestDocument::Ptr testDocument, testDocuments)
+ testDocument->setBaseDirectory(temporaryDir.path());
+
+ QScopedPointer<CppQuickFixFactory> factory;
+ if (includeForTestFactory.isEmpty())
+ factory.reset(new AddIncludeForUndefinedIdentifier);
+ else
+ factory.reset(new AddIncludeForUndefinedIdentifierTestFactory(includeForTestFactory));
+
+ QuickFixOperationTest::run(testDocuments, factory.data(), headerPath,
+ refactoringOperationIndex);
}
void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_noDoubleQtHeaderInclude()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ CppTools::Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
- const QByteArray base = TestIncludePaths::directoryOfTestFile().toUtf8();
+ const QByteArray base = temporaryDir.path().toUtf8();
// This file makes the QDir definition available so that locator finds it.
original = expected = "#include <QDir>\n"
"void avoidBeingRecognizedAsForwardingHeader();";
- testFiles << QuickFixTestDocument::create(base + "/fileUsingQDir.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create(base + "/fileUsingQDir.cpp", original, expected);
original = expected = "@QDir dir;\n";
- testFiles << QuickFixTestDocument::create(base + "/fileWantsToUseQDir.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create(base + "/fileWantsToUseQDir.cpp", original, expected);
ProjectPart::HeaderPaths headerPaths;
headerPaths += ProjectPart::HeaderPath(TestIncludePaths::globalQtCoreIncludePath(),
@@ -3186,13 +3220,13 @@ void CppEditorPlugin::test_quickfix_AddIncludeForUndefinedIdentifier_noDoubleQtH
AddIncludeForUndefinedIdentifier factory;
const QStringList expectedOperations = QStringList() << QLatin1String("Add #include <QDir>");
- QuickFixOfferedOperationsTest(testFiles, &factory, headerPaths, expectedOperations);
+ QuickFixOfferedOperationsTest(testDocuments, &factory, headerPaths, expectedOperations);
}
/// Check: Move definition from header to cpp.
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCpp()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3212,7 +3246,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCpp()
"\n"
" void bar();\n"
"};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3226,15 +3260,15 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCpp()
" return 5;\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppInsideNS()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3254,7 +3288,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppInsideNS()
" int ba@r();\n"
"};\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3272,10 +3306,10 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppInsideNS()
"}\n"
"\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Move definition outside class
@@ -3315,7 +3349,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncOutside1()
/// Check: Move definition outside class
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncOutside2()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3340,7 +3374,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncOutside2()
"{\n"
" return 1;\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3348,16 +3382,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncOutside2()
"void Foo::f1() {}\n"
"void Foo::f3() {}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory, ProjectPart::HeaderPaths(), 1);
+ QuickFixOperationTest(testDocuments, &factory, ProjectPart::HeaderPaths(), 1);
}
/// Check: Move definition from header to cpp (with namespace).
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppNS()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3377,7 +3411,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppNS()
" inline int number() const;\n"
"};\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3390,16 +3424,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppNS()
"{\n"
" return 5;\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Move definition from header to cpp (with namespace + using).
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppNSUsing()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3419,7 +3453,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppNSUsing()
" inline int number() const;\n"
"};\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3434,10 +3468,10 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncToCppNSUsing()
"{\n"
" return 5;\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Move definition outside class with Namespace
@@ -3470,7 +3504,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_MemberFuncOutsideWithNs()
/// Check: Move free function from header to cpp.
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_FreeFuncToCpp()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3483,7 +3517,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_FreeFuncToCpp()
expected =
"int number() const;\n"
;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3496,16 +3530,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_FreeFuncToCpp()
"{\n"
" return 5;\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Move free function from header to cpp (with namespace).
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_FreeFuncToCppNS()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3521,7 +3555,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_FreeFuncToCppNS()
"namespace MyNamespace {\n"
"int number() const;\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3534,16 +3568,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_FreeFuncToCppNS()
"{\n"
" return 5;\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Move Ctor with member initialization list (QTCREATORBUG-9157).
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_CtorWithInitialization1()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3564,7 +3598,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_CtorWithInitialization1()
" int a;\n"
" float b;\n"
"};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original ="#include \"file.h\"\n";
@@ -3574,16 +3608,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_CtorWithInitialization1()
"\n"
"Foo::Foo() : a(42), b(3.141) {}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Move Ctor with member initialization list (QTCREATORBUG-9462).
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_CtorWithInitialization2()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3607,7 +3641,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_CtorWithInitialization2()
"\n"
" int member;\n"
"};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original ="#include \"file.h\"\n";
@@ -3619,16 +3653,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_CtorWithInitialization2()
"{\n"
"}\n"
;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check if definition is inserted right after class for move definition outside
void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_afterClass()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3651,7 +3685,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_afterClass()
"void Foo::a() {}\n"
"\n"
"class Bar {};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3661,10 +3695,10 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_afterClass()
"{\n\n"
"}\n";
expected = original;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefOutside factory;
- QuickFixOperationTest(testFiles, &factory, ProjectPart::HeaderPaths(), 1);
+ QuickFixOperationTest(testDocuments, &factory, ProjectPart::HeaderPaths(), 1);
}
/// Check if whitespace is respected for operator functions
@@ -3747,7 +3781,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefOutside_macroUses()
/// Check: revert test_quickfix_MoveFuncDefOutside_MemberFuncToCpp()
void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFunc()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3760,7 +3794,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFunc()
"class Foo {\n"
" inline int number() const {return 5;}\n"
"};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3770,10 +3804,10 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFunc()
expected =
"#include \"file.h\"\n"
"\n\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefToDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: revert test_quickfix_MoveFuncDefOutside_MemberFuncOutside()
@@ -3804,7 +3838,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncOutside()
/// Check: revert test_quickfix_MoveFuncDefOutside_MemberFuncToCppNS()
void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncToCppNS()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3824,7 +3858,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncToCppNS()
" }\n"
"};\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3835,16 +3869,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncToCppNS()
" return 5;\n"
"}\n";
expected = "#include \"file.h\"\n\n\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefToDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: revert test_quickfix_MoveFuncDefOutside_MemberFuncToCppNSUsing()
void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncToCppNSUsing()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3864,7 +3898,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncToCppNSUsing()
" }\n"
"};\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3879,10 +3913,10 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncToCppNSUsing()
"#include \"file.h\"\n"
"using namespace MyNs;\n"
"\n\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefToDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: revert test_quickfix_MoveFuncDefOutside_MemberFuncOutsideWithNs()
@@ -3915,7 +3949,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_MemberFuncOutsideWithNs()
/// Check: revert test_quickfix_MoveFuncDefOutside_FreeFuncToCpp()
void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_FreeFuncToCpp()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3926,7 +3960,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_FreeFuncToCpp()
"{\n"
" return 5;\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3938,16 +3972,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_FreeFuncToCpp()
" return 5;\n"
"}\n";
expected = "#include \"file.h\"\n\n\n\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefToDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: revert test_quickfix_MoveFuncDefOutside_FreeFuncToCppNS()
void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_FreeFuncToCppNS()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -3963,7 +3997,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_FreeFuncToCppNS()
" return 5;\n"
"}\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -3976,16 +4010,16 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_FreeFuncToCppNS()
expected =
"#include \"file.h\"\n"
"\n\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefToDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: revert test_quickfix_MoveFuncDefOutside_CtorWithInitialization()
void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_CtorWithInitialization()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -4006,7 +4040,7 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_CtorWithInitialization()
" int a;\n"
" float b;\n"
"};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -4015,10 +4049,10 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_CtorWithInitialization()
"Foo::F@oo() : a(42), b(3.141) {}"
;
expected ="#include \"file.h\"\n\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
MoveFuncDefToDecl factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
/// Check: Definition should not be placed behind the variable. QTCREATORBUG-10303
@@ -4078,10 +4112,193 @@ void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_macroUses()
ProjectPart::HeaderPaths(), 0, "QTCREATORBUG-12314");
}
+void CppEditorPlugin::test_quickfix_MoveFuncDefToDecl_override()
+{
+ QByteArray original =
+ "struct Base {\n"
+ " virtual int foo() = 0;\n"
+ "};\n"
+ "struct Derived : Base {\n"
+ " int foo() override;\n"
+ "};\n"
+ "\n"
+ "int Derived::fo@o()\n"
+ "{\n"
+ " return 5;\n"
+ "}\n";
+
+ QByteArray expected =
+ "struct Base {\n"
+ " virtual int foo() = 0;\n"
+ "};\n"
+ "struct Derived : Base {\n"
+ " int foo() override\n"
+ " {\n"
+ " return 5;\n"
+ " }\n"
+ "};\n\n\n";
+
+ MoveFuncDefToDecl factory;
+ QuickFixOperationTest(singleDocument(original, expected), &factory);
+}
+
+/// Check: Move all definitions from header to cpp.
+void CppEditorPlugin::test_quickfix_MoveAllFuncDefOutside_MemberFuncToCpp()
+{
+ QList<QuickFixTestDocument::Ptr> testDocuments;
+ QByteArray original;
+ QByteArray expected;
+
+ // Header File
+ original =
+ "class Fo@o {\n"
+ " int numberA() const\n"
+ " {\n"
+ " return 5;\n"
+ " }\n"
+ " int numberB() const\n"
+ " {\n"
+ " return 5;\n"
+ " }\n"
+ "};\n";
+ expected =
+ "class Foo {\n"
+ " int numberA() const;\n"
+ " int numberB() const;\n"
+ "};\n";
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
+
+ // Source File
+ original =
+ "#include \"file.h\"\n";
+ expected =
+ "#include \"file.h\"\n"
+ "\n"
+ "\n"
+ "int Foo::numberA() const\n"
+ "{\n"
+ " return 5;\n"
+ "}\n"
+ "\n\n"
+ "int Foo::numberB() const\n"
+ "{\n"
+ " return 5;\n"
+ "}\n"
+ ;
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
+
+ MoveAllFuncDefOutside factory;
+ QuickFixOperationTest(testDocuments, &factory);
+}
+
+/// Check: Move all definition outside class
+void CppEditorPlugin::test_quickfix_MoveAllFuncDefOutside_MemberFuncOutside()
+{
+ QByteArray original =
+ "class F@oo {\n"
+ " int f1()\n"
+ " {\n"
+ " return 1;\n"
+ " }\n"
+ " int f2() const\n"
+ " {\n"
+ " return 2;\n"
+ " }\n"
+ "};\n";
+ QByteArray expected =
+ "class Foo {\n"
+ " int f1();\n"
+ " int f2() const;\n"
+ "};\n"
+ "\n\n"
+ "int Foo::f1()\n"
+ "{\n"
+ " return 1;\n"
+ "}\n"
+ "\n\n"
+ "int Foo::f2() const\n"
+ "{\n"
+ " return 2;\n"
+ "}\n";
+
+ MoveAllFuncDefOutside factory;
+ QuickFixOperationTest(singleDocument(original, expected), &factory);
+}
+
+/// Check: Move all definition outside class
+void CppEditorPlugin::test_quickfix_MoveAllFuncDefOutside_DoNotTriggerOnBaseClass()
+{
+ QByteArray original =
+ "class Bar;\n"
+ "class Foo : public Ba@r {\n"
+ " int f1()\n"
+ " {\n"
+ " return 1;\n"
+ " }\n"
+ "};\n";
+
+ MoveAllFuncDefOutside factory;
+ QuickFixOperationTest(singleDocument(original, ""), &factory);
+}
+
+/// Check: Move all definition outside class
+void CppEditorPlugin::test_quickfix_MoveAllFuncDefOutside_classWithBaseClass()
+{
+ QByteArray original =
+ "class Bar;\n"
+ "class Fo@o : public Bar {\n"
+ " int f1()\n"
+ " {\n"
+ " return 1;\n"
+ " }\n"
+ "};\n";
+ QByteArray expected =
+ "class Bar;\n"
+ "class Foo : public Bar {\n"
+ " int f1();\n"
+ "};\n"
+ "\n\n"
+ "int Foo::f1()\n"
+ "{\n"
+ " return 1;\n"
+ "}\n";
+
+ MoveAllFuncDefOutside factory;
+ QuickFixOperationTest(singleDocument(original, expected), &factory);
+}
+
+/// Check: Do not take macro expanded code into account (QTCREATORBUG-13900)
+void CppEditorPlugin::test_quickfix_MoveAllFuncDefOutside_ignoreMacroCode()
+{
+ QByteArray original =
+ "#define FAKE_Q_OBJECT int bar() {return 5;}\n"
+ "class Fo@o {\n"
+ " FAKE_Q_OBJECT\n"
+ " int f1()\n"
+ " {\n"
+ " return 1;\n"
+ " }\n"
+ "};\n";
+ QByteArray expected =
+ "#define FAKE_Q_OBJECT int bar() {return 5;}\n"
+ "class Foo {\n"
+ " FAKE_Q_OBJECT\n"
+ " int f1();\n"
+ "};\n"
+ "\n\n"
+ "int Foo::f1()\n"
+ "{\n"
+ " return 1;\n"
+ "}\n";
+
+ MoveAllFuncDefOutside factory;
+ QuickFixOperationTest(singleDocument(original, expected), &factory);
+}
+
void CppEditorPlugin::test_quickfix_AssignToLocalVariable_templates()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -4094,7 +4311,7 @@ void CppEditorPlugin::test_quickfix_AssignToLocalVariable_templates()
"};\n"
;
expected = original;
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -4109,10 +4326,10 @@ void CppEditorPlugin::test_quickfix_AssignToLocalVariable_templates()
" List<int> list;\n"
" int localFirst = list.first();\n"
"}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
AssignToLocalVariable factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_typeDeduction_data()
@@ -4181,7 +4398,7 @@ void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_typeDeduction()
void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_freeFunction_separateFiles()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -4190,7 +4407,7 @@ void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_freeFunction_separ
"void foo(const char *a, long b = 1);\n";
expected =
"void foo(const char *a, long b = 1, int newParameter = 156);\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -4199,15 +4416,15 @@ void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_freeFunction_separ
expected =
"void foo(const char *a, long b, int newParameter)\n"
"{return newParameter + 123 + newParameter;}\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
ExtractLiteralAsParameter factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_memberFunction_separateFiles()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
QByteArray expected;
@@ -4222,7 +4439,7 @@ void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_memberFunction_sep
"public:\n"
" int zort(int newParameter = 155);\n"
"};\n";
- testFiles << QuickFixTestDocument::create("file.h", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.h", original, expected);
// Source File
original =
@@ -4233,28 +4450,25 @@ void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_memberFunction_sep
"#include \"file.h\"\n\n"
"int Narf::zort(int newParameter)\n"
"{ return newParameter + 1; }\n";
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
ExtractLiteralAsParameter factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
void CppEditorPlugin::test_quickfix_ExtractLiteralAsParameter_notTriggeringForInvalidCode()
{
- QList<QuickFixTestDocument::Ptr> testFiles;
+ QList<QuickFixTestDocument::Ptr> testDocuments;
QByteArray original;
- QByteArray expected;
-
original =
"T(\"test\")\n"
"{\n"
" const int i = @14;\n"
"}\n";
- expected = original;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, "");
ExtractLiteralAsParameter factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
void CppEditorPlugin::test_quickfix_ConvertQt4Connect_connectOutOfClass()
@@ -4283,11 +4497,11 @@ void CppEditorPlugin::test_quickfix_ConvertQt4Connect_connectOutOfClass()
" connect(&obj, &TestClass::sigFoo, &obj, &TestClass::setProp);"
+ suffix;
- QList<QuickFixTestDocument::Ptr> testFiles;
- testFiles << QuickFixTestDocument::create("file.cpp", original, expected);
+ QList<QuickFixTestDocument::Ptr> testDocuments;
+ testDocuments << QuickFixTestDocument::create("file.cpp", original, expected);
ConvertQt4Connect factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
void CppEditorPlugin::test_quickfix_ConvertQt4Connect_connectWithinClass_data()
@@ -4328,13 +4542,13 @@ void CppEditorPlugin::test_quickfix_ConvertQt4Connect_connectWithinClass()
QByteArray suffix = "\n}\n";
- QList<QuickFixTestDocument::Ptr> testFiles;
- testFiles << QuickFixTestDocument::create("file.cpp",
+ QList<QuickFixTestDocument::Ptr> testDocuments;
+ testDocuments << QuickFixTestDocument::create("file.cpp",
prefix + original + suffix,
prefix + expected + suffix);
ConvertQt4Connect factory;
- QuickFixOperationTest(testFiles, &factory);
+ QuickFixOperationTest(testDocuments, &factory);
}
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppquickfix_test.h b/src/plugins/cppeditor/cppquickfix_test.h
index a46eab46b40..ec0345fc11f 100644
--- a/src/plugins/cppeditor/cppquickfix_test.h
+++ b/src/plugins/cppeditor/cppquickfix_test.h
@@ -67,6 +67,8 @@ public:
QString m_expectedSource;
};
+typedef QList<QuickFixTestDocument::Ptr> QuickFixTestDocuments;
+
class BaseQuickFixTestCase : public TestCase
{
public:
@@ -82,6 +84,8 @@ protected:
QList<QuickFixTestDocument::Ptr> m_testDocuments;
private:
+ QScopedPointer<CppTools::Tests::TemporaryDir> m_temporaryDirectory;
+
CppTools::CppCodeStylePreferences *m_cppCodeStylePreferences;
QByteArray m_cppCodeStylePreferencesOriginalDelegateId;
@@ -123,3 +127,5 @@ QList<QuickFixTestDocument::Ptr> singleDocument(const QByteArray &original,
} // namespace Tests
} // namespace Internal
} // namespace CppEditor
+
+Q_DECLARE_METATYPE(CppEditor::Internal::Tests::QuickFixTestDocuments)
diff --git a/src/plugins/cppeditor/cppquickfixassistant.cpp b/src/plugins/cppeditor/cppquickfixassistant.cpp
index 6fa9eb76b6c..12661e0ec3e 100644
--- a/src/plugins/cppeditor/cppquickfixassistant.cpp
+++ b/src/plugins/cppeditor/cppquickfixassistant.cpp
@@ -63,9 +63,9 @@ IAssistProcessor *CppQuickFixAssistProvider::createProcessor() const
return new QuickFixAssistProcessor(this);
}
-QList<TextEditor::QuickFixFactory *> CppQuickFixAssistProvider::quickFixFactories() const
+QList<QuickFixFactory *> CppQuickFixAssistProvider::quickFixFactories() const
{
- QList<TextEditor::QuickFixFactory *> results;
+ QList<QuickFixFactory *> results;
foreach (CppQuickFixFactory *f, ExtensionSystem::PluginManager::getObjects<CppQuickFixFactory>())
results.append(f);
return results;
@@ -75,19 +75,19 @@ QList<TextEditor::QuickFixFactory *> CppQuickFixAssistProvider::quickFixFactorie
// CppQuickFixAssistInterface
// --------------------------
CppQuickFixInterface::CppQuickFixInterface(CppEditorWidget *editor,
- TextEditor::AssistReason reason)
+ AssistReason reason)
: AssistInterface(editor->document(), editor->position(),
- editor->textDocument()->filePath(), reason)
+ editor->textDocument()->filePath().toString(), reason)
, m_editor(editor)
, m_semanticInfo(editor->semanticInfo())
- , m_snapshot(CppTools::CppModelManager::instance()->snapshot())
+ , m_snapshot(CppModelManager::instance()->snapshot())
, m_currentFile(CppRefactoringChanges::file(editor, m_semanticInfo.doc))
, m_context(m_semanticInfo.doc, m_snapshot)
{
QTC_CHECK(m_semanticInfo.doc);
QTC_CHECK(m_semanticInfo.doc->translationUnit());
QTC_CHECK(m_semanticInfo.doc->translationUnit()->ast());
- CPlusPlus::ASTPath astPath(m_semanticInfo.doc);
+ ASTPath astPath(m_semanticInfo.doc);
m_path = astPath(editor->textCursor());
}
@@ -126,7 +126,7 @@ bool CppQuickFixInterface::isCursorOn(unsigned tokenIndex) const
return currentFile()->isCursorOn(tokenIndex);
}
-bool CppQuickFixInterface::isCursorOn(const CPlusPlus::AST *ast) const
+bool CppQuickFixInterface::isCursorOn(const AST *ast) const
{
return currentFile()->isCursorOn(ast);
}
diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp
index 5e6b4de5fa2..baabd0bbda4 100644
--- a/src/plugins/cppeditor/cppquickfixes.cpp
+++ b/src/plugins/cppeditor/cppquickfixes.cpp
@@ -38,6 +38,7 @@
#include "cppinsertvirtualmethods.h"
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <cpptools/cppclassesfilter.h>
#include <cpptools/cppcodestylesettings.h>
@@ -62,7 +63,6 @@
#include <QDir>
#include <QFileInfo>
#include <QInputDialog>
-#include <QMessageBox>
#include <QSharedPointer>
#include <QStack>
#include <QTextCursor>
@@ -117,6 +117,7 @@ void registerQuickFixes(ExtensionSystem::IPlugin *plugIn)
plugIn->addAutoReleasedObject(new InsertDefFromDecl);
plugIn->addAutoReleasedObject(new MoveFuncDefOutside);
+ plugIn->addAutoReleasedObject(new MoveAllFuncDefOutside);
plugIn->addAutoReleasedObject(new MoveFuncDefToDecl);
plugIn->addAutoReleasedObject(new AssignToLocalVariable);
@@ -260,7 +261,7 @@ Namespace *isNamespaceFunction(const LookupContext &context, Function *function)
// Given include is e.g. "afile.h" or <afile.h> (quotes/angle brackets included!).
void insertNewIncludeDirective(const QString &include, CppRefactoringFilePtr file,
- const CPlusPlus::Document::Ptr &cppDocument)
+ const Document::Ptr &cppDocument)
{
// Find optimal position
using namespace IncludeUtils;
@@ -296,6 +297,30 @@ bool nameIncludesOperatorName(const Name *name)
|| (name->isQualifiedNameId() && name->asQualifiedNameId()->name()->isOperatorNameId());
}
+QString memberBaseName(const QString &name)
+{
+ QString baseName = name;
+
+ // Remove leading and trailing "_"
+ while (baseName.startsWith(QLatin1Char('_')))
+ baseName.remove(0, 1);
+ while (baseName.endsWith(QLatin1Char('_')))
+ baseName.chop(1);
+ if (baseName != name)
+ return baseName;
+
+ // If no leading/trailing "_": remove "m_" and "m" prefix
+ if (baseName.startsWith(QLatin1String("m_"))) {
+ baseName.remove(0, 2);
+ } else if (baseName.startsWith(QLatin1Char('m')) && baseName.length() > 1
+ && baseName.at(1).isUpper()) {
+ baseName.remove(0, 1);
+ baseName[0] = baseName.at(0).toLower();
+ }
+
+ return baseName;
+}
+
} // anonymous namespace
namespace {
@@ -1907,15 +1932,16 @@ void AddIncludeForUndefinedIdentifier::match(const CppQuickFixInterface &interfa
Snapshot localForwardHeaders = forwardHeaders;
localForwardHeaders.insert(interface.snapshot().document(info->fileName()));
- QStringList headerAndItsForwardingHeaders;
- headerAndItsForwardingHeaders << info->fileName();
+ Utils::FileNameList headerAndItsForwardingHeaders;
+ headerAndItsForwardingHeaders << Utils::FileName::fromString(info->fileName());
headerAndItsForwardingHeaders += localForwardHeaders.filesDependingOn(info->fileName());
- foreach (const QString &header, headerAndItsForwardingHeaders) {
- const QString include = findShortestInclude(currentDocumentFilePath, header,
+ foreach (const Utils::FileName &header, headerAndItsForwardingHeaders) {
+ const QString include = findShortestInclude(currentDocumentFilePath,
+ header.toString(),
headerPaths);
if (include.size() > 2) {
- const QString headerFileName = QFileInfo(info->fileName()).fileName();
+ const QString headerFileName = Utils::FileName::fromString(info->fileName()).fileName();
QTC_ASSERT(!headerFileName.isEmpty(), break);
int priority = 0;
@@ -2341,19 +2367,9 @@ public:
, m_xsSpec(xsSpec)
, m_decl(decl)
{
- QString type;
- switch (xsSpec) {
- case InsertionPointLocator::Public: type = QLatin1String("public"); break;
- case InsertionPointLocator::Protected: type = QLatin1String("protected"); break;
- case InsertionPointLocator::Private: type = QLatin1String("private"); break;
- case InsertionPointLocator::PublicSlot: type = QLatin1String("public slot"); break;
- case InsertionPointLocator::ProtectedSlot: type = QLatin1String("protected slot"); break;
- case InsertionPointLocator::PrivateSlot: type = QLatin1String("private slot"); break;
- default: break;
- }
-
setDescription(QCoreApplication::translate("CppEditor::InsertDeclOperation",
- "Add %1 Declaration").arg(type));
+ "Add %1 Declaration")
+ .arg(InsertionPointLocator::accessSpecToString(xsSpec)));
}
void perform()
@@ -2634,7 +2650,7 @@ void InsertDefFromDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
return;
// Check if there is already a definition
- CppTools::SymbolFinder symbolFinder;
+ SymbolFinder symbolFinder;
if (symbolFinder.findMatchingDefinition(decl, interface.snapshot(),
true)) {
return;
@@ -2717,18 +2733,25 @@ namespace {
class GenerateGetterSetterOperation : public CppQuickFixOperation
{
public:
+ enum OperationType {
+ InvalidType,
+ GetterSetterType,
+ GetterType,
+ SetterType
+ };
+
GenerateGetterSetterOperation(const CppQuickFixInterface &interface)
: CppQuickFixOperation(interface)
+ , m_type(InvalidType)
, m_variableName(0)
, m_declaratorId(0)
, m_declarator(0)
, m_variableDecl(0)
, m_classSpecifier(0)
, m_classDecl(0)
+ , m_symbol(0)
, m_offerQuickFix(true)
{
- setDescription(TextEditor::QuickFixFactory::tr("Create Getter and Setter Member Functions"));
-
const QList<AST *> &path = interface.path();
// We expect something like
// [0] TranslationUnitAST
@@ -2784,18 +2807,9 @@ public:
}
m_variableString = QString::fromUtf8(variableId->chars(), variableId->size());
- m_baseName = m_variableString;
- if (m_baseName.startsWith(QLatin1Char('_'))) {
- m_baseName.remove(0, 1);
- } else if (m_baseName.endsWith(QLatin1Char('_'))) {
- m_baseName.chop(1);
- } else if (m_baseName.startsWith(QLatin1String("m_"))) {
- m_baseName.remove(0, 2);
- } else if (m_baseName.startsWith(QLatin1Char('m')) && m_baseName.length() > 1
- && m_baseName.at(1).isUpper()) {
- m_baseName.remove(0, 1);
- m_baseName[0] = m_baseName.at(0).toLower();
- }
+ m_baseName = memberBaseName(m_variableString);
+ if (m_baseName.isEmpty())
+ m_baseName = QLatin1String("value");
m_getterName = m_baseName != m_variableString
? m_baseName
@@ -2804,25 +2818,118 @@ public:
m_setterName = QString::fromLatin1("set%1%2")
.arg(m_baseName.left(1).toUpper()).arg(m_baseName.mid(1));
- // Check if the class has already a getter or setter.
+ // Check if the class has already both a getter and setter.
// This is only a simple check which should suffice not triggering the
// same quick fix again. Limitations:
// 1) It only checks in the current class, but not in base classes.
// 2) It compares only names instead of types/signatures.
+ bool hasGetter = false;
+ bool hasSetter = false;
if (Class *klass = m_classSpecifier->symbol) {
for (unsigned i = 0; i < klass->memberCount(); ++i) {
Symbol *symbol = klass->memberAt(i);
if (const Name *symbolName = symbol->name()) {
if (const Identifier *id = symbolName->identifier()) {
const QString memberName = QString::fromUtf8(id->chars(), id->size());
- if (memberName == m_getterName || memberName == m_setterName) {
- m_offerQuickFix = false;
- return;
- }
+ if (memberName == m_getterName)
+ hasGetter = true;
+ if (memberName == m_setterName)
+ hasSetter = true;
+ if (hasGetter && hasSetter)
+ break;
}
}
} // for
}
+ if (hasGetter && hasSetter) {
+ m_offerQuickFix = false;
+ return;
+ }
+
+ // Find the right symbol in the simple declaration
+ const List<Symbol *> *symbols = m_variableDecl->symbols;
+ QTC_ASSERT(symbols, return);
+ for (; symbols; symbols = symbols->next) {
+ Symbol *s = symbols->value;
+ if (const Name *name = s->name()) {
+ if (const Identifier *id = name->identifier()) {
+ const QString symbolName = QString::fromUtf8(id->chars(), id->size());
+ if (symbolName == m_variableString) {
+ m_symbol = s;
+ break;
+ }
+ }
+ }
+ }
+
+ QTC_ASSERT(m_symbol, return);
+ if (hasSetter) { // hasGetter is false in this case
+ m_type = GetterType;
+ } else { // no setter
+ if (hasGetter) {
+ if (m_symbol->type().isConst()) {
+ m_offerQuickFix = false;
+ return;
+ } else {
+ m_type = SetterType;
+ }
+ } else {
+ m_type = (m_symbol->type().isConst()) ? GetterType : GetterSetterType;
+ }
+ }
+ updateDescriptionAndPriority();
+ }
+
+ // Clones "other" in order to prevent all the initial detection made in the ctor.
+ GenerateGetterSetterOperation(const CppQuickFixInterface &interface,
+ GenerateGetterSetterOperation *other, OperationType type)
+ : CppQuickFixOperation(interface)
+ , m_type(type)
+ , m_variableName(other->m_variableName)
+ , m_declaratorId(other->m_declaratorId)
+ , m_declarator(other->m_declarator)
+ , m_variableDecl(other->m_variableDecl)
+ , m_classSpecifier(other->m_classSpecifier)
+ , m_classDecl(other->m_classDecl)
+ , m_symbol(other->m_symbol)
+ , m_baseName(other->m_baseName)
+ , m_getterName(other->m_getterName)
+ , m_setterName(other->m_setterName)
+ , m_variableString(other->m_variableString)
+ , m_offerQuickFix(other->m_offerQuickFix)
+ {
+ QTC_ASSERT(isValid(), return);
+ updateDescriptionAndPriority();
+ }
+
+ bool generateGetter() const
+ {
+ return (m_type == GetterSetterType || m_type == GetterType);
+ }
+
+ bool generateSetter() const
+ {
+ return (m_type == GetterSetterType || m_type == SetterType);
+ }
+
+ void updateDescriptionAndPriority()
+ {
+ switch (m_type) {
+ case GetterSetterType:
+ setPriority(5);
+ setDescription(QuickFixFactory::tr("Create Getter and Setter Member Functions"));
+ break;
+ case GetterType:
+ setPriority(4);
+ setDescription(QuickFixFactory::tr("Create Getter Member Function"));
+ break;
+ case SetterType:
+ setPriority(3);
+ setDescription(QuickFixFactory::tr("Create Setter Member Function"));
+ break;
+ default:
+ break;
+ }
}
bool isValid() const
@@ -2841,26 +2948,8 @@ public:
CppRefactoringChanges refactoring(snapshot());
CppRefactoringFilePtr currentFile = refactoring.file(fileName());
- const List<Symbol *> *symbols = m_variableDecl->symbols;
- QTC_ASSERT(symbols, return);
-
- // Find the right symbol in the simple declaration
- Symbol *symbol = 0;
- for (; symbols; symbols = symbols->next) {
- Symbol *s = symbols->value;
- if (const Name *name = s->name()) {
- if (const Identifier *id = name->identifier()) {
- const QString symbolName = QString::fromUtf8(id->chars(), id->size());
- if (symbolName == m_variableString) {
- symbol = s;
- break;
- }
- }
- }
- }
-
- QTC_ASSERT(symbol, return);
- FullySpecifiedType fullySpecifiedType = symbol->type();
+ QTC_ASSERT(m_symbol, return);
+ FullySpecifiedType fullySpecifiedType = m_symbol->type();
Type *type = fullySpecifiedType.type();
QTC_ASSERT(type, return);
Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
@@ -2903,7 +2992,7 @@ public:
paramString = oo.prettyType(referenceToConstParamType, paramName);
}
- const bool isStatic = symbol->storage() == Symbol::Static;
+ const bool isStatic = m_symbol->storage() == Symbol::Static;
// Construct declaration strings
QString declaration = declLocation.prefix();
@@ -2924,8 +3013,9 @@ public:
.arg(m_setterName)
.arg(paramString);
- declaration += declarationGetter;
- if (!fullySpecifiedType.isConst())
+ if (generateGetter())
+ declaration += declarationGetter;
+ if (generateSetter())
declaration += declarationSetter;
declaration += declLocation.suffix();
@@ -2948,8 +3038,10 @@ public:
.arg(classString).arg(m_setterName)
.arg(paramString).arg(m_variableString)
.arg(paramName);
- QString implementation = implementationGetter;
- if (!fullySpecifiedType.isConst())
+ QString implementation;
+ if (generateGetter())
+ implementation += implementationGetter;
+ if (generateSetter())
implementation += implementationSetter;
// Create and apply changes
@@ -2959,17 +3051,17 @@ public:
currChanges.insert(declInsertPos, declaration);
if (sameFile) {
- InsertionLocation loc = insertLocationForMethodDefinition(symbol, false, refactoring,
+ InsertionLocation loc = insertLocationForMethodDefinition(m_symbol, false, refactoring,
currentFile->fileName());
currChanges.insert(currentFile->position(loc.line(), loc.column()), implementation);
} else {
CppRefactoringChanges implRef(snapshot());
CppRefactoringFilePtr implFile = implRef.file(implFileName);
ChangeSet implChanges;
- InsertionLocation loc = insertLocationForMethodDefinition(symbol, false,
+ InsertionLocation loc = insertLocationForMethodDefinition(m_symbol, false,
implRef, implFileName);
const int implInsertPos = implFile->position(loc.line(), loc.column());
- implChanges.insert(implFile->position(loc.line(), loc.column()), implementation);
+ implChanges.insert(implInsertPos, implementation);
implFile->setChangeSet(implChanges);
implFile->appendIndentRange(
ChangeSet::Range(implInsertPos, implInsertPos + implementation.size()));
@@ -2981,12 +3073,14 @@ public:
currentFile->apply();
}
+ OperationType m_type;
SimpleNameAST *m_variableName;
DeclaratorIdAST *m_declaratorId;
DeclaratorAST *m_declarator;
SimpleDeclarationAST *m_variableDecl;
ClassSpecifierAST *m_classSpecifier;
SimpleDeclarationAST *m_classDecl;
+ Symbol *m_symbol;
QString m_baseName;
QString m_getterName;
@@ -3001,10 +3095,17 @@ void GenerateGetterSetter::match(const CppQuickFixInterface &interface,
QuickFixOperations &result)
{
GenerateGetterSetterOperation *op = new GenerateGetterSetterOperation(interface);
- if (op->isValid())
+ if (op->m_type != GenerateGetterSetterOperation::InvalidType) {
result.append(op);
- else
+ if (op->m_type == GenerateGetterSetterOperation::GetterSetterType) {
+ result.append(new GenerateGetterSetterOperation(
+ interface, op, GenerateGetterSetterOperation::GetterType));
+ result.append(new GenerateGetterSetterOperation(
+ interface, op, GenerateGetterSetterOperation::SetterType));
+ }
+ } else {
delete op;
+ }
}
namespace {
@@ -3186,10 +3287,9 @@ public:
return QString();
if (!isValidIdentifier(name)) {
- QMessageBox::critical(0,
- QCoreApplication::translate("QuickFix::ExtractFunction",
- "Extract Function Refactoring"),
- QCoreApplication::translate("QuickFix::ExtractFunction",
+ Core::AsynchronousMessageBox::critical(QCoreApplication::translate("QuickFix::ExtractFunction",
+ "Extract Function Refactoring"),
+ QCoreApplication::translate("QuickFix::ExtractFunction",
"Invalid function name"));
return QString();
}
@@ -3880,8 +3980,8 @@ public:
{
setDescription(
mode == FromPointer
- ? TextEditor::QuickFixFactory::tr("Convert to Stack Variable")
- : TextEditor::QuickFixFactory::tr("Convert to Pointer"));
+ ? QuickFixFactory::tr("Convert to Stack Variable")
+ : QuickFixFactory::tr("Convert to Pointer"));
}
void perform() Q_DECL_OVERRIDE
@@ -4219,7 +4319,7 @@ public:
, m_signalName(signalName)
, m_storageName(storageName)
{
- setDescription(TextEditor::QuickFixFactory::tr("Generate Missing Q_PROPERTY Members..."));
+ setDescription(QuickFixFactory::tr("Generate Missing Q_PROPERTY Members..."));
}
void perform()
@@ -4232,6 +4332,9 @@ public:
const QString typeName = file->textOf(m_declaration->type_id);
const QString propertyName = file->textOf(m_declaration->property_name);
+ QString baseName = memberBaseName(m_storageName);
+ if (baseName.isEmpty() || baseName == m_storageName)
+ baseName = QStringLiteral("arg");
// getter declaration
if (m_generateFlags & GenerateGetter) {
@@ -4246,12 +4349,13 @@ public:
if (m_generateFlags & GenerateSetter) {
QString setterDeclaration;
QTextStream setter(&setterDeclaration);
- setter << "void " << m_setterName << '(' << typeName << " arg)\n{\n";
+ setter << "void " << m_setterName << '(' << typeName << ' ' << baseName << ")\n{\n";
if (m_signalName.isEmpty()) {
- setter << m_storageName << " = arg;\n}\n";
+ setter << m_storageName << " = " << baseName << ";\n}\n";
} else {
- setter << "if (" << m_storageName << " == arg)\nreturn;\n\n"
- << m_storageName << " = arg;\nemit " << m_signalName << "(arg);\n}\n";
+ setter << "if (" << m_storageName << " == " << baseName << ")\nreturn;\n\n"
+ << m_storageName << " = " << baseName << ";\nemit " << m_signalName
+ << '(' << baseName << ");\n}\n";
}
InsertionLocation setterLoc = locator.methodDeclarationInClass(file->fileName(), m_class, InsertionPointLocator::PublicSlot);
QTC_ASSERT(setterLoc.isValid(), return);
@@ -4261,7 +4365,8 @@ public:
// signal declaration
if (m_generateFlags & GenerateSignal) {
const QString declaration = QLatin1String("void ") + m_signalName + QLatin1Char('(')
- + typeName + QLatin1String(" arg);\n");
+ + typeName + QLatin1Char(' ') + baseName
+ + QLatin1String(");\n");
InsertionLocation loc = locator.methodDeclarationInClass(file->fileName(), m_class, InsertionPointLocator::Signals);
QTC_ASSERT(loc.isValid(), return);
insertAndIndent(file, &declarations, loc, declaration);
@@ -4454,7 +4559,7 @@ QString definitionSignature(const CppQuickFixInterface *assist,
return oo.prettyType(tn, nameText);
}
-class MoveFuncDefOutsideOp : public CppQuickFixOperation
+class MoveFuncDefRefactoringHelper
{
public:
enum MoveType {
@@ -4463,78 +4568,106 @@ public:
MoveOutsideMemberToCppFile
};
- MoveFuncDefOutsideOp(const CppQuickFixInterface &interface,
- MoveType type, FunctionDefinitionAST *funcDef, const QString &cppFileName)
- : CppQuickFixOperation(interface, 0)
- , m_funcDef(funcDef)
- , m_type(type)
- , m_cppFileName(cppFileName)
- , m_func(funcDef->symbol)
- , m_headerFileName(QString::fromUtf8(m_func->fileName(), m_func->fileNameLength()))
+ MoveFuncDefRefactoringHelper(CppQuickFixOperation *operation, MoveType type,
+ const QString &fromFile, const QString &toFile)
+ : m_operation(operation), m_type(type), m_changes(m_operation->snapshot())
{
- if (m_type == MoveOutside) {
- setDescription(QCoreApplication::translate("CppEditor::QuickFix",
- "Move Definition Outside Class"));
- } else {
- const QDir dir = QFileInfo(m_headerFileName).dir();
- setDescription(QCoreApplication::translate("CppEditor::QuickFix",
- "Move Definition to %1")
- .arg(dir.relativeFilePath(m_cppFileName)));
- }
+ m_fromFile = m_changes.file(fromFile);
+ m_toFile = (m_type == MoveOutside) ? m_fromFile : m_changes.file(toFile);
}
- void perform()
+ void performMove(FunctionDefinitionAST *funcAST)
{
- CppRefactoringChanges refactoring(snapshot());
- CppRefactoringFilePtr fromFile = refactoring.file(m_headerFileName);
- CppRefactoringFilePtr toFile = (m_type == MoveOutside) ? fromFile
- : refactoring.file(m_cppFileName);
-
// Determine file, insert position and scope
- InsertionLocation l
- = insertLocationForMethodDefinition(m_func, false, refactoring, toFile->fileName());
+ InsertionLocation l = insertLocationForMethodDefinition(funcAST->symbol, false,
+ m_changes, m_toFile->fileName());
const QString prefix = l.prefix();
const QString suffix = l.suffix();
- const int insertPos = toFile->position(l.line(), l.column());
- Scope *scopeAtInsertPos = toFile->cppDocument()->scopeAt(l.line(), l.column());
+ const int insertPos = m_toFile->position(l.line(), l.column());
+ Scope *scopeAtInsertPos = m_toFile->cppDocument()->scopeAt(l.line(), l.column());
// construct definition
- const QString funcDec = definitionSignature(this, m_funcDef,
- fromFile, toFile,
+ const QString funcDec = definitionSignature(m_operation, funcAST, m_fromFile, m_toFile,
scopeAtInsertPos);
QString funcDef = prefix + funcDec;
- const int startPosition = fromFile->endOf(m_funcDef->declarator);
- const int endPosition = fromFile->endOf(m_funcDef->function_body);
- funcDef += fromFile->textOf(startPosition, endPosition);
+ const int startPosition = m_fromFile->endOf(funcAST->declarator);
+ const int endPosition = m_fromFile->endOf(funcAST->function_body);
+ funcDef += m_fromFile->textOf(startPosition, endPosition);
funcDef += suffix;
// insert definition at new position
- ChangeSet cppChanges;
- cppChanges.insert(insertPos, funcDef);
- toFile->setChangeSet(cppChanges);
- toFile->appendIndentRange(ChangeSet::Range(insertPos, insertPos + funcDef.size()));
- toFile->setOpenEditor(true, insertPos);
- toFile->apply();
+ m_toFileChangeSet.insert(insertPos, funcDef);
+ m_toFile->appendIndentRange(ChangeSet::Range(insertPos, insertPos + funcDef.size()));
+ m_toFile->setOpenEditor(true, insertPos);
// remove definition from fromFile
- ChangeSet headerTarget;
if (m_type == MoveOutsideMemberToCppFile) {
- headerTarget.remove(fromFile->range(m_funcDef));
+ m_fromFileChangeSet.remove(m_fromFile->range(funcAST));
} else {
- QString textFuncDecl = fromFile->textOf(m_funcDef);
- textFuncDecl.truncate(startPosition - fromFile->startOf(m_funcDef));
+ QString textFuncDecl = m_fromFile->textOf(funcAST);
+ textFuncDecl.truncate(startPosition - m_fromFile->startOf(funcAST));
textFuncDecl = textFuncDecl.trimmed() + QLatin1Char(';');
- headerTarget.replace(fromFile->range(m_funcDef), textFuncDecl);
+ m_fromFileChangeSet.replace(m_fromFile->range(funcAST), textFuncDecl);
+ }
+ }
+
+ void applyChanges()
+ {
+ if (!m_toFileChangeSet.isEmpty()) {
+ m_toFile->setChangeSet(m_toFileChangeSet);
+ m_toFile->apply();
+ }
+ if (!m_fromFileChangeSet.isEmpty()) {
+ m_fromFile->setChangeSet(m_fromFileChangeSet);
+ m_fromFile->apply();
}
- fromFile->setChangeSet(headerTarget);
- fromFile->apply();
}
private:
- FunctionDefinitionAST *m_funcDef;
+ CppQuickFixOperation *m_operation;
MoveType m_type;
+ CppRefactoringChanges m_changes;
+ CppRefactoringFilePtr m_fromFile;
+ CppRefactoringFilePtr m_toFile;
+ ChangeSet m_fromFileChangeSet;
+ ChangeSet m_toFileChangeSet;
+};
+
+class MoveFuncDefOutsideOp : public CppQuickFixOperation
+{
+public:
+ MoveFuncDefOutsideOp(const CppQuickFixInterface &interface,
+ MoveFuncDefRefactoringHelper::MoveType type,
+ FunctionDefinitionAST *funcDef, const QString &cppFileName)
+ : CppQuickFixOperation(interface, 0)
+ , m_funcDef(funcDef)
+ , m_type(type)
+ , m_cppFileName(cppFileName)
+ , m_headerFileName(QString::fromUtf8(funcDef->symbol->fileName(),
+ funcDef->symbol->fileNameLength()))
+ {
+ if (m_type == MoveFuncDefRefactoringHelper::MoveOutside) {
+ setDescription(QCoreApplication::translate("CppEditor::QuickFix",
+ "Move Definition Outside Class"));
+ } else {
+ const QDir dir = QFileInfo(m_headerFileName).dir();
+ setDescription(QCoreApplication::translate("CppEditor::QuickFix",
+ "Move Definition to %1")
+ .arg(dir.relativeFilePath(m_cppFileName)));
+ }
+ }
+
+ void perform()
+ {
+ MoveFuncDefRefactoringHelper helper(this, m_type, m_headerFileName, m_cppFileName);
+ helper.performMove(m_funcDef);
+ helper.applyChanges();
+ }
+
+private:
+ FunctionDefinitionAST *m_funcDef;
+ MoveFuncDefRefactoringHelper::MoveType m_type;
const QString m_cppFileName;
- Function *m_func;
const QString m_headerFileName;
};
@@ -4577,14 +4710,15 @@ void MoveFuncDefOutside::match(const CppQuickFixInterface &interface, QuickFixOp
bool isHeaderFile = false;
const QString cppFileName = correspondingHeaderOrSource(interface.fileName(), &isHeaderFile);
- if (isHeaderFile && !cppFileName.isEmpty())
- result.append(new MoveFuncDefOutsideOp(interface, ((moveOutsideMemberDefinition) ?
- MoveFuncDefOutsideOp::MoveOutsideMemberToCppFile
- : MoveFuncDefOutsideOp::MoveToCppFile),
- funcAST, cppFileName));
+ if (isHeaderFile && !cppFileName.isEmpty()) {
+ const MoveFuncDefRefactoringHelper::MoveType type = moveOutsideMemberDefinition
+ ? MoveFuncDefRefactoringHelper::MoveOutsideMemberToCppFile
+ : MoveFuncDefRefactoringHelper::MoveToCppFile;
+ result.append(new MoveFuncDefOutsideOp(interface, type, funcAST, cppFileName));
+ }
if (classAST)
- result.append(new MoveFuncDefOutsideOp(interface, MoveFuncDefOutsideOp::MoveOutside,
+ result.append(new MoveFuncDefOutsideOp(interface, MoveFuncDefRefactoringHelper::MoveOutside,
funcAST, QLatin1String("")));
return;
@@ -4592,6 +4726,94 @@ void MoveFuncDefOutside::match(const CppQuickFixInterface &interface, QuickFixOp
namespace {
+class MoveAllFuncDefOutsideOp : public CppQuickFixOperation
+{
+public:
+ MoveAllFuncDefOutsideOp(const CppQuickFixInterface &interface,
+ MoveFuncDefRefactoringHelper::MoveType type,
+ ClassSpecifierAST *classDef, const QString &cppFileName)
+ : CppQuickFixOperation(interface, 0)
+ , m_type(type)
+ , m_classDef(classDef)
+ , m_cppFileName(cppFileName)
+ , m_headerFileName(QString::fromUtf8(classDef->symbol->fileName(),
+ classDef->symbol->fileNameLength()))
+ {
+ if (m_type == MoveFuncDefRefactoringHelper::MoveOutside) {
+ setDescription(QCoreApplication::translate("CppEditor::QuickFix", "Move All Function "
+ "Definitions Outside Class"));
+ } else {
+ const QDir dir = QFileInfo(m_headerFileName).dir();
+ setDescription(QCoreApplication::translate("CppEditor::QuickFix",
+ "Move All Function Definitions to %1")
+ .arg(dir.relativeFilePath(m_cppFileName)));
+ }
+ }
+
+ void perform()
+ {
+ MoveFuncDefRefactoringHelper helper(this, m_type, m_headerFileName, m_cppFileName);
+ for (DeclarationListAST *it = m_classDef->member_specifier_list; it; it = it->next) {
+ if (FunctionDefinitionAST *funcAST = it->value->asFunctionDefinition()) {
+ if (funcAST->symbol && !funcAST->symbol->isGenerated())
+ helper.performMove(funcAST);
+ }
+ }
+ helper.applyChanges();
+ }
+
+private:
+ MoveFuncDefRefactoringHelper::MoveType m_type;
+ ClassSpecifierAST *m_classDef;
+ const QString m_cppFileName;
+ const QString m_headerFileName;
+};
+
+} // anonymous namespace
+
+void MoveAllFuncDefOutside::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
+{
+ const QList<AST *> &path = interface.path();
+ const int pathSize = path.size();
+ if (pathSize < 2)
+ return;
+
+ // Determine if cursor is on a class which is not a base class
+ ClassSpecifierAST *classAST = Q_NULLPTR;
+ if (SimpleNameAST *nameAST = path.at(pathSize - 1)->asSimpleName()) {
+ if (!interface.isCursorOn(nameAST))
+ return;
+ classAST = path.at(pathSize - 2)->asClassSpecifier();
+ }
+ if (!classAST)
+ return;
+
+ // Determine if the class has at least one function definition
+ bool classContainsFunctions = false;
+ for (DeclarationListAST *it = classAST->member_specifier_list; it; it = it->next) {
+ if (FunctionDefinitionAST *funcAST = it->value->asFunctionDefinition()) {
+ if (funcAST->symbol && !funcAST->symbol->isGenerated()) {
+ classContainsFunctions = true;
+ break;
+ }
+ }
+ }
+ if (!classContainsFunctions)
+ return;
+
+ bool isHeaderFile = false;
+ const QString cppFileName = correspondingHeaderOrSource(interface.fileName(), &isHeaderFile);
+ if (isHeaderFile && !cppFileName.isEmpty()) {
+ result.append(new MoveAllFuncDefOutsideOp(interface,
+ MoveFuncDefRefactoringHelper::MoveToCppFile,
+ classAST, cppFileName));
+ }
+ result.append(new MoveAllFuncDefOutsideOp(interface, MoveFuncDefRefactoringHelper::MoveOutside,
+ classAST, QLatin1String("")));
+}
+
+namespace {
+
class MoveFuncDefToDeclOp : public CppQuickFixOperation
{
public:
@@ -4852,7 +5074,6 @@ void AssignToLocalVariable::match(const CppQuickFixInterface &interface, QuickFi
const QList<AST *> &path = interface.path();
AST *outerAST = 0;
SimpleNameAST *nameAST = 0;
- SimpleNameAST *visibleNameAST = 0;
for (int i = path.size() - 3; i >= 0; --i) {
if (CallAST *callAST = path.at(i)->asCall()) {
@@ -4866,6 +5087,10 @@ void AssignToLocalVariable::match(const CppQuickFixInterface &interface, QuickFi
return;
if (path.at(idx)->asMemInitializer())
return;
+ if (path.at(idx)->asCall()) { // Fallback if we have a->b()->c()...
+ --i;
+ continue;
+ }
}
for (int a = i - 1; a > 0; --a) {
if (path.at(a)->asBinaryExpression())
@@ -4877,21 +5102,15 @@ void AssignToLocalVariable::match(const CppQuickFixInterface &interface, QuickFi
}
if (MemberAccessAST *member = path.at(i + 1)->asMemberAccess()) { // member
- if (member->base_expression) {
- if (IdExpressionAST *idex = member->base_expression->asIdExpression()) {
- nameAST = idex->name->asSimpleName();
- visibleNameAST = member->member_name->asSimpleName();
- }
- }
+ if (NameAST *name = member->member_name)
+ nameAST = name->asSimpleName();
} else if (QualifiedNameAST *qname = path.at(i + 2)->asQualifiedName()) { // static or
nameAST = qname->unqualified_name->asSimpleName(); // func in ns
- visibleNameAST = nameAST;
} else { // normal
nameAST = path.at(i + 2)->asSimpleName();
- visibleNameAST = nameAST;
}
- if (nameAST && visibleNameAST) {
+ if (nameAST) {
outerAST = callAST;
break;
}
@@ -4916,14 +5135,13 @@ void AssignToLocalVariable::match(const CppQuickFixInterface &interface, QuickFi
if (NamedTypeSpecifierAST *ts = path.at(i + 2)->asNamedTypeSpecifier()) {
nameAST = ts->name->asSimpleName();
- visibleNameAST = nameAST;
outerAST = newexp;
break;
}
}
}
- if (outerAST && nameAST && visibleNameAST) {
+ if (outerAST && nameAST) {
const CppRefactoringFilePtr file = interface.currentFile();
QList<LookupItem> items;
TypeOfExpression typeOfExpression;
@@ -4962,7 +5180,7 @@ void AssignToLocalVariable::match(const CppQuickFixInterface &interface, QuickFi
}
}
- const Name *name = visibleNameAST->name;
+ const Name *name = nameAST->name;
const int insertPos = interface.currentFile()->startOf(outerAST);
result.append(new AssignToLocalVariableOperation(interface, insertPos, outerAST, name));
return;
diff --git a/src/plugins/cppeditor/cppquickfixes.h b/src/plugins/cppeditor/cppquickfixes.h
index d1bd30cc5c8..b51cf185364 100644
--- a/src/plugins/cppeditor/cppquickfixes.h
+++ b/src/plugins/cppeditor/cppquickfixes.h
@@ -507,6 +507,15 @@ public:
};
/*!
+ Moves all member function definitions outside the class or to the implementation file.
+ */
+class MoveAllFuncDefOutside: public CppQuickFixFactory
+{
+public:
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
+};
+
+/*!
Moves the definition of a function to its declaration.
*/
class MoveFuncDefToDecl: public CppQuickFixFactory
diff --git a/src/plugins/cppeditor/cpptypehierarchy.cpp b/src/plugins/cppeditor/cpptypehierarchy.cpp
index 63129ace8ff..2d2304cf3e9 100644
--- a/src/plugins/cppeditor/cpptypehierarchy.cpp
+++ b/src/plugins/cppeditor/cpptypehierarchy.cpp
@@ -100,7 +100,7 @@ CppTypeHierarchyWidget::CppTypeHierarchyWidget() :
m_inspectedClass->setMargin(5);
m_model = new CppTypeHierarchyModel(this);
m_treeView = new NavigationTreeView(this);
- m_treeView->setActivationMode(Utils::SingleClickActivation);
+ m_treeView->setActivationMode(SingleClickActivation);
m_delegate = new AnnotatedItemDelegate(this);
m_delegate->setDelimiter(QLatin1String(" "));
m_delegate->setAnnotationRole(AnnotationRole);
diff --git a/src/plugins/cppeditor/cppuseselections_test.cpp b/src/plugins/cppeditor/cppuseselections_test.cpp
index 68255662a9c..5bd6733776e 100644
--- a/src/plugins/cppeditor/cppuseselections_test.cpp
+++ b/src/plugins/cppeditor/cppuseselections_test.cpp
@@ -89,6 +89,10 @@ UseSelectionsTestCase::UseSelectionsTestCase(TestDocument &testFile,
QVERIFY(testFile.hasCursorMarker());
testFile.m_source.remove(testFile.m_cursorPosition, 1);
+
+ CppTools::Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+ testFile.setBaseDirectory(temporaryDir.path());
testFile.writeToDisk();
QVERIFY(openCppEditor(testFile.filePath(), &testFile.m_editor, &m_editorWidget));
diff --git a/src/plugins/cppeditor/cppuseselectionsupdater.cpp b/src/plugins/cppeditor/cppuseselectionsupdater.cpp
index 1ada044e637..49ee7303e10 100644
--- a/src/plugins/cppeditor/cppuseselectionsupdater.cpp
+++ b/src/plugins/cppeditor/cppuseselectionsupdater.cpp
@@ -360,7 +360,7 @@ void CppUseSelectionsUpdater::handleSymbolCaseAsynchronously(const Document::Ptr
void CppUseSelectionsUpdater::handleSymbolCaseSynchronously(const Document::Ptr document,
const Snapshot &snapshot)
{
- const CPlusPlus::Document::Ptr previousDocument = m_document;
+ const Document::Ptr previousDocument = m_document;
m_document = document;
const Params params = Params(m_editorWidget->textCursor(), document, snapshot);
diff --git a/src/plugins/cppeditor/cppvirtualfunctionassistprovider.cpp b/src/plugins/cppeditor/cppvirtualfunctionassistprovider.cpp
index 457b5a632bc..97db446ac89 100644
--- a/src/plugins/cppeditor/cppvirtualfunctionassistprovider.cpp
+++ b/src/plugins/cppeditor/cppvirtualfunctionassistprovider.cpp
@@ -31,7 +31,6 @@
#include "cppvirtualfunctionassistprovider.h"
-#include "cppeditor.h"
#include "cppeditorconstants.h"
#include "cppvirtualfunctionproposalitem.h"
@@ -41,6 +40,7 @@
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
+#include <cpptools/cpptoolsreuse.h>
#include <cpptools/functionutils.h>
#include <cpptools/symbolfinder.h>
#include <cpptools/typehierarchybuilder.h>
@@ -128,11 +128,12 @@ public:
: m_params(params)
{}
- IAssistProposal *immediateProposal(const TextEditor::AssistInterface *) Q_DECL_OVERRIDE
+ IAssistProposal *immediateProposal(const AssistInterface *) Q_DECL_OVERRIDE
{
QTC_ASSERT(m_params.function, return 0);
- AssistProposalItem *hintItem = new VirtualFunctionProposalItem(CppEditorWidget::Link());
+ AssistProposalItem *hintItem
+ = new VirtualFunctionProposalItem(TextEditorWidget::Link());
hintItem->setText(QCoreApplication::translate("VirtualFunctionsAssistProcessor",
"...searching overrides"));
hintItem->setOrder(-1000);
@@ -179,7 +180,7 @@ private:
AssistProposalItem *itemFromFunction(Function *func) const
{
- const CppEditorWidget::Link link = CppEditorWidget::linkToSymbol(maybeDefinitionFor(func));
+ const TextEditorWidget::Link link = CppTools::linkToSymbol(maybeDefinitionFor(func));
QString text = m_overview.prettyName(LookupContext::fullyQualifiedName(func));
if (func->isPureVirtual())
text += QLatin1String(" = 0");
@@ -194,7 +195,7 @@ private:
VirtualFunctionAssistProvider::Parameters m_params;
Overview m_overview;
Icons m_icons;
- mutable CppTools::SymbolFinder m_finder;
+ mutable SymbolFinder m_finder;
};
VirtualFunctionAssistProvider::VirtualFunctionAssistProvider()
diff --git a/src/plugins/cppeditor/cppvirtualfunctionassistprovider.h b/src/plugins/cppeditor/cppvirtualfunctionassistprovider.h
index 6a2c95a327d..fac0f110907 100644
--- a/src/plugins/cppeditor/cppvirtualfunctionassistprovider.h
+++ b/src/plugins/cppeditor/cppvirtualfunctionassistprovider.h
@@ -37,7 +37,6 @@
#include <cplusplus/Symbols.h>
#include <cplusplus/TypeOfExpression.h>
-
#include <QSharedPointer>
#include <QTextCursor>
diff --git a/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp b/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp
index c9094e4a166..f1a7ff62b16 100644
--- a/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp
+++ b/src/plugins/cppeditor/followsymbol_switchmethoddecldef_test.cpp
@@ -270,8 +270,13 @@ F2TestCase::F2TestCase(CppEditorAction action,
"No test file with target cursor marker is provided.");
// Write files to disk
- foreach (TestDocumentPtr testFile, testFiles)
+ CppTools::Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+ foreach (TestDocumentPtr testFile, testFiles) {
+ QVERIFY(testFile->baseDirectory().isEmpty());
+ testFile->setBaseDirectory(temporaryDir.path());
QVERIFY(testFile->writeToDisk());
+ }
// Update Code Model
QSet<QString> filePaths;
@@ -344,7 +349,7 @@ F2TestCase::F2TestCase(CppEditorAction action,
BaseTextEditor *currentTextEditor = dynamic_cast<BaseTextEditor*>(currentEditor);
QVERIFY(currentTextEditor);
- QCOMPARE(currentTextEditor->document()->filePath(), targetTestFile->filePath());
+ QCOMPARE(currentTextEditor->document()->filePath().toString(), targetTestFile->filePath());
int expectedLine, expectedColumn;
currentTextEditor->convertPosition(targetTestFile->m_targetCursorPosition,
&expectedLine, &expectedColumn);
diff --git a/src/plugins/cpptools/baseeditordocumentparser.cpp b/src/plugins/cpptools/baseeditordocumentparser.cpp
index 5c46890c201..93bd1b6d8a9 100644
--- a/src/plugins/cpptools/baseeditordocumentparser.cpp
+++ b/src/plugins/cpptools/baseeditordocumentparser.cpp
@@ -107,8 +107,8 @@ void BaseEditorDocumentParser::setEditorDefines(const QByteArray &editorDefines)
BaseEditorDocumentParser *BaseEditorDocumentParser::get(const QString &filePath)
{
CppModelManager *cmmi = CppModelManager::instance();
- if (EditorDocumentHandle *editorDocument = cmmi->editorDocument(filePath)) {
- if (BaseEditorDocumentProcessor *processor = editorDocument->processor())
+ if (CppEditorDocumentHandle *cppEditorDocument = cmmi->cppEditorDocument(filePath)) {
+ if (BaseEditorDocumentProcessor *processor = cppEditorDocument->processor())
return processor->parser();
}
return 0;
@@ -130,7 +130,7 @@ void BaseEditorDocumentParser::updateProjectPart()
return;
// Fall-back step 1: Get some parts through the dependency table:
- projectParts = cmm->projectPartFromDependencies(m_filePath);
+ projectParts = cmm->projectPartFromDependencies(Utils::FileName::fromString(m_filePath));
if (projectParts.isEmpty())
// Fall-back step 2: Use fall-back part from the model manager:
m_projectPart = cmm->fallbackProjectPart();
diff --git a/src/plugins/cpptools/baseeditordocumentprocessor.cpp b/src/plugins/cpptools/baseeditordocumentprocessor.cpp
index 5624be8ce47..373624a9ea5 100644
--- a/src/plugins/cpptools/baseeditordocumentprocessor.cpp
+++ b/src/plugins/cpptools/baseeditordocumentprocessor.cpp
@@ -66,8 +66,8 @@ TextEditor::TextDocument *BaseEditorDocumentProcessor::baseTextDocument() const
BaseEditorDocumentProcessor *BaseEditorDocumentProcessor::get(const QString &filePath)
{
CppModelManager *cmmi = CppModelManager::instance();
- if (EditorDocumentHandle *editorDocument = cmmi->editorDocument(filePath))
- return editorDocument->processor();
+ if (CppEditorDocumentHandle *cppEditorDocument = cmmi->cppEditorDocument(filePath))
+ return cppEditorDocument->processor();
return 0;
}
diff --git a/src/plugins/cpptools/baseeditordocumentprocessor.h b/src/plugins/cpptools/baseeditordocumentprocessor.h
index 032ea0eda12..0ac944947ae 100644
--- a/src/plugins/cpptools/baseeditordocumentprocessor.h
+++ b/src/plugins/cpptools/baseeditordocumentprocessor.h
@@ -87,7 +87,7 @@ protected:
CppTools::WorkingCopy workingCopy);
// Convenience
- QString filePath() const { return m_baseTextDocument->filePath(); }
+ QString filePath() const { return m_baseTextDocument->filePath().toString(); }
unsigned revision() const { return static_cast<unsigned>(textDocument()->revision()); }
QTextDocument *textDocument() const { return m_baseTextDocument->document(); }
diff --git a/src/plugins/cpptools/builtineditordocumentparser.cpp b/src/plugins/cpptools/builtineditordocumentparser.cpp
index 5dbf26ccb36..4aea3d3cc05 100644
--- a/src/plugins/cpptools/builtineditordocumentparser.cpp
+++ b/src/plugins/cpptools/builtineditordocumentparser.cpp
@@ -116,9 +116,9 @@ void BuiltinEditorDocumentParser::update(WorkingCopy workingCopy)
m_snapshot = Snapshot();
} else {
// Remove changed files from the snapshot
- QSet<QString> toRemove;
+ QSet<Utils::FileName> toRemove;
foreach (const Document::Ptr &doc, m_snapshot) {
- QString fileName = doc->fileName();
+ const Utils::FileName fileName = Utils::FileName::fromString(doc->fileName());
if (workingCopy.contains(fileName)) {
if (workingCopy.get(fileName).second != doc->editorRevision())
addFileAndDependencies(&toRemove, fileName);
@@ -131,7 +131,7 @@ void BuiltinEditorDocumentParser::update(WorkingCopy workingCopy)
if (!toRemove.isEmpty()) {
invalidateSnapshot = true;
- foreach (const QString &fileName, toRemove)
+ foreach (const Utils::FileName &fileName, toRemove)
m_snapshot.remove(fileName);
}
}
@@ -183,7 +183,7 @@ void BuiltinEditorDocumentParser::update(WorkingCopy workingCopy)
m_snapshot = sourceProcessor.snapshot();
Snapshot newSnapshot = m_snapshot.simplified(document());
for (Snapshot::const_iterator i = m_snapshot.begin(), ei = m_snapshot.end(); i != ei; ++i) {
- if (Client::isInjectedFile(i.key()))
+ if (Client::isInjectedFile(i.key().toString()))
newSnapshot.insert(i.value());
}
m_snapshot = newSnapshot;
@@ -231,12 +231,12 @@ BuiltinEditorDocumentParser *BuiltinEditorDocumentParser::get(const QString &fil
return 0;
}
-void BuiltinEditorDocumentParser::addFileAndDependencies(QSet<QString> *toRemove,
- const QString &fileName) const
+void BuiltinEditorDocumentParser::addFileAndDependencies(QSet<Utils::FileName> *toRemove,
+ const Utils::FileName &fileName) const
{
toRemove->insert(fileName);
- if (fileName != filePath()) {
- QStringList deps = m_snapshot.filesDependingOn(fileName);
- toRemove->unite(QSet<QString>::fromList(deps));
+ if (fileName != Utils::FileName::fromString(filePath())) {
+ Utils::FileNameList deps = m_snapshot.filesDependingOn(fileName);
+ toRemove->unite(QSet<Utils::FileName>::fromList(deps));
}
}
diff --git a/src/plugins/cpptools/builtineditordocumentparser.h b/src/plugins/cpptools/builtineditordocumentparser.h
index ff0869f834c..4d04118bacf 100644
--- a/src/plugins/cpptools/builtineditordocumentparser.h
+++ b/src/plugins/cpptools/builtineditordocumentparser.h
@@ -65,7 +65,7 @@ public:
static BuiltinEditorDocumentParser *get(const QString &filePath);
private:
- void addFileAndDependencies(QSet<QString> *toRemove, const QString &fileName) const;
+ void addFileAndDependencies(QSet<Utils::FileName> *toRemove, const Utils::FileName &fileName) const;
private:
QByteArray m_configFile;
diff --git a/src/plugins/cpptools/builtineditordocumentprocessor.cpp b/src/plugins/cpptools/builtineditordocumentprocessor.cpp
index a9ad5838762..184563837d7 100644
--- a/src/plugins/cpptools/builtineditordocumentprocessor.cpp
+++ b/src/plugins/cpptools/builtineditordocumentprocessor.cpp
@@ -128,7 +128,7 @@ BuiltinEditorDocumentProcessor::BuiltinEditorDocumentProcessor(
TextEditor::TextDocument *document,
bool enableSemanticHighlighter)
: BaseEditorDocumentProcessor(document)
- , m_parser(document->filePath())
+ , m_parser(document->filePath().toString())
, m_codeWarningsUpdated(false)
, m_semanticHighlighter(enableSemanticHighlighter
? new CppTools::SemanticHighlighter(document)
diff --git a/src/plugins/cpptools/completionsettingspage.cpp b/src/plugins/cpptools/completionsettingspage.cpp
index 5b401a52582..099393810d4 100644
--- a/src/plugins/cpptools/completionsettingspage.cpp
+++ b/src/plugins/cpptools/completionsettingspage.cpp
@@ -29,9 +29,9 @@
****************************************************************************/
#include "completionsettingspage.h"
+#include "ui_completionsettingspage.h"
-#include <ui_completionsettingspage.h>
-#include "cpptoolsconstants.h"
+#include "cpptoolssettings.h"
#include <coreplugin/icore.h>
#include <texteditor/texteditorsettings.h>
@@ -40,14 +40,11 @@
using namespace CppTools;
using namespace CppTools::Internal;
-using namespace CppTools::Constants;
CompletionSettingsPage::CompletionSettingsPage(QObject *parent)
: TextEditor::TextEditorOptionsPage(parent)
, m_page(0)
{
- m_commentsSettings.fromSettings(QLatin1String(CPPTOOLS_SETTINGSGROUP), Core::ICore::settings());
-
setId("P.Completion");
setDisplayName(tr("Completion"));
}
@@ -64,11 +61,15 @@ QWidget *CompletionSettingsPage::widget()
m_page = new Ui::CompletionSettingsPage;
m_page->setupUi(m_widget);
- const TextEditor::CompletionSettings &settings =
+ connect(m_page->completionTrigger,
+ static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &CompletionSettingsPage::onCompletionTriggerChanged);
+
+ const TextEditor::CompletionSettings &completionSettings =
TextEditor::TextEditorSettings::completionSettings();
int caseSensitivityIndex = 0;
- switch (settings.m_caseSensitivity) {
+ switch (completionSettings.m_caseSensitivity) {
case TextEditor::CaseSensitive:
caseSensitivityIndex = 0;
break;
@@ -81,7 +82,7 @@ QWidget *CompletionSettingsPage::widget()
}
int completionTriggerIndex = 0;
- switch (settings.m_completionTrigger) {
+ switch (completionSettings.m_completionTrigger) {
case TextEditor::ManualCompletion:
completionTriggerIndex = 0;
break;
@@ -95,14 +96,19 @@ QWidget *CompletionSettingsPage::widget()
m_page->caseSensitivity->setCurrentIndex(caseSensitivityIndex);
m_page->completionTrigger->setCurrentIndex(completionTriggerIndex);
- m_page->autoInsertBrackets->setChecked(settings.m_autoInsertBrackets);
- m_page->surroundSelectedText->setChecked(settings.m_surroundingAutoBrackets);
- m_page->partiallyComplete->setChecked(settings.m_partiallyComplete);
- m_page->spaceAfterFunctionName->setChecked(settings.m_spaceAfterFunctionName);
- m_page->autoSplitStrings->setChecked(settings.m_autoSplitStrings);
- m_page->enableDoxygenCheckBox->setChecked(m_commentsSettings.m_enableDoxygen);
- m_page->generateBriefCheckBox->setChecked(m_commentsSettings.m_generateBrief);
- m_page->leadingAsterisksCheckBox->setChecked(m_commentsSettings.m_leadingAsterisks);
+ m_page->automaticProposalTimeoutSpinBox
+ ->setValue(completionSettings.m_automaticProposalTimeoutInMs);
+ m_page->autoInsertBrackets->setChecked(completionSettings.m_autoInsertBrackets);
+ m_page->surroundSelectedText->setChecked(completionSettings.m_surroundingAutoBrackets);
+ m_page->partiallyComplete->setChecked(completionSettings.m_partiallyComplete);
+ m_page->spaceAfterFunctionName->setChecked(completionSettings.m_spaceAfterFunctionName);
+ m_page->autoSplitStrings->setChecked(completionSettings.m_autoSplitStrings);
+
+ const CommentsSettings &commentsSettings = CppToolsSettings::instance()->commentsSettings();
+ m_page->enableDoxygenCheckBox->setChecked(commentsSettings.m_enableDoxygen);
+ m_page->generateBriefCheckBox->setChecked(commentsSettings.m_generateBrief);
+ m_page->leadingAsterisksCheckBox->setChecked(commentsSettings.m_leadingAsterisks);
+
m_page->generateBriefCheckBox->setEnabled(m_page->enableDoxygenCheckBox->isChecked());
}
return m_widget;
@@ -112,26 +118,27 @@ void CompletionSettingsPage::apply()
{
if (!m_page) // page was never shown
return;
- TextEditor::CompletionSettings settings;
- settings.m_caseSensitivity = caseSensitivity();
- settings.m_completionTrigger = completionTrigger();
- settings.m_autoInsertBrackets = m_page->autoInsertBrackets->isChecked();
- settings.m_surroundingAutoBrackets = m_page->surroundSelectedText->isChecked();
- settings.m_partiallyComplete = m_page->partiallyComplete->isChecked();
- settings.m_spaceAfterFunctionName = m_page->spaceAfterFunctionName->isChecked();
- settings.m_autoSplitStrings = m_page->autoSplitStrings->isChecked();
- TextEditor::TextEditorSettings::setCompletionSettings(settings);
+ TextEditor::CompletionSettings completionSettings;
+ completionSettings.m_caseSensitivity = caseSensitivity();
+ completionSettings.m_completionTrigger = completionTrigger();
+ completionSettings.m_automaticProposalTimeoutInMs
+ = m_page->automaticProposalTimeoutSpinBox->value();
+ completionSettings.m_autoInsertBrackets = m_page->autoInsertBrackets->isChecked();
+ completionSettings.m_surroundingAutoBrackets = m_page->surroundSelectedText->isChecked();
+ completionSettings.m_partiallyComplete = m_page->partiallyComplete->isChecked();
+ completionSettings.m_spaceAfterFunctionName = m_page->spaceAfterFunctionName->isChecked();
+ completionSettings.m_autoSplitStrings = m_page->autoSplitStrings->isChecked();
+ TextEditor::TextEditorSettings::setCompletionSettings(completionSettings);
if (!requireCommentsSettingsUpdate())
return;
- m_commentsSettings.m_enableDoxygen = m_page->enableDoxygenCheckBox->isChecked();
- m_commentsSettings.m_generateBrief = m_page->generateBriefCheckBox->isChecked();
- m_commentsSettings.m_leadingAsterisks = m_page->leadingAsterisksCheckBox->isChecked();
- m_commentsSettings.toSettings(QLatin1String(CPPTOOLS_SETTINGSGROUP), Core::ICore::settings());
-
- emit commentsSettingsChanged(m_commentsSettings);
+ CommentsSettings commentsSettings;
+ commentsSettings.m_enableDoxygen = m_page->enableDoxygenCheckBox->isChecked();
+ commentsSettings.m_generateBrief = m_page->generateBriefCheckBox->isChecked();
+ commentsSettings.m_leadingAsterisks = m_page->leadingAsterisksCheckBox->isChecked();
+ CppToolsSettings::instance()->setCommentsSettings(commentsSettings);
}
TextEditor::CaseSensitivity CompletionSettingsPage::caseSensitivity() const
@@ -158,6 +165,13 @@ TextEditor::CompletionTrigger CompletionSettingsPage::completionTrigger() const
}
}
+void CompletionSettingsPage::onCompletionTriggerChanged()
+{
+ const bool enableTimeoutWidgets = completionTrigger() == TextEditor::AutomaticCompletion;
+ m_page->automaticProposalTimeoutLabel->setEnabled(enableTimeoutWidgets);
+ m_page->automaticProposalTimeoutSpinBox->setEnabled(enableTimeoutWidgets);
+}
+
void CompletionSettingsPage::finish()
{
delete m_widget;
@@ -167,14 +181,10 @@ void CompletionSettingsPage::finish()
m_page = 0;
}
-const CommentsSettings &CompletionSettingsPage::commentsSettings() const
-{
- return m_commentsSettings;
-}
-
bool CompletionSettingsPage::requireCommentsSettingsUpdate() const
{
- return m_commentsSettings.m_enableDoxygen != m_page->enableDoxygenCheckBox->isChecked()
- || m_commentsSettings.m_generateBrief != m_page->generateBriefCheckBox->isChecked()
- || m_commentsSettings.m_leadingAsterisks != m_page->leadingAsterisksCheckBox->isChecked();
+ const CommentsSettings &commentsSettings = CppToolsSettings::instance()->commentsSettings();
+ return commentsSettings.m_enableDoxygen != m_page->enableDoxygenCheckBox->isChecked()
+ || commentsSettings.m_generateBrief != m_page->generateBriefCheckBox->isChecked()
+ || commentsSettings.m_leadingAsterisks != m_page->leadingAsterisksCheckBox->isChecked();
}
diff --git a/src/plugins/cpptools/completionsettingspage.h b/src/plugins/cpptools/completionsettingspage.h
index f1e22829437..dbf78f89b64 100644
--- a/src/plugins/cpptools/completionsettingspage.h
+++ b/src/plugins/cpptools/completionsettingspage.h
@@ -57,15 +57,12 @@ public:
void apply();
void finish();
- const CommentsSettings &commentsSettings() const;
-
-signals:
- void commentsSettingsChanged(const CppTools::CommentsSettings &settings);
-
private:
TextEditor::CaseSensitivity caseSensitivity() const;
TextEditor::CompletionTrigger completionTrigger() const;
+ void onCompletionTriggerChanged();
+
bool requireCommentsSettingsUpdate() const;
Ui::CompletionSettingsPage *m_page;
diff --git a/src/plugins/cpptools/completionsettingspage.ui b/src/plugins/cpptools/completionsettingspage.ui
index 83605b43560..a03db2255c7 100644
--- a/src/plugins/cpptools/completionsettingspage.ui
+++ b/src/plugins/cpptools/completionsettingspage.ui
@@ -17,10 +17,10 @@
<string>Behavior</string>
</property>
<layout class="QGridLayout" name="gridLayout">
- <item row="4" column="0">
- <layout class="QHBoxLayout" name="horizontalLayout">
+ <item row="5" column="0">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
- <spacer name="horizontalSpacer_2">
+ <spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
@@ -36,53 +36,17 @@
</spacer>
</item>
<item>
- <widget class="QCheckBox" name="surroundSelectedText">
- <property name="toolTip">
- <string>When typing a matching character and there is a text selection, instead of removing the selection, surrounds it with the corresponding characters.</string>
+ <widget class="QCheckBox" name="spaceAfterFunctionName">
+ <property name="enabled">
+ <bool>true</bool>
</property>
<property name="text">
- <string>Surround &amp;text selections</string>
- </property>
- <property name="checked">
- <bool>true</bool>
+ <string>Insert &amp;space after function name</string>
</property>
</widget>
</item>
</layout>
</item>
- <item row="0" column="2" colspan="2">
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>70</width>
- <height>24</height>
- </size>
- </property>
- </spacer>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="completionTriggerLabel">
- <property name="text">
- <string>Activate completion:</string>
- </property>
- </widget>
- </item>
- <item row="1" column="3">
- <spacer name="horizontalSpacer_3">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>24</height>
- </size>
- </property>
- </spacer>
- </item>
<item row="0" column="0">
<widget class="QLabel" name="caseSensitivityLabel">
<property name="text">
@@ -118,13 +82,77 @@
</item>
</widget>
</item>
+ <item row="4" column="0">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>30</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="surroundSelectedText">
+ <property name="toolTip">
+ <string>When typing a matching character and there is a text selection, instead of removing the selection, surrounds it with the corresponding characters.</string>
+ </property>
+ <property name="text">
+ <string>Surround &amp;text selections</string>
+ </property>
+ <property name="checked">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
<item row="6" column="0">
<widget class="QCheckBox" name="autoSplitStrings">
+ <property name="toolTip">
+ <string>Splits a string into two lines by adding an end quote at the cursor position when you press Enter and a start quote to the next line, before the rest of the string.
+
+In addition, Shift+Enter inserts an escape character at the cursor position and moves the rest of the string to the next line.</string>
+ </property>
<property name="text">
<string>Automatically split strings</string>
</property>
</widget>
</item>
+ <item row="1" column="5">
+ <spacer name="horizontalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>24</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="0" column="2" colspan="4">
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>70</width>
+ <height>24</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
<item row="1" column="1" colspan="2">
<widget class="QComboBox" name="completionTrigger">
<item>
@@ -144,6 +172,13 @@
</item>
</widget>
</item>
+ <item row="1" column="3">
+ <widget class="QLabel" name="automaticProposalTimeoutLabel">
+ <property name="text">
+ <string>Timeout in ms:</string>
+ </property>
+ </widget>
+ </item>
<item row="2" column="0">
<widget class="QCheckBox" name="partiallyComplete">
<property name="toolTip">
@@ -157,6 +192,13 @@
</property>
</widget>
</item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="completionTriggerLabel">
+ <property name="text">
+ <string>Activate completion:</string>
+ </property>
+ </widget>
+ </item>
<item row="3" column="0" colspan="2">
<widget class="QCheckBox" name="autoInsertBrackets">
<property name="toolTip">
@@ -170,35 +212,18 @@
</property>
</widget>
</item>
- <item row="5" column="0">
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <spacer name="horizontalSpacer_4">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::Fixed</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>30</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item>
- <widget class="QCheckBox" name="spaceAfterFunctionName">
- <property name="enabled">
- <bool>true</bool>
- </property>
- <property name="text">
- <string>Insert &amp;space after function name</string>
- </property>
- </widget>
- </item>
- </layout>
+ <item row="1" column="4">
+ <widget class="QSpinBox" name="automaticProposalTimeoutSpinBox">
+ <property name="maximum">
+ <number>500</number>
+ </property>
+ <property name="singleStep">
+ <number>50</number>
+ </property>
+ <property name="value">
+ <number>400</number>
+ </property>
+ </widget>
</item>
</layout>
</widget>
diff --git a/src/plugins/cpptools/cppcodeformatter.cpp b/src/plugins/cpptools/cppcodeformatter.cpp
index f11462a7ff3..d888b22622c 100644
--- a/src/plugins/cpptools/cppcodeformatter.cpp
+++ b/src/plugins/cpptools/cppcodeformatter.cpp
@@ -703,7 +703,7 @@ int CodeFormatter::tokenCount() const
return m_tokens.size();
}
-const CPlusPlus::Token &CodeFormatter::currentToken() const
+const Token &CodeFormatter::currentToken() const
{
return m_currentToken;
}
@@ -1111,7 +1111,7 @@ void CodeFormatter::dump() const
namespace CppTools {
namespace Internal {
- class CppCodeFormatterData: public TextEditor::CodeFormatterData
+ class CppCodeFormatterData: public CodeFormatterData
{
public:
CodeFormatter::BlockData m_data;
@@ -1123,7 +1123,7 @@ QtStyleCodeFormatter::QtStyleCodeFormatter()
{
}
-QtStyleCodeFormatter::QtStyleCodeFormatter(const TextEditor::TabSettings &tabSettings,
+QtStyleCodeFormatter::QtStyleCodeFormatter(const TabSettings &tabSettings,
const CppCodeStyleSettings &settings)
: m_tabSettings(tabSettings)
, m_styleSettings(settings)
@@ -1131,7 +1131,7 @@ QtStyleCodeFormatter::QtStyleCodeFormatter(const TextEditor::TabSettings &tabSet
setTabSize(tabSettings.m_tabSize);
}
-void QtStyleCodeFormatter::setTabSettings(const TextEditor::TabSettings &tabSettings)
+void QtStyleCodeFormatter::setTabSettings(const TabSettings &tabSettings)
{
m_tabSettings = tabSettings;
setTabSize(tabSettings.m_tabSize);
diff --git a/src/plugins/cpptools/cppcodegen_test.cpp b/src/plugins/cpptools/cppcodegen_test.cpp
index f8f84e0be37..89161bcdb57 100644
--- a/src/plugins/cpptools/cppcodegen_test.cpp
+++ b/src/plugins/cpptools/cppcodegen_test.cpp
@@ -33,6 +33,7 @@
#include "insertionpointlocator.h"
#include <utils/fileutils.h>
+#include <utils/qtcassert.h>
#include <QtTest>
#include <QDebug>
@@ -46,6 +47,34 @@ using namespace CPlusPlus;
using namespace CppTools;
using namespace CppTools::Internal;
+namespace {
+
+Document::Ptr createDocument(const QString filePath, const QByteArray text,
+ unsigned expectedGlobalSymbolCount)
+{
+ Document::Ptr document = Document::create(filePath);
+ document->setUtf8Source(text);
+ document->check();
+ QTC_ASSERT(document->diagnosticMessages().isEmpty(), return Document::Ptr());
+ QTC_ASSERT(document->globalSymbolCount() == expectedGlobalSymbolCount, return Document::Ptr());
+
+ return document;
+}
+
+Document::Ptr createDocumentAndFile(Tests::TemporaryDir *temporaryDir,
+ const QByteArray relativeFilePath,
+ const QByteArray text,
+ unsigned expectedGlobalSymbolCount)
+{
+ QTC_ASSERT(temporaryDir, return Document::Ptr());
+ const QString absoluteFilePath = temporaryDir->createFile(relativeFilePath, text);
+ QTC_ASSERT(!absoluteFilePath.isEmpty(), return Document::Ptr());
+
+ return createDocument(absoluteFilePath, text, expectedGlobalSymbolCount);
+}
+
+} // anonymous namespace
+
/*!
Should insert at line 3, column 1, with "public:\n" as prefix and without suffix.
*/
@@ -56,14 +85,8 @@ void CppToolsPlugin::test_codegen_public_in_empty_class()
"{\n"
"};\n"
"\n";
-
- Document::Ptr doc = Document::create(QLatin1String("public_in_empty_class"));
- doc->setUtf8Source(src);
- doc->parse();
- doc->check();
-
- QCOMPARE(doc->diagnosticMessages().size(), 0);
- QCOMPARE(doc->globalSymbolCount(), 1U);
+ Document::Ptr doc = createDocument(QLatin1String("public_in_empty_class"), src, 1U);
+ QVERIFY(doc);
Class *foo = doc->globalSymbolAt(0)->asClass();
QVERIFY(foo);
@@ -96,14 +119,8 @@ void CppToolsPlugin::test_codegen_public_in_nonempty_class()
"public:\n" // line 3
"};\n" // line 4
"\n";
-
- Document::Ptr doc = Document::create(QLatin1String("public_in_nonempty_class"));
- doc->setUtf8Source(src);
- doc->parse();
- doc->check();
-
- QCOMPARE(doc->diagnosticMessages().size(), 0);
- QCOMPARE(doc->globalSymbolCount(), 1U);
+ Document::Ptr doc = createDocument(QLatin1String("public_in_nonempty_class"), src, 1U);
+ QVERIFY(doc);
Class *foo = doc->globalSymbolAt(0)->asClass();
QVERIFY(foo);
@@ -136,14 +153,8 @@ void CppToolsPlugin::test_codegen_public_before_protected()
"protected:\n" // line 3
"};\n"
"\n";
-
- Document::Ptr doc = Document::create(QLatin1String("public_before_protected"));
- doc->setUtf8Source(src);
- doc->parse();
- doc->check();
-
- QCOMPARE(doc->diagnosticMessages().size(), 0);
- QCOMPARE(doc->globalSymbolCount(), 1U);
+ Document::Ptr doc = createDocument(QLatin1String("public_before_protected"), src, 1U);
+ QVERIFY(doc);
Class *foo = doc->globalSymbolAt(0)->asClass();
QVERIFY(foo);
@@ -177,14 +188,8 @@ void CppToolsPlugin::test_codegen_private_after_protected()
"protected:\n" // line 3
"};\n"
"\n";
-
- Document::Ptr doc = Document::create(QLatin1String("private_after_protected"));
- doc->setUtf8Source(src);
- doc->parse();
- doc->check();
-
- QCOMPARE(doc->diagnosticMessages().size(), 0);
- QCOMPARE(doc->globalSymbolCount(), 1U);
+ Document::Ptr doc = createDocument(QLatin1String("private_after_protected"), src, 1U);
+ QVERIFY(doc);
Class *foo = doc->globalSymbolAt(0)->asClass();
QVERIFY(foo);
@@ -218,14 +223,8 @@ void CppToolsPlugin::test_codegen_protected_in_nonempty_class()
"public:\n" // line 3
"};\n" // line 4
"\n";
-
- Document::Ptr doc = Document::create(QLatin1String("protected_in_nonempty_class"));
- doc->setUtf8Source(src);
- doc->parse();
- doc->check();
-
- QCOMPARE(doc->diagnosticMessages().size(), 0);
- QCOMPARE(doc->globalSymbolCount(), 1U);
+ Document::Ptr doc = createDocument(QLatin1String("protected_in_nonempty_class"), src, 1U);
+ QVERIFY(doc);
Class *foo = doc->globalSymbolAt(0)->asClass();
QVERIFY(foo);
@@ -259,14 +258,8 @@ void CppToolsPlugin::test_codegen_protected_between_public_and_private()
"private:\n" // line 4
"};\n" // line 5
"\n";
-
- Document::Ptr doc = Document::create(QLatin1String("protected_betwee_public_and_private"));
- doc->setUtf8Source(src);
- doc->parse();
- doc->check();
-
- QCOMPARE(doc->diagnosticMessages().size(), 0);
- QCOMPARE(doc->globalSymbolCount(), 1U);
+ Document::Ptr doc = createDocument(QLatin1String("protected_betwee_public_and_private"), src, 1U);
+ QVERIFY(doc);
Class *foo = doc->globalSymbolAt(0)->asClass();
QVERIFY(foo);
@@ -321,13 +314,8 @@ void CppToolsPlugin::test_codegen_qtdesigner_integration()
"\n"
"#endif // MAINWINDOW_H\n";
- Document::Ptr doc = Document::create(QLatin1String("qtdesigner_integration"));
- doc->setUtf8Source(src);
- doc->parse();
- doc->check();
-
- QCOMPARE(doc->diagnosticMessages().size(), 0);
- QCOMPARE(doc->globalSymbolCount(), 2U);
+ Document::Ptr doc = createDocument(QLatin1String("qtdesigner_integration"), src, 2U);
+ QVERIFY(doc);
Class *foo = doc->globalSymbolAt(1)->asClass();
QVERIFY(foo);
@@ -351,38 +339,29 @@ void CppToolsPlugin::test_codegen_qtdesigner_integration()
void CppToolsPlugin::test_codegen_definition_empty_class()
{
- const QByteArray srcText = "\n"
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
+ const QByteArray headerText = "\n"
"class Foo\n" // line 1
"{\n"
"void foo();\n" // line 3
"};\n"
"\n";
+ Document::Ptr headerDocument = createDocumentAndFile(&temporaryDir, "file.h", headerText, 1U);
+ QVERIFY(headerDocument);
- const QByteArray dstText = "\n"
+ const QByteArray sourceText = "\n"
"int x;\n" // line 1
"\n";
-
- Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
- QVERIFY(CppTools::Tests::TestCase::writeFile(src->fileName(), srcText));
- src->setUtf8Source(srcText);
- src->parse();
- src->check();
- QCOMPARE(src->diagnosticMessages().size(), 0);
- QCOMPARE(src->globalSymbolCount(), 1U);
-
- Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
- QVERIFY(CppTools::Tests::TestCase::writeFile(dst->fileName(), dstText));
- dst->setUtf8Source(dstText);
- dst->parse();
- dst->check();
- QCOMPARE(dst->diagnosticMessages().size(), 0);
- QCOMPARE(dst->globalSymbolCount(), 1U);
+ Document::Ptr sourceDocument = createDocumentAndFile(&temporaryDir, "file.cpp", sourceText, 1U);
+ QVERIFY(sourceDocument);
Snapshot snapshot;
- snapshot.insert(src);
- snapshot.insert(dst);
+ snapshot.insert(headerDocument);
+ snapshot.insert(sourceDocument);
- Class *foo = src->globalSymbolAt(0)->asClass();
+ Class *foo = headerDocument->globalSymbolAt(0)->asClass();
QVERIFY(foo);
QCOMPARE(foo->line(), 1U);
QCOMPARE(foo->column(), 7U);
@@ -397,7 +376,7 @@ void CppToolsPlugin::test_codegen_definition_empty_class()
QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first();
- QCOMPARE(loc.fileName(), dst->fileName());
+ QCOMPARE(loc.fileName(), sourceDocument->fileName());
QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
QCOMPARE(loc.suffix(), QString());
QCOMPARE(loc.line(), 3U);
@@ -406,49 +385,41 @@ void CppToolsPlugin::test_codegen_definition_empty_class()
void CppToolsPlugin::test_codegen_definition_first_member()
{
- const QByteArray srcText = "\n"
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
+ const QByteArray headerText = "\n"
"class Foo\n" // line 1
"{\n"
"void foo();\n" // line 3
"void bar();\n" // line 4
"};\n"
"\n";
+ Document::Ptr headerDocument = createDocumentAndFile(&temporaryDir, "file.h", headerText, 1U);
+ QVERIFY(headerDocument);
- const QByteArray dstText = QString::fromLatin1(
- "\n"
- "#include \"%1/file.h\"\n" // line 1
- "int x;\n"
- "\n"
- "void Foo::bar()\n" // line 4
- "{\n"
- "\n"
- "}\n"
- "\n"
- "int y;\n").arg(QDir::tempPath()).toLatin1();
-
- Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
- QVERIFY(CppTools::Tests::TestCase::writeFile(src->fileName(), srcText));
- src->setUtf8Source(srcText);
- src->parse();
- src->check();
- QCOMPARE(src->diagnosticMessages().size(), 0);
- QCOMPARE(src->globalSymbolCount(), 1U);
-
- Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
- dst->addIncludeFile(Document::Include(QLatin1String("file.h"), src->fileName(), 1,
- Client::IncludeLocal));
- QVERIFY(CppTools::Tests::TestCase::writeFile(dst->fileName(), dstText));
- dst->setUtf8Source(dstText);
- dst->parse();
- dst->check();
- QCOMPARE(dst->diagnosticMessages().size(), 0);
- QCOMPARE(dst->globalSymbolCount(), 3U);
+ const QByteArray sourceText = QString::fromLatin1(
+ "\n"
+ "#include \"%1/file.h\"\n" // line 1
+ "int x;\n"
+ "\n"
+ "void Foo::bar()\n" // line 4
+ "{\n"
+ "\n"
+ "}\n"
+ "\n"
+ "int y;\n").arg(temporaryDir.path()).toLatin1();
+ Document::Ptr sourceDocument = createDocumentAndFile(&temporaryDir, "file.cpp", sourceText, 3U);
+ QVERIFY(sourceDocument);
+ sourceDocument->addIncludeFile(Document::Include(QLatin1String("file.h"),
+ headerDocument->fileName(), 1,
+ Client::IncludeLocal));
Snapshot snapshot;
- snapshot.insert(src);
- snapshot.insert(dst);
+ snapshot.insert(headerDocument);
+ snapshot.insert(sourceDocument);
- Class *foo = src->globalSymbolAt(0)->asClass();
+ Class *foo = headerDocument->globalSymbolAt(0)->asClass();
QVERIFY(foo);
QCOMPARE(foo->line(), 1U);
QCOMPARE(foo->column(), 7U);
@@ -463,7 +434,7 @@ void CppToolsPlugin::test_codegen_definition_first_member()
QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first();
- QCOMPARE(loc.fileName(), dst->fileName());
+ QCOMPARE(loc.fileName(), sourceDocument->fileName());
QCOMPARE(loc.line(), 4U);
QCOMPARE(loc.column(), 1U);
QCOMPARE(loc.suffix(), QLatin1String("\n\n"));
@@ -472,49 +443,42 @@ void CppToolsPlugin::test_codegen_definition_first_member()
void CppToolsPlugin::test_codegen_definition_last_member()
{
- const QByteArray srcText = "\n"
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
+ const QByteArray headerText = "\n"
"class Foo\n" // line 1
"{\n"
"void foo();\n" // line 3
"void bar();\n" // line 4
"};\n"
"\n";
+ Document::Ptr headerDocument = createDocumentAndFile(&temporaryDir, "file.h", headerText, 1U);
+ QVERIFY(headerDocument);
- const QByteArray dstText = QString::fromLatin1(
- "\n"
- "#include \"%1/file.h\"\n" // line 1
- "int x;\n"
- "\n"
- "void Foo::foo()\n" // line 4
- "{\n"
- "\n"
- "}\n" // line 7
- "\n"
- "int y;\n").arg(QDir::tempPath()).toLatin1();
-
- Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
- QVERIFY(CppTools::Tests::TestCase::writeFile(src->fileName(), srcText));
- src->setUtf8Source(srcText);
- src->parse();
- src->check();
- QCOMPARE(src->diagnosticMessages().size(), 0);
- QCOMPARE(src->globalSymbolCount(), 1U);
-
- Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
- dst->addIncludeFile(Document::Include(QLatin1String("file.h"), src->fileName(), 1,
- Client::IncludeLocal));
- QVERIFY(CppTools::Tests::TestCase::writeFile(dst->fileName(), dstText));
- dst->setUtf8Source(dstText);
- dst->parse();
- dst->check();
- QCOMPARE(dst->diagnosticMessages().size(), 0);
- QCOMPARE(dst->globalSymbolCount(), 3U);
+ const QByteArray sourceText = QString::fromLatin1(
+ "\n"
+ "#include \"%1/file.h\"\n" // line 1
+ "int x;\n"
+ "\n"
+ "void Foo::foo()\n" // line 4
+ "{\n"
+ "\n"
+ "}\n" // line 7
+ "\n"
+ "int y;\n").arg(temporaryDir.path()).toLatin1();
+
+ Document::Ptr sourceDocument = createDocumentAndFile(&temporaryDir, "file.cpp", sourceText, 3U);
+ QVERIFY(sourceDocument);
+ sourceDocument->addIncludeFile(Document::Include(QLatin1String("file.h"),
+ headerDocument->fileName(), 1,
+ Client::IncludeLocal));
Snapshot snapshot;
- snapshot.insert(src);
- snapshot.insert(dst);
+ snapshot.insert(headerDocument);
+ snapshot.insert(sourceDocument);
- Class *foo = src->globalSymbolAt(0)->asClass();
+ Class *foo = headerDocument->globalSymbolAt(0)->asClass();
QVERIFY(foo);
QCOMPARE(foo->line(), 1U);
QCOMPARE(foo->column(), 7U);
@@ -529,7 +493,7 @@ void CppToolsPlugin::test_codegen_definition_last_member()
QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first();
- QCOMPARE(loc.fileName(), dst->fileName());
+ QCOMPARE(loc.fileName(), sourceDocument->fileName());
QCOMPARE(loc.line(), 7U);
QCOMPARE(loc.column(), 2U);
QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
@@ -538,7 +502,10 @@ void CppToolsPlugin::test_codegen_definition_last_member()
void CppToolsPlugin::test_codegen_definition_middle_member()
{
- const QByteArray srcText = "\n"
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
+ const QByteArray headerText = "\n"
"class Foo\n" // line 1
"{\n"
"void foo();\n" // line 3
@@ -547,46 +514,37 @@ void CppToolsPlugin::test_codegen_definition_middle_member()
"};\n"
"\n";
- const QByteArray dstText = QString::fromLatin1(
- "\n"
- "#include \"%1/file.h\"\n" // line 1
- "int x;\n"
- "\n"
- "void Foo::foo()\n" // line 4
- "{\n"
- "\n"
- "}\n" // line 7
- "\n"
- "void Foo::car()\n" // line 9
- "{\n"
- "\n"
- "}\n"
- "\n"
- "int y;\n").arg(QDir::tempPath()).toLatin1();
-
- Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
- QVERIFY(CppTools::Tests::TestCase::writeFile(src->fileName(), srcText));
- src->setUtf8Source(srcText);
- src->parse();
- src->check();
- QCOMPARE(src->diagnosticMessages().size(), 0);
- QCOMPARE(src->globalSymbolCount(), 1U);
-
- Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
- dst->addIncludeFile(Document::Include(QLatin1String("file.h"), src->fileName(), 1,
- Client::IncludeLocal));
- QVERIFY(CppTools::Tests::TestCase::writeFile(dst->fileName(), dstText));
- dst->setUtf8Source(dstText);
- dst->parse();
- dst->check();
- QCOMPARE(dst->diagnosticMessages().size(), 0);
- QCOMPARE(dst->globalSymbolCount(), 4U);
+ Document::Ptr headerDocument = createDocumentAndFile(&temporaryDir, "file.h", headerText, 1U);
+ QVERIFY(headerDocument);
+
+ const QByteArray sourceText = QString::fromLatin1(
+ "\n"
+ "#include \"%1/file.h\"\n" // line 1
+ "int x;\n"
+ "\n"
+ "void Foo::foo()\n" // line 4
+ "{\n"
+ "\n"
+ "}\n" // line 7
+ "\n"
+ "void Foo::car()\n" // line 9
+ "{\n"
+ "\n"
+ "}\n"
+ "\n"
+ "int y;\n").arg(QDir::tempPath()).toLatin1();
+
+ Document::Ptr sourceDocument = createDocumentAndFile(&temporaryDir, "file.cpp", sourceText, 4U);
+ QVERIFY(sourceDocument);
+ sourceDocument->addIncludeFile(Document::Include(QLatin1String("file.h"),
+ headerDocument->fileName(), 1,
+ Client::IncludeLocal));
Snapshot snapshot;
- snapshot.insert(src);
- snapshot.insert(dst);
+ snapshot.insert(headerDocument);
+ snapshot.insert(sourceDocument);
- Class *foo = src->globalSymbolAt(0)->asClass();
+ Class *foo = headerDocument->globalSymbolAt(0)->asClass();
QVERIFY(foo);
QCOMPARE(foo->line(), 1U);
QCOMPARE(foo->column(), 7U);
@@ -601,7 +559,7 @@ void CppToolsPlugin::test_codegen_definition_middle_member()
QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first();
- QCOMPARE(loc.fileName(), dst->fileName());
+ QCOMPARE(loc.fileName(), sourceDocument->fileName());
QCOMPARE(loc.line(), 7U);
QCOMPARE(loc.column(), 2U);
QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
@@ -610,7 +568,10 @@ void CppToolsPlugin::test_codegen_definition_middle_member()
void CppToolsPlugin::test_codegen_definition_middle_member_surrounded_by_undefined()
{
- const QByteArray srcText = "\n"
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
+ const QByteArray headerText = "\n"
"class Foo\n" // line 1
"{\n"
"void foo();\n" // line 3
@@ -619,8 +580,10 @@ void CppToolsPlugin::test_codegen_definition_middle_member_surrounded_by_undefin
"void car();\n" // line 6
"};\n"
"\n";
+ Document::Ptr headerDocument = createDocumentAndFile(&temporaryDir, "file.h", headerText, 1U);
+ QVERIFY(headerDocument);
- const QByteArray dstText = QString::fromLatin1(
+ const QByteArray sourceText = QString::fromLatin1(
"\n"
"#include \"%1/file.h\"\n" // line 1
"int x;\n"
@@ -630,31 +593,18 @@ void CppToolsPlugin::test_codegen_definition_middle_member_surrounded_by_undefin
"\n"
"}\n"
"\n"
- "int y;\n").arg(QDir::tempPath()).toLatin1();
-
- Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
- QVERIFY(CppTools::Tests::TestCase::writeFile(src->fileName(), srcText));
- src->setUtf8Source(srcText);
- src->parse();
- src->check();
- QCOMPARE(src->diagnosticMessages().size(), 0);
- QCOMPARE(src->globalSymbolCount(), 1U);
-
- Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
- dst->addIncludeFile(Document::Include(QLatin1String("file.h"), src->fileName(), 1,
- Client::IncludeLocal));
- QVERIFY(CppTools::Tests::TestCase::writeFile(dst->fileName(), dstText));
- dst->setUtf8Source(dstText);
- dst->parse();
- dst->check();
- QCOMPARE(dst->diagnosticMessages().size(), 0);
- QCOMPARE(dst->globalSymbolCount(), 3U);
+ "int y;\n").arg(temporaryDir.path()).toLatin1();
+ Document::Ptr sourceDocument = createDocumentAndFile(&temporaryDir, "file.cpp", sourceText, 3U);
+ QVERIFY(sourceDocument);
+ sourceDocument->addIncludeFile(Document::Include(QLatin1String("file.h"),
+ headerDocument->fileName(), 1,
+ Client::IncludeLocal));
Snapshot snapshot;
- snapshot.insert(src);
- snapshot.insert(dst);
+ snapshot.insert(headerDocument);
+ snapshot.insert(sourceDocument);
- Class *foo = src->globalSymbolAt(0)->asClass();
+ Class *foo = headerDocument->globalSymbolAt(0)->asClass();
QVERIFY(foo);
QCOMPARE(foo->line(), 1U);
QCOMPARE(foo->column(), 7U);
@@ -669,7 +619,7 @@ void CppToolsPlugin::test_codegen_definition_middle_member_surrounded_by_undefin
QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first();
- QCOMPARE(loc.fileName(), dst->fileName());
+ QCOMPARE(loc.fileName(), sourceDocument->fileName());
QCOMPARE(loc.line(), 4U);
QCOMPARE(loc.column(), 1U);
QCOMPARE(loc.prefix(), QString());
@@ -678,7 +628,10 @@ void CppToolsPlugin::test_codegen_definition_middle_member_surrounded_by_undefin
void CppToolsPlugin::test_codegen_definition_member_specific_file()
{
- const QByteArray srcText = "\n"
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
+ const QByteArray headerText = "\n"
"class Foo\n" // line 1
"{\n"
"void foo();\n" // line 3
@@ -690,42 +643,31 @@ void CppToolsPlugin::test_codegen_definition_member_specific_file()
"{\n"
"\n"
"}\n";
+ Document::Ptr headerDocument = createDocumentAndFile(&temporaryDir, "file.h", headerText, 2U);
+ QVERIFY(headerDocument);
- const QByteArray dstText = QString::fromLatin1(
- "\n"
- "#include \"%1/file.h\"\n" // line 1
- "int x;\n"
- "\n"
- "void Foo::foo()\n" // line 4
- "{\n"
- "\n"
- "}\n" // line 7
- "\n"
- "int y;\n").arg(QDir::tempPath()).toLatin1();
-
- Document::Ptr src = Document::create(QDir::tempPath() + QLatin1String("/file.h"));
- QVERIFY(CppTools::Tests::TestCase::writeFile(src->fileName(), srcText));
- src->setUtf8Source(srcText);
- src->parse();
- src->check();
- QCOMPARE(src->diagnosticMessages().size(), 0);
- QCOMPARE(src->globalSymbolCount(), 2U);
-
- Document::Ptr dst = Document::create(QDir::tempPath() + QLatin1String("/file.cpp"));
- dst->addIncludeFile(Document::Include(QLatin1String("file.h"), src->fileName(), 1,
- Client::IncludeLocal));
- QVERIFY(CppTools::Tests::TestCase::writeFile(dst->fileName(), dstText));
- dst->setUtf8Source(dstText);
- dst->parse();
- dst->check();
- QCOMPARE(dst->diagnosticMessages().size(), 0);
- QCOMPARE(dst->globalSymbolCount(), 3U);
+ const QByteArray sourceText = QString::fromLatin1(
+ "\n"
+ "#include \"%1/file.h\"\n" // line 1
+ "int x;\n"
+ "\n"
+ "void Foo::foo()\n" // line 4
+ "{\n"
+ "\n"
+ "}\n" // line 7
+ "\n"
+ "int y;\n").arg(temporaryDir.path()).toLatin1();
+ Document::Ptr sourceDocument = createDocumentAndFile(&temporaryDir, "file.cpp", sourceText, 3U);
+ QVERIFY(sourceDocument);
+ sourceDocument->addIncludeFile(Document::Include(QLatin1String("file.h"),
+ headerDocument->fileName(), 1,
+ Client::IncludeLocal));
Snapshot snapshot;
- snapshot.insert(src);
- snapshot.insert(dst);
+ snapshot.insert(headerDocument);
+ snapshot.insert(sourceDocument);
- Class *foo = src->globalSymbolAt(0)->asClass();
+ Class *foo = headerDocument->globalSymbolAt(0)->asClass();
QVERIFY(foo);
QCOMPARE(foo->line(), 1U);
QCOMPARE(foo->column(), 7U);
@@ -737,10 +679,10 @@ void CppToolsPlugin::test_codegen_definition_member_specific_file()
CppRefactoringChanges changes(snapshot);
InsertionPointLocator find(changes);
- QList<InsertionLocation> locList = find.methodDefinition(decl, true, dst->fileName());
+ QList<InsertionLocation> locList = find.methodDefinition(decl, true, sourceDocument->fileName());
QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first();
- QCOMPARE(loc.fileName(), dst->fileName());
+ QCOMPARE(loc.fileName(), sourceDocument->fileName());
QCOMPARE(loc.line(), 7U);
QCOMPARE(loc.column(), 2U);
QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
diff --git a/src/plugins/cpptools/cppcodemodelinspectordumper.cpp b/src/plugins/cpptools/cppcodemodelinspectordumper.cpp
index ad831e962ed..11bfdfa793e 100644
--- a/src/plugins/cpptools/cppcodemodelinspectordumper.cpp
+++ b/src/plugins/cpptools/cppcodemodelinspectordumper.cpp
@@ -580,10 +580,10 @@ void Dumper::dumpWorkingCopy(const WorkingCopy &workingCopy)
m_out << "Working Copy contains " << workingCopy.size() << " entries{{{1\n";
const QByteArray i1 = indent(1);
- QHashIterator<QString, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
+ QHashIterator< ::Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
while (it.hasNext()) {
it.next();
- const QString filePath = it.key();
+ const ::Utils::FileName &filePath = it.key();
unsigned sourcRevision = it.value().second;
m_out << i1 << "rev=" << sourcRevision << ", " << filePath << "\n";
}
diff --git a/src/plugins/cpptools/cppcodestylepreferences.cpp b/src/plugins/cpptools/cppcodestylepreferences.cpp
index 9603c67fd1b..1ca57f9e6b6 100644
--- a/src/plugins/cpptools/cppcodestylepreferences.cpp
+++ b/src/plugins/cpptools/cppcodestylepreferences.cpp
@@ -37,8 +37,8 @@ static const char settingsSuffixKey[] = "CodeStyleSettings";
CppCodeStylePreferences::CppCodeStylePreferences(QObject *parent) :
ICodeStylePreferences(parent)
{
- connect(this, SIGNAL(currentValueChanged(QVariant)),
- this, SLOT(slotCurrentValueChanged(QVariant)));
+ connect(this, &CppCodeStylePreferences::currentValueChanged,
+ this, &CppCodeStylePreferences::slotCurrentValueChanged);
}
QVariant CppCodeStylePreferences::value() const
diff --git a/src/plugins/cpptools/cppcodestylesettings.cpp b/src/plugins/cpptools/cppcodestylesettings.cpp
index 5712e43048a..7e9ce21c591 100644
--- a/src/plugins/cpptools/cppcodestylesettings.cpp
+++ b/src/plugins/cpptools/cppcodestylesettings.cpp
@@ -36,7 +36,7 @@
#include <projectexplorer/editorconfiguration.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <utils/qtcassert.h>
#include <utils/settingsutils.h>
@@ -210,7 +210,7 @@ static void configureOverviewWithCodeStyleSettings(CPlusPlus::Overview &overview
CPlusPlus::Overview CppCodeStyleSettings::currentProjectCodeStyleOverview()
{
- ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ ProjectExplorer::Project *project = ProjectExplorer::ProjectTree::currentProject();
if (!project)
return currentGlobalCodeStyleOverview();
diff --git a/src/plugins/cpptools/cppcodestylesettingspage.cpp b/src/plugins/cpptools/cppcodestylesettingspage.cpp
index 2dcb1da3b0e..7ed6805ee1d 100644
--- a/src/plugins/cpptools/cppcodestylesettingspage.cpp
+++ b/src/plugins/cpptools/cppcodestylesettingspage.cpp
@@ -221,7 +221,7 @@ namespace CppTools {
namespace Internal {
-static void applyRefactorings(QTextDocument *textDocument, TextEditor::TextEditorWidget *editor,
+static void applyRefactorings(QTextDocument *textDocument, TextEditorWidget *editor,
const CppCodeStyleSettings &settings)
{
// Preprocess source
@@ -282,48 +282,48 @@ CppCodeStylePreferencesWidget::CppCodeStylePreferencesWidget(QWidget *parent)
setVisualizeWhitespace(true);
- connect(m_ui->tabSettingsWidget, SIGNAL(settingsChanged(TextEditor::TabSettings)),
- this, SLOT(slotTabSettingsChanged(TextEditor::TabSettings)));
- connect(m_ui->indentBlockBraces, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentBlockBody, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentClassBraces, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentNamespaceBraces, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentEnumBraces, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentNamespaceBody, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentSwitchLabels, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentCaseStatements, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentCaseBlocks, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentCaseBreak, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentAccessSpecifiers, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentDeclarationsRelativeToAccessSpecifiers, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentFunctionBody, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->indentFunctionBraces, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->extraPaddingConditions, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->alignAssignments, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->bindStarToIdentifier, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->bindStarToTypeName, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->bindStarToLeftSpecifier, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
- connect(m_ui->bindStarToRightSpecifier, SIGNAL(toggled(bool)),
- this, SLOT(slotCodeStyleSettingsChanged()));
+ connect(m_ui->tabSettingsWidget, &TabSettingsWidget::settingsChanged,
+ this, &CppCodeStylePreferencesWidget::slotTabSettingsChanged);
+ connect(m_ui->indentBlockBraces, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentBlockBody, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentClassBraces, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentNamespaceBraces, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentEnumBraces, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentNamespaceBody, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentSwitchLabels, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentCaseStatements, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentCaseBlocks, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentCaseBreak, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentAccessSpecifiers, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentDeclarationsRelativeToAccessSpecifiers, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentFunctionBody, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->indentFunctionBraces, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->extraPaddingConditions, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->alignAssignments, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->bindStarToIdentifier, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->bindStarToTypeName, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->bindStarToLeftSpecifier, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
+ connect(m_ui->bindStarToRightSpecifier, &QCheckBox::toggled,
+ this, &CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged);
m_ui->categoryTab->setCurrentIndex(0);
@@ -340,8 +340,8 @@ void CppCodeStylePreferencesWidget::setCodeStyle(CppTools::CppCodeStylePreferenc
// code preferences
m_preferences = codeStylePreferences;
- connect(m_preferences, SIGNAL(currentTabSettingsChanged(TextEditor::TabSettings)),
- this, SLOT(setTabSettings(TextEditor::TabSettings)));
+ connect(m_preferences, &CppCodeStylePreferences::currentTabSettingsChanged,
+ this, &CppCodeStylePreferencesWidget::setTabSettings);
connect(m_preferences, SIGNAL(currentCodeStyleSettingsChanged(CppTools::CppCodeStyleSettings)),
this, SLOT(setCodeStyleSettings(CppTools::CppCodeStyleSettings)));
connect(m_preferences, SIGNAL(currentPreferencesChanged(TextEditor::ICodeStylePreferences*)),
@@ -382,7 +382,7 @@ CppCodeStyleSettings CppCodeStylePreferencesWidget::cppCodeStyleSettings() const
return set;
}
-void CppCodeStylePreferencesWidget::setTabSettings(const TextEditor::TabSettings &settings)
+void CppCodeStylePreferencesWidget::setTabSettings(const TabSettings &settings)
{
m_ui->tabSettingsWidget->setTabSettings(settings);
}
@@ -416,7 +416,7 @@ void CppCodeStylePreferencesWidget::setCodeStyleSettings(const CppCodeStyleSetti
updatePreview();
}
-void CppCodeStylePreferencesWidget::slotCurrentPreferencesChanged(TextEditor::ICodeStylePreferences *preferences, bool preview)
+void CppCodeStylePreferencesWidget::slotCurrentPreferencesChanged(ICodeStylePreferences *preferences, bool preview)
{
const bool enable = !preferences->isReadOnly() && !m_preferences->currentDelegate();
m_ui->tabSettingsWidget->setEnabled(enable);
@@ -443,7 +443,7 @@ void CppCodeStylePreferencesWidget::slotCodeStyleSettingsChanged()
updatePreview();
}
-void CppCodeStylePreferencesWidget::slotTabSettingsChanged(const TextEditor::TabSettings &settings)
+void CppCodeStylePreferencesWidget::slotTabSettingsChanged(const TabSettings &settings)
{
if (m_blockUpdates)
return;
@@ -463,9 +463,9 @@ void CppCodeStylePreferencesWidget::updatePreview()
? m_preferences
: CppToolsSettings::instance()->cppCodeStyle();
const CppCodeStyleSettings ccss = cppCodeStylePreferences->currentCodeStyleSettings();
- const TextEditor::TabSettings ts = cppCodeStylePreferences->currentTabSettings();
+ const TabSettings ts = cppCodeStylePreferences->currentTabSettings();
QtStyleCodeFormatter formatter(ts, ccss);
- foreach (TextEditor::SnippetEditorWidget *preview, m_previews) {
+ foreach (SnippetEditorWidget *preview, m_previews) {
preview->textDocument()->setTabSettings(ts);
preview->setCodeStyle(cppCodeStylePreferences);
@@ -485,14 +485,14 @@ void CppCodeStylePreferencesWidget::updatePreview()
}
}
-void CppCodeStylePreferencesWidget::decorateEditors(const TextEditor::FontSettings &fontSettings)
+void CppCodeStylePreferencesWidget::decorateEditors(const FontSettings &fontSettings)
{
const ISnippetProvider *provider = ExtensionSystem::PluginManager::getObject<ISnippetProvider>(
[](ISnippetProvider *current) {
return current->groupId() == QLatin1String(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID);
});
- foreach (TextEditor::SnippetEditorWidget *editor, m_previews) {
+ foreach (SnippetEditorWidget *editor, m_previews) {
editor->textDocument()->setFontSettings(fontSettings);
if (provider)
provider->decorateEditor(editor);
@@ -501,7 +501,7 @@ void CppCodeStylePreferencesWidget::decorateEditors(const TextEditor::FontSettin
void CppCodeStylePreferencesWidget::setVisualizeWhitespace(bool on)
{
- foreach (TextEditor::SnippetEditorWidget *editor, m_previews) {
+ foreach (SnippetEditorWidget *editor, m_previews) {
DisplaySettings displaySettings = editor->displaySettings();
displaySettings.m_visualizeWhitespace = on;
editor->setDisplaySettings(displaySettings);
diff --git a/src/plugins/cpptools/cppcompletion_test.cpp b/src/plugins/cpptools/cppcompletion_test.cpp
index e52b2cb1e51..5c84ec93079 100644
--- a/src/plugins/cpptools/cppcompletion_test.cpp
+++ b/src/plugins/cpptools/cppcompletion_test.cpp
@@ -58,7 +58,7 @@ namespace {
typedef QByteArray _;
-class CompletionTestCase : public CppTools::Tests::TestCase
+class CompletionTestCase : public Tests::TestCase
{
public:
CompletionTestCase(const QByteArray &sourceText, const QByteArray &textToInsert = QByteArray())
@@ -73,14 +73,16 @@ public:
m_source[m_position] = ' ';
// Write source to file
- const QString fileName = QDir::tempPath() + QLatin1String("/file.h");
- QVERIFY(writeFile(fileName, m_source));
+ m_temporaryDir.reset(new Tests::TemporaryDir());
+ QVERIFY(m_temporaryDir->isValid());
+ const QString fileName = m_temporaryDir->createFile("file.h", m_source);
+ QVERIFY(!fileName.isEmpty());
// Open in editor
m_editor = EditorManager::openEditor(fileName);
QVERIFY(m_editor);
closeEditorAtEndOfTestCase(m_editor);
- m_editorWidget = qobject_cast<TextEditor::TextEditorWidget *>(m_editor->widget());
+ m_editorWidget = qobject_cast<TextEditorWidget *>(m_editor->widget());
QVERIFY(m_editorWidget);
m_textDocument = m_editorWidget->document();
@@ -103,11 +105,11 @@ public:
{
QStringList completions;
CppCompletionAssistInterface *ai
- = new CppCompletionAssistInterface(m_editorWidget->textDocument()->filePath(),
+ = new CppCompletionAssistInterface(m_editorWidget->textDocument()->filePath().toString(),
m_editorWidget->document(), m_position,
ExplicitlyInvoked, m_snapshot,
ProjectPart::HeaderPaths());
- CppCompletionAssistProcessor processor;
+ InternalCppCompletionAssistProcessor processor;
const Tests::IAssistProposalScopedPointer proposal(processor.perform(ai));
if (!proposal.d)
@@ -150,6 +152,7 @@ private:
QByteArray m_source;
int m_position;
Snapshot m_snapshot;
+ QScopedPointer<Tests::TemporaryDir> m_temporaryDir;
TextEditorWidget *m_editorWidget;
QTextDocument *m_textDocument;
IEditor *m_editor;
@@ -307,10 +310,40 @@ void CppToolsPlugin::test_completion()
actualCompletions.sort();
expectedCompletions.sort();
- QEXPECT_FAIL("enum_in_function_in_struct_in_function", "doesn't work", Abort);
+ QEXPECT_FAIL("enum_in_function_in_struct_in_function", "QTCREATORBUG-13757", Abort);
+ QEXPECT_FAIL("enum_in_function_in_struct_in_function_cxx11", "QTCREATORBUG-13757", Abort);
+ QEXPECT_FAIL("enum_in_function_in_struct_in_function_anon", "QTCREATORBUG-13757", Abort);
+ QEXPECT_FAIL("enum_in_class_accessed_in_member_func_cxx11", "QTCREATORBUG-13757", Abort);
+ QEXPECT_FAIL("enum_in_class_accessed_in_member_func_inline_cxx11", "QTCREATORBUG-13757", Abort);
QCOMPARE(actualCompletions, expectedCompletions);
}
+static void enumTestCase(const QByteArray &tag, const QByteArray &source,
+ const QByteArray &prefix = QByteArray())
+{
+ QByteArray fullSource = source;
+ fullSource.replace('$', "enum E { val1, val2, val3 };");
+ QTest::newRow(tag) << fullSource << (prefix + "val")
+ << (QStringList()
+ << QLatin1String("val1")
+ << QLatin1String("val2")
+ << QLatin1String("val3"));
+
+ QTest::newRow(tag + "_cxx11") << fullSource << (prefix + "E::")
+ << (QStringList()
+ << QLatin1String("E")
+ << QLatin1String("val1")
+ << QLatin1String("val2")
+ << QLatin1String("val3"));
+
+ fullSource.replace("enum E ", "enum ");
+ QTest::newRow(tag + "_anon") << fullSource << (prefix + "val")
+ << (QStringList()
+ << QLatin1String("val1")
+ << QLatin1String("val2")
+ << QLatin1String("val3"));
+}
+
void CppToolsPlugin::test_completion_data()
{
QTest::addColumn<QByteArray>("code");
@@ -1759,103 +1792,94 @@ void CppToolsPlugin::test_completion_data()
<< QLatin1String("staticFun2")
<< QLatin1String("m2"));
- QTest::newRow("enum_inside_block_inside_function_cxx11_QTCREATORBUG5456") << _(
- "void foo()\n"
- "{\n"
- " {\n"
- " enum E { e1, e2, e3 };\n"
- " @\n"
- " }\n"
- "}\n"
- ) << _("E::") << (QStringList()
- << QLatin1String("E")
- << QLatin1String("e1")
- << QLatin1String("e2")
- << QLatin1String("e3"));
-
- QTest::newRow("enum_inside_function") << _(
+ enumTestCase(
+ "enum_inside_block_inside_function",
+ "void foo()\n"
+ "{\n"
+ " {\n"
+ " $\n"
+ " @\n"
+ " }\n"
+ "}\n"
+ );
+
+ enumTestCase(
+ "enum_inside_function",
"void foo()\n"
"{\n"
- " enum E { val1, val2, val3 };\n"
+ " $\n"
" @\n"
"}\n"
- ) << _("val") << (QStringList()
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
+ );
- QTest::newRow("anon_enum_inside_function") << _(
- "void foo()\n"
- "{\n"
- " enum { val1, val2, val3 };\n"
- " @\n"
- "}\n"
- ) << _("val") << (QStringList()
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
-
- QTest::newRow("enum_in_function_in_struct_in_function") << _(
+ enumTestCase(
+ "enum_in_function_in_struct_in_function",
"void foo()\n"
"{\n"
" struct S {\n"
" void fun()\n"
" {\n"
- " enum E { val1, val2, val3 };\n"
+ " $\n"
" @\n"
" }\n"
" };\n"
"}\n"
- ) << _("val") << (QStringList()
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
+ );
- QTest::newRow("enum_inside_function_cxx11_QTCREATORBUG5456") << _(
- "void foo()\n"
+ enumTestCase(
+ "enum_inside_class",
+ "struct Foo\n"
"{\n"
- " enum E { e1, e2, e3 };\n"
+ " $\n"
" @\n"
- "}\n"
- ) << _("E::") << (QStringList()
- << QLatin1String("E")
- << QLatin1String("e1")
- << QLatin1String("e2")
- << QLatin1String("e3"));
+ "};\n",
+ "Foo::"
+ );
- QTest::newRow("enum_inside_class") << _(
- "struct Foo\n"
+ enumTestCase(
+ "enum_inside_namespace",
+ "namespace Ns\n"
"{\n"
- " enum E { val1, val2, val3 };\n"
+ " $\n"
" @\n"
- "};\n"
- ) << _("Foo::v") << (QStringList()
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
+ "}\n",
+ "Ns::"
+ );
- QTest::newRow("enum_inside_class_cxx11") << _(
- "struct Foo\n"
+ enumTestCase(
+ "enum_inside_member_function",
+ "class Foo { void func(); };\n"
+ "void Foo::func()\n"
"{\n"
- " enum E { val1, val2, val3 };\n"
+ " $\n"
" @\n"
+ "}\n"
+ );
+
+ enumTestCase(
+ "enum_in_class_accessed_in_member_func_inline",
+ "class Foo\n"
+ "{\n"
+ " $\n"
+ " void func()\n"
+ " {\n"
+ " @\n"
+ " }\n"
"};\n"
- ) << _("Foo::E::") << (QStringList()
- << QLatin1String("E")
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
+ );
- QTest::newRow("anon_enum_inside_class") << _(
- "struct Foo\n"
+ enumTestCase(
+ "enum_in_class_accessed_in_member_func",
+ "class Foo\n"
"{\n"
- " enum { val1, val2, val3 };\n"
- " @\n"
+ " $\n"
+ " void func();\n"
"};\n"
- ) << _("Foo::v") << (QStringList()
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
+ "void Foo::func()\n"
+ "{\n"
+ " @\n"
+ "}\n"
+ );
QTest::newRow("nested_anonymous_with___attribute__") << _(
"struct Enclosing\n"
@@ -1871,40 +1895,6 @@ void CppToolsPlugin::test_completion_data()
<< QLatin1String("Enclosing")
<< QLatin1String("i"));
- QTest::newRow("enum_inside_namespace") << _(
- "namespace Ns\n"
- "{\n"
- " enum E { val1, val2, val3 };\n"
- " @\n"
- "}\n"
- ) << _("Ns::v") << (QStringList()
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
-
- QTest::newRow("enum_inside_namespace_cxx11") << _(
- "namespace Ns\n"
- "{\n"
- " enum E { val1, val2, val3 };\n"
- " @\n"
- "}\n"
- ) << _("Ns::E::") << (QStringList()
- << QLatin1String("E")
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
-
- QTest::newRow("anon_enum_inside_namespace") << _(
- "namespace Ns\n"
- "{\n"
- " enum { val1, val2, val3 };\n"
- " @\n"
- "}\n"
- ) << _("Ns::v") << (QStringList()
- << QLatin1String("val1")
- << QLatin1String("val2")
- << QLatin1String("val3"));
-
QTest::newRow("lambdaCalls_1") << _(
"struct S { int bar; };\n"
"void foo()\n"
@@ -2394,6 +2384,17 @@ void CppToolsPlugin::test_completion_data()
"}\n"
) << _("s.") << (QStringList()
<< QLatin1String("S"));
+
+ QTest::newRow("auto_declaration_in_if_condition") << _(
+ "struct Foo { int bar; };\n"
+ "void fun() {\n"
+ " if (auto s = new Foo) {\n"
+ " @\n"
+ " }\n"
+ "}\n"
+ ) << _("s->") << (QStringList()
+ << QLatin1String("Foo")
+ << QLatin1String("bar"));
}
void CppToolsPlugin::test_completion_member_access_operator()
diff --git a/src/plugins/cpptools/cppcompletionassist.cpp b/src/plugins/cpptools/cppcompletionassist.cpp
index 5a02dbd6447..d11ac69f0b0 100644
--- a/src/plugins/cpptools/cppcompletionassist.cpp
+++ b/src/plugins/cpptools/cppcompletionassist.cpp
@@ -413,7 +413,7 @@ int CppFunctionHintModel::activeArgument(const QString &prefix) const
IAssistProcessor *InternalCompletionAssistProvider::createProcessor() const
{
- return new CppCompletionAssistProcessor;
+ return new InternalCppCompletionAssistProcessor;
}
AssistInterface *InternalCompletionAssistProvider::createAssistInterface(
@@ -423,9 +423,8 @@ AssistInterface *InternalCompletionAssistProvider::createAssistInterface(
QTC_ASSERT(document, return 0);
CppModelManager *modelManager = CppModelManager::instance();
- return new CppTools::Internal::CppCompletionAssistInterface(filePath, document, isObjCEnabled,
- position, reason,
- modelManager->workingCopy());
+ return new CppCompletionAssistInterface(filePath, document, isObjCEnabled, position, reason,
+ modelManager->workingCopy());
}
// -----------------
@@ -598,28 +597,11 @@ bool isQPrivateSignal(const Symbol *symbol)
} // Anonymous
-// ----------------------------
-// CppCompletionAssistProcessor
-// ----------------------------
-CppCompletionAssistProcessor::CppCompletionAssistProcessor()
- : m_startPosition(-1)
- , m_snippetCollector(QLatin1String(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID),
- QIcon(QLatin1String(":/texteditor/images/snippet.png")))
- , preprocessorCompletions(QStringList()
- << QLatin1String("define")
- << QLatin1String("error")
- << QLatin1String("include")
- << QLatin1String("line")
- << QLatin1String("pragma")
- << QLatin1String("undef")
- << QLatin1String("if")
- << QLatin1String("ifdef")
- << QLatin1String("ifndef")
- << QLatin1String("elif")
- << QLatin1String("else")
- << QLatin1String("endif"))
- , m_model(new CppAssistProposalModel)
- , m_hintProposal(0)
+// ------------------------------------
+// InternalCppCompletionAssistProcessor
+// ------------------------------------
+InternalCppCompletionAssistProcessor::InternalCppCompletionAssistProcessor()
+ : m_model(new CppAssistProposalModel)
{
// FIXME: C++11?
m_languageFeatures.objCEnabled = true;
@@ -628,10 +610,10 @@ CppCompletionAssistProcessor::CppCompletionAssistProcessor()
m_languageFeatures.qtMocRunEnabled = true;
}
-CppCompletionAssistProcessor::~CppCompletionAssistProcessor()
+InternalCppCompletionAssistProcessor::~InternalCppCompletionAssistProcessor()
{}
-IAssistProposal * CppCompletionAssistProcessor::perform(const AssistInterface *interface)
+IAssistProposal * InternalCppCompletionAssistProcessor::perform(const AssistInterface *interface)
{
m_interface.reset(static_cast<const CppCompletionAssistInterface *>(interface));
@@ -649,7 +631,7 @@ IAssistProposal * CppCompletionAssistProcessor::perform(const AssistInterface *i
return 0;
}
-bool CppCompletionAssistProcessor::accepts() const
+bool InternalCppCompletionAssistProcessor::accepts() const
{
const int pos = m_interface->position();
unsigned token = T_EOF_SYMBOL;
@@ -715,7 +697,7 @@ bool CppCompletionAssistProcessor::accepts() const
return false;
}
-IAssistProposal *CppCompletionAssistProcessor::createContentProposal()
+IAssistProposal *InternalCppCompletionAssistProcessor::createContentProposal()
{
// Duplicates are kept only if they are snippets.
QSet<QString> processed;
@@ -745,8 +727,8 @@ IAssistProposal *CppCompletionAssistProcessor::createContentProposal()
return new CppAssistProposal(m_startPosition, m_model.take());
}
-IAssistProposal *CppCompletionAssistProcessor::createHintProposal(
- QList<CPlusPlus::Function *> functionSymbols) const
+IAssistProposal *InternalCppCompletionAssistProcessor::createHintProposal(
+ QList<Function *> functionSymbols) const
{
IFunctionHintProposalModel *model =
new CppFunctionHintModel(functionSymbols, m_model->m_typeOfExpression);
@@ -754,9 +736,9 @@ IAssistProposal *CppCompletionAssistProcessor::createHintProposal(
return proposal;
}
-int CppCompletionAssistProcessor::startOfOperator(int pos,
- unsigned *kind,
- bool wantFunctionCall) const
+int InternalCppCompletionAssistProcessor::startOfOperator(int pos,
+ unsigned *kind,
+ bool wantFunctionCall) const
{
const QChar ch = pos > -1 ? m_interface->characterAt(pos - 1) : QChar();
const QChar ch2 = pos > 0 ? m_interface->characterAt(pos - 2) : QChar();
@@ -862,7 +844,7 @@ int CppCompletionAssistProcessor::startOfOperator(int pos,
return start;
}
-int CppCompletionAssistProcessor::findStartOfName(int pos) const
+int InternalCppCompletionAssistProcessor::findStartOfName(int pos) const
{
if (pos == -1)
pos = m_interface->position();
@@ -876,7 +858,7 @@ int CppCompletionAssistProcessor::findStartOfName(int pos) const
return pos + 1;
}
-int CppCompletionAssistProcessor::startCompletionHelper()
+int InternalCppCompletionAssistProcessor::startCompletionHelper()
{
if (m_languageFeatures.objCEnabled) {
if (tryObjCCompletion())
@@ -970,7 +952,7 @@ int CppCompletionAssistProcessor::startCompletionHelper()
return startCompletionInternal(fileName, line, column, expression, endOfExpression);
}
-bool CppCompletionAssistProcessor::tryObjCCompletion()
+bool InternalCppCompletionAssistProcessor::tryObjCCompletion()
{
int end = m_interface->position();
while (m_interface->characterAt(end).isSpace())
@@ -1042,10 +1024,10 @@ enum CompletionOrder {
};
}
-void CppCompletionAssistProcessor::addCompletionItem(const QString &text,
- const QIcon &icon,
- int order,
- const QVariant &data)
+void InternalCppCompletionAssistProcessor::addCompletionItem(const QString &text,
+ const QIcon &icon,
+ int order,
+ const QVariant &data)
{
AssistProposalItem *item = new CppAssistProposalItem;
item->setText(text);
@@ -1055,8 +1037,7 @@ void CppCompletionAssistProcessor::addCompletionItem(const QString &text,
m_completions.append(item);
}
-void CppCompletionAssistProcessor::addCompletionItem(CPlusPlus::Symbol *symbol,
- int order)
+void InternalCppCompletionAssistProcessor::addCompletionItem(Symbol *symbol, int order)
{
ConvertToCompletionItem toCompletionItem;
AssistProposalItem *item = toCompletionItem(symbol);
@@ -1067,8 +1048,8 @@ void CppCompletionAssistProcessor::addCompletionItem(CPlusPlus::Symbol *symbol,
}
}
-void CppCompletionAssistProcessor::completeObjCMsgSend(CPlusPlus::ClassOrNamespace *binding,
- bool staticClassAccess)
+void InternalCppCompletionAssistProcessor::completeObjCMsgSend(ClassOrNamespace *binding,
+ bool staticClassAccess)
{
QList<Scope*> memberScopes;
foreach (Symbol *s, binding->symbols()) {
@@ -1094,12 +1075,12 @@ void CppCompletionAssistProcessor::completeObjCMsgSend(CPlusPlus::ClassOrNamespa
Symbol *arg = method->argumentAt(i);
text += QString::fromUtf8(selectorName->nameAt(i)->identifier()->chars());
text += QLatin1Char(':');
- text += TextEditor::Snippet::kVariableDelimiter;
+ text += Snippet::kVariableDelimiter;
text += QLatin1Char('(');
text += oo.prettyType(arg->type());
text += QLatin1Char(')');
text += oo.prettyName(arg->name());
- text += TextEditor::Snippet::kVariableDelimiter;
+ text += Snippet::kVariableDelimiter;
}
} else {
text = QString::fromUtf8(selectorName->identifier()->chars());
@@ -1114,7 +1095,7 @@ void CppCompletionAssistProcessor::completeObjCMsgSend(CPlusPlus::ClassOrNamespa
}
}
-bool CppCompletionAssistProcessor::completeInclude(const QTextCursor &cursor)
+bool InternalCppCompletionAssistProcessor::completeInclude(const QTextCursor &cursor)
{
QString directoryPrefix;
if (m_model->m_completionOperator == T_SLASH) {
@@ -1157,8 +1138,8 @@ bool CppCompletionAssistProcessor::completeInclude(const QTextCursor &cursor)
return !m_completions.isEmpty();
}
-void CppCompletionAssistProcessor::completeInclude(const QString &realPath,
- const QStringList &suffixes)
+void InternalCppCompletionAssistProcessor::completeInclude(const QString &realPath,
+ const QStringList &suffixes)
{
QDirIterator i(realPath, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
while (i.hasNext()) {
@@ -1174,16 +1155,16 @@ void CppCompletionAssistProcessor::completeInclude(const QString &realPath,
}
}
-void CppCompletionAssistProcessor::completePreprocessor()
+void InternalCppCompletionAssistProcessor::completePreprocessor()
{
- foreach (const QString &preprocessorCompletion, preprocessorCompletions)
+ foreach (const QString &preprocessorCompletion, m_preprocessorCompletions)
addCompletionItem(preprocessorCompletion);
if (objcKeywordsWanted())
addCompletionItem(QLatin1String("import"));
}
-bool CppCompletionAssistProcessor::objcKeywordsWanted() const
+bool InternalCppCompletionAssistProcessor::objcKeywordsWanted() const
{
if (!m_languageFeatures.objCEnabled)
return false;
@@ -1195,10 +1176,10 @@ bool CppCompletionAssistProcessor::objcKeywordsWanted() const
|| mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE);
}
-int CppCompletionAssistProcessor::startCompletionInternal(const QString &fileName,
- unsigned line, unsigned column,
- const QString &expr,
- int endOfExpression)
+int InternalCppCompletionAssistProcessor::startCompletionInternal(const QString &fileName,
+ unsigned line, unsigned column,
+ const QString &expr,
+ int endOfExpression)
{
QString expression = expr.trimmed();
@@ -1311,7 +1292,7 @@ int CppCompletionAssistProcessor::startCompletionInternal(const QString &fileNam
return -1;
}
-void CppCompletionAssistProcessor::globalCompletion(CPlusPlus::Scope *currentScope)
+void InternalCppCompletionAssistProcessor::globalCompletion(Scope *currentScope)
{
const LookupContext &context = m_model->m_typeOfExpression->context();
@@ -1388,7 +1369,7 @@ void CppCompletionAssistProcessor::globalCompletion(CPlusPlus::Scope *currentSco
addSnippets();
}
-bool CppCompletionAssistProcessor::completeMember(const QList<CPlusPlus::LookupItem> &baseResults)
+bool InternalCppCompletionAssistProcessor::completeMember(const QList<LookupItem> &baseResults)
{
const LookupContext &context = m_model->m_typeOfExpression->context();
@@ -1414,7 +1395,7 @@ bool CppCompletionAssistProcessor::completeMember(const QList<CPlusPlus::LookupI
return false;
}
-bool CppCompletionAssistProcessor::completeScope(const QList<CPlusPlus::LookupItem> &results)
+bool InternalCppCompletionAssistProcessor::completeScope(const QList<LookupItem> &results)
{
const LookupContext &context = m_model->m_typeOfExpression->context();
if (results.isEmpty())
@@ -1481,7 +1462,7 @@ bool CppCompletionAssistProcessor::completeScope(const QList<CPlusPlus::LookupIt
return !m_completions.isEmpty();
}
-void CppCompletionAssistProcessor::completeNamespace(CPlusPlus::ClassOrNamespace *b)
+void InternalCppCompletionAssistProcessor::completeNamespace(ClassOrNamespace *b)
{
QSet<ClassOrNamespace *> bindingsVisited;
QList<ClassOrNamespace *> bindingsToVisit;
@@ -1513,7 +1494,7 @@ void CppCompletionAssistProcessor::completeNamespace(CPlusPlus::ClassOrNamespace
scopesVisited.insert(scope);
- for (Scope::iterator it = scope->firstMember(); it != scope->lastMember(); ++it) {
+ for (Scope::iterator it = scope->memberBegin(); it != scope->memberEnd(); ++it) {
Symbol *member = *it;
addCompletionItem(member);
}
@@ -1521,7 +1502,7 @@ void CppCompletionAssistProcessor::completeNamespace(CPlusPlus::ClassOrNamespace
}
}
-void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b, bool staticLookup)
+void InternalCppCompletionAssistProcessor::completeClass(ClassOrNamespace *b, bool staticLookup)
{
QSet<ClassOrNamespace *> bindingsVisited;
QList<ClassOrNamespace *> bindingsToVisit;
@@ -1563,14 +1544,15 @@ void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b,
}
}
-void CppCompletionAssistProcessor::addClassMembersToCompletion(Scope *scope, bool staticLookup)
+void InternalCppCompletionAssistProcessor::addClassMembersToCompletion(Scope *scope,
+ bool staticLookup)
{
if (!scope)
return;
std::set<Class *> nestedAnonymouses;
- for (Scope::iterator it = scope->firstMember(); it != scope->lastMember(); ++it) {
+ for (Scope::iterator it = scope->memberBegin(); it != scope->memberEnd(); ++it) {
Symbol *member = *it;
if (member->isFriend()
|| member->isQtPropertyDeclaration()
@@ -1598,7 +1580,9 @@ void CppCompletionAssistProcessor::addClassMembersToCompletion(Scope *scope, boo
addClassMembersToCompletion(*cit, staticLookup);
}
-bool CppCompletionAssistProcessor::completeQtMethod(const QList<CPlusPlus::LookupItem> &results, bool wantSignals)
+bool InternalCppCompletionAssistProcessor::completeQtMethod(
+ const QList<LookupItem> &results,
+ bool wantSignals)
{
if (results.isEmpty())
return false;
@@ -1700,12 +1684,7 @@ bool CppCompletionAssistProcessor::completeQtMethod(const QList<CPlusPlus::Looku
return !m_completions.isEmpty();
}
-void CppCompletionAssistProcessor::addSnippets()
-{
- m_completions.append(m_snippetCollector.collect());
-}
-
-void CppCompletionAssistProcessor::addKeywords()
+void InternalCppCompletionAssistProcessor::addKeywords()
{
int keywordLimit = T_FIRST_OBJC_AT_KEYWORD;
if (objcKeywordsWanted())
@@ -1720,7 +1699,8 @@ void CppCompletionAssistProcessor::addKeywords()
addCompletionItem(QLatin1String(Token::name(i)), m_icons.keywordIcon(), KeywordsOrder);
}
-void CppCompletionAssistProcessor::addMacros(const QString &fileName, const CPlusPlus::Snapshot &snapshot)
+void InternalCppCompletionAssistProcessor::addMacros(const QString &fileName,
+ const Snapshot &snapshot)
{
QSet<QString> processed;
QSet<QString> definedMacros;
@@ -1731,7 +1711,7 @@ void CppCompletionAssistProcessor::addMacros(const QString &fileName, const CPlu
addCompletionItem(macroName, m_icons.macroIcon(), MacrosOrder);
}
-void CppCompletionAssistProcessor::addMacros_helper(const CPlusPlus::Snapshot &snapshot,
+void InternalCppCompletionAssistProcessor::addMacros_helper(const Snapshot &snapshot,
const QString &fileName,
QSet<QString> *processed,
QSet<QString> *definedMacros)
@@ -1755,9 +1735,9 @@ void CppCompletionAssistProcessor::addMacros_helper(const CPlusPlus::Snapshot &s
}
}
-bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPlusPlus::LookupItem> &results,
- int endOfExpression,
- bool toolTipOnly)
+bool InternalCppCompletionAssistProcessor::completeConstructorOrFunction(const QList<LookupItem> &results,
+ int endOfExpression,
+ bool toolTipOnly)
{
const LookupContext &context = m_model->m_typeOfExpression->context();
QList<Function *> functions;
diff --git a/src/plugins/cpptools/cppcompletionassist.h b/src/plugins/cpptools/cppcompletionassist.h
index b740fcc8b9b..e95c21603d3 100644
--- a/src/plugins/cpptools/cppcompletionassist.h
+++ b/src/plugins/cpptools/cppcompletionassist.h
@@ -31,6 +31,7 @@
#ifndef CPPCOMPLETIONASSIST_H
#define CPPCOMPLETIONASSIST_H
+#include "cppcompletionassistprocessor.h"
#include "cppcompletionassistprovider.h"
#include "cppmodelmanager.h"
#include "cppworkingcopy.h"
@@ -96,11 +97,11 @@ public:
TextEditor::AssistReason reason) const Q_DECL_OVERRIDE;
};
-class CppCompletionAssistProcessor : public TextEditor::IAssistProcessor
+class InternalCppCompletionAssistProcessor : public CppCompletionAssistProcessor
{
public:
- CppCompletionAssistProcessor();
- ~CppCompletionAssistProcessor();
+ InternalCppCompletionAssistProcessor();
+ ~InternalCppCompletionAssistProcessor();
TextEditor::IAssistProposal *perform(const TextEditor::AssistInterface *interface) Q_DECL_OVERRIDE;
@@ -144,7 +145,6 @@ private:
const QVariant &data = QVariant());
void addCompletionItem(CPlusPlus::Symbol *symbol,
int order = 0);
- void addSnippets();
void addKeywords();
void addMacros(const QString &fileName, const CPlusPlus::Snapshot &snapshot);
void addMacros_helper(const CPlusPlus::Snapshot &snapshot,
@@ -152,15 +152,9 @@ private:
QSet<QString> *processed,
QSet<QString> *definedMacros);
- int m_startPosition;
CPlusPlus::LanguageFeatures m_languageFeatures;
QScopedPointer<const CppCompletionAssistInterface> m_interface;
- QList<TextEditor::AssistProposalItem *> m_completions;
- TextEditor::SnippetAssistCollector m_snippetCollector;
- CPlusPlus::Icons m_icons;
- QStringList preprocessorCompletions;
QScopedPointer<CppAssistProposalModel> m_model;
- TextEditor::IAssistProposal *m_hintProposal;
};
class CppCompletionAssistInterface : public TextEditor::AssistInterface
diff --git a/src/plugins/cpptools/cppcompletionassistprocessor.cpp b/src/plugins/cpptools/cppcompletionassistprocessor.cpp
new file mode 100644
index 00000000000..d6ce5e6a14e
--- /dev/null
+++ b/src/plugins/cpptools/cppcompletionassistprocessor.cpp
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "cppcompletionassistprocessor.h"
+
+#include <cppeditor/cppeditorconstants.h>
+
+namespace CppTools {
+
+CppCompletionAssistProcessor::CppCompletionAssistProcessor()
+ : m_startPosition(-1)
+ , m_preprocessorCompletions(QStringList()
+ << QLatin1String("define")
+ << QLatin1String("error")
+ << QLatin1String("include")
+ << QLatin1String("line")
+ << QLatin1String("pragma")
+ << QLatin1String("pragma once")
+ << QLatin1String("pragma omp atomic")
+ << QLatin1String("pragma omp parallel")
+ << QLatin1String("pragma omp for")
+ << QLatin1String("pragma omp ordered")
+ << QLatin1String("pragma omp parallel for")
+ << QLatin1String("pragma omp section")
+ << QLatin1String("pragma omp sections")
+ << QLatin1String("pragma omp parallel sections")
+ << QLatin1String("pragma omp single")
+ << QLatin1String("pragma omp master")
+ << QLatin1String("pragma omp critical")
+ << QLatin1String("pragma omp barrier")
+ << QLatin1String("pragma omp flush")
+ << QLatin1String("pragma omp threadprivate")
+ << QLatin1String("undef")
+ << QLatin1String("if")
+ << QLatin1String("ifdef")
+ << QLatin1String("ifndef")
+ << QLatin1String("elif")
+ << QLatin1String("else")
+ << QLatin1String("endif"))
+ , m_hintProposal(0)
+ , m_snippetCollector(QLatin1String(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID),
+ QIcon(QLatin1String(":/texteditor/images/snippet.png")))
+{
+}
+
+void CppCompletionAssistProcessor::addSnippets()
+{
+ m_completions.append(m_snippetCollector.collect());
+}
+
+} // namespace CppTools
diff --git a/src/plugins/cpptools/cppcompletionassistprocessor.h b/src/plugins/cpptools/cppcompletionassistprocessor.h
new file mode 100644
index 00000000000..294c5011ca8
--- /dev/null
+++ b/src/plugins/cpptools/cppcompletionassistprocessor.h
@@ -0,0 +1,63 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 CPPCOMPLETIONASSISTPROCESSOR_H
+#define CPPCOMPLETIONASSISTPROCESSOR_H
+
+#include "cpptools_global.h"
+
+#include <texteditor/codeassist/iassistprocessor.h>
+#include <texteditor/snippets/snippetassistcollector.h>
+
+#include <cplusplus/Icons.h>
+
+namespace CppTools {
+
+class CPPTOOLS_EXPORT CppCompletionAssistProcessor : public TextEditor::IAssistProcessor
+{
+public:
+ CppCompletionAssistProcessor();
+
+protected:
+ void addSnippets();
+
+ int m_startPosition;
+ QList<TextEditor::AssistProposalItem *> m_completions;
+ QStringList m_preprocessorCompletions;
+ TextEditor::IAssistProposal *m_hintProposal;
+ CPlusPlus::Icons m_icons;
+
+private:
+ TextEditor::SnippetAssistCollector m_snippetCollector;
+};
+
+} // namespace CppTools
+
+#endif // CPPCOMPLETIONASSISTPROCESSOR_H
diff --git a/src/plugins/cpptools/cppcurrentdocumentfilter.cpp b/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
index 8a64421663a..045398189d9 100644
--- a/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
+++ b/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
@@ -45,6 +45,7 @@ CppCurrentDocumentFilter::CppCurrentDocumentFilter(CppTools::CppModelManager *ma
setId("Methods in current Document");
setDisplayName(tr("C++ Symbols in Current Document"));
setShortcutString(QString(QLatin1Char('.')));
+ setPriority(High);
setIncludedByDefault(false);
search.setSymbolsToSearchFor(SymbolSearcher::Declarations |
@@ -132,7 +133,7 @@ void CppCurrentDocumentFilter::onCurrentEditorChanged(Core::IEditor *currentEdit
{
QMutexLocker locker(&m_mutex);
if (currentEditor)
- m_currentFileName = currentEditor->document()->filePath();
+ m_currentFileName = currentEditor->document()->filePath().toString();
else
m_currentFileName.clear();
m_itemsOfCurrentDoc.clear();
@@ -144,7 +145,7 @@ void CppCurrentDocumentFilter::onEditorAboutToClose(Core::IEditor *editorAboutTo
return;
QMutexLocker locker(&m_mutex);
- if (m_currentFileName == editorAboutToClose->document()->filePath()) {
+ if (m_currentFileName == editorAboutToClose->document()->filePath().toString()) {
m_currentFileName.clear();
m_itemsOfCurrentDoc.clear();
}
diff --git a/src/plugins/cppeditor/cppeditoroutline.cpp b/src/plugins/cpptools/cppeditoroutline.cpp
index bb0f074041a..ba7575cb3f1 100644
--- a/src/plugins/cppeditor/cppeditoroutline.cpp
+++ b/src/plugins/cpptools/cppeditoroutline.cpp
@@ -30,10 +30,10 @@
#include "cppeditoroutline.h"
-#include "cppeditor.h"
-#include "cppeditorplugin.h"
-
#include <cpptools/cppmodelmanager.h>
+#include <cpptools/cpptoolsreuse.h>
+#include <cpptools/cpptoolssettings.h>
+#include <texteditor/texteditor.h>
#include <cplusplus/OverviewModel.h>
#include <utils/treeviewcombobox.h>
@@ -42,15 +42,11 @@
#include <QTimer>
/*!
- \class CppEditor::Internal::CppEditorOutline
- \brief A helper class of CppEditorWidget that provides the outline model
- and widget, e.g. for the editor's tool bar.
-
- \internal
+ \class CppTools::CppEditorOutline
+ \brief A helper class that provides the outline model and widget,
+ e.g. for the editor's tool bar.
The caller is responsible for deleting the widget returned by widget().
-
- \sa CppEditor::Internal::CppEditorWidget
*/
enum { UpdateOutlineIntervalInMs = 500 };
@@ -94,10 +90,9 @@ QTimer *newSingleShotTimer(QObject *parent, int msInternal, const QString &objec
} // anonymous namespace
-namespace CppEditor {
-namespace Internal {
+namespace CppTools {
-CppEditorOutline::CppEditorOutline(CppEditorWidget *editorWidget)
+CppEditorOutline::CppEditorOutline(TextEditor::TextEditorWidget *editorWidget)
: QObject(editorWidget)
, m_editorWidget(editorWidget)
, m_combo(new Utils::TreeViewComboBox)
@@ -105,7 +100,7 @@ CppEditorOutline::CppEditorOutline(CppEditorWidget *editorWidget)
, m_proxyModel(new OverviewProxyModel(m_model, this))
{
// Set up proxy model
- if (CppEditorPlugin::instance()->sortedOutline())
+ if (CppTools::CppToolsSettings::instance()->sortedEditorDocumentOutline())
m_proxyModel->sort(0, Qt::AscendingOrder);
else
m_proxyModel->sort(-1, Qt::AscendingOrder); // don't sort yet, but set column for sortedOutline()
@@ -125,8 +120,9 @@ CppEditorOutline::CppEditorOutline(CppEditorWidget *editorWidget)
m_sortAction = new QAction(tr("Sort Alphabetically"), m_combo);
m_sortAction->setCheckable(true);
m_sortAction->setChecked(isSorted());
- connect(m_sortAction, SIGNAL(toggled(bool)),
- CppEditorPlugin::instance(), SLOT(setSortedOutline(bool)));
+ connect(m_sortAction, &QAction::toggled,
+ CppTools::CppToolsSettings::instance(),
+ &CppTools::CppToolsSettings::setSortedEditorDocumentOutline);
m_combo->addAction(m_sortAction);
connect(m_combo, SIGNAL(activated(int)), this, SLOT(gotoSymbolInEditor()));
@@ -195,7 +191,7 @@ void CppEditorOutline::updateNow()
return;
const CPlusPlus::Snapshot snapshot = cmmi->snapshot();
- const QString filePath = m_editorWidget->textDocument()->filePath();
+ const QString filePath = m_editorWidget->textDocument()->filePath().toString();
CPlusPlus::Document::Ptr document = snapshot.document(filePath);
if (!document)
return;
@@ -253,7 +249,7 @@ void CppEditorOutline::gotoSymbolInEditor()
if (!symbol)
return;
- const TextEditor::TextEditorWidget::Link &link = CppEditorWidget::linkToSymbol(symbol);
+ const TextEditor::TextEditorWidget::Link &link = CppTools::linkToSymbol(symbol);
if (!link.hasValidTarget())
return;
@@ -285,7 +281,6 @@ QModelIndex CppEditorOutline::indexForPosition(int line, int column,
return lastIndex;
}
-} // namespace Internal
-} // namespace CppEditor
+} // namespace CppTools
#include <cppeditoroutline.moc>
diff --git a/src/plugins/cppeditor/cppeditoroutline.h b/src/plugins/cpptools/cppeditoroutline.h
index 1e8a8fc76a3..c40ef4327d1 100644
--- a/src/plugins/cppeditor/cppeditoroutline.h
+++ b/src/plugins/cpptools/cppeditoroutline.h
@@ -31,6 +31,8 @@
#ifndef CPPEDITOROUTLINE_H
#define CPPEDITOROUTLINE_H
+#include "cpptools_global.h"
+
#include <QModelIndex>
#include <QObject>
@@ -41,20 +43,18 @@ class QTimer;
QT_END_NAMESPACE
namespace CPlusPlus { class OverviewModel; }
+namespace TextEditor { class TextEditorWidget; }
namespace Utils { class TreeViewComboBox; }
-namespace CppEditor {
-namespace Internal {
-
-class CppEditorWidget;
+namespace CppTools {
-class CppEditorOutline : public QObject
+class CPPTOOLS_EXPORT CppEditorOutline : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(CppEditorOutline)
public:
- explicit CppEditorOutline(CppEditorWidget *editorWidget);
+ explicit CppEditorOutline(TextEditor::TextEditorWidget *editorWidget);
void update();
@@ -84,7 +84,7 @@ private:
const QModelIndex &rootIndex = QModelIndex()) const;
private:
- CppEditorWidget *m_editorWidget;
+ TextEditor::TextEditorWidget *m_editorWidget;
Utils::TreeViewComboBox *m_combo; // Not owned
CPlusPlus::OverviewModel *m_model;
@@ -95,7 +95,6 @@ private:
QTimer *m_updateIndexTimer;
};
-} // namespace Internal
-} // namespace CppEditor
+} // namespace CppTools
#endif // CPPEDITOROUTLINE_H
diff --git a/src/plugins/cpptools/cppfilesettingspage.cpp b/src/plugins/cpptools/cppfilesettingspage.cpp
index 7b617496e0c..449095664ee 100644
--- a/src/plugins/cpptools/cppfilesettingspage.cpp
+++ b/src/plugins/cpptools/cppfilesettingspage.cpp
@@ -40,11 +40,11 @@
#include <cppeditor/cppeditorconstants.h>
#include <utils/environment.h>
+#include <utils/fileutils.h>
#include <QSettings>
#include <QDebug>
#include <QFile>
-#include <QFileInfo>
#include <QCoreApplication>
#include <QDate>
#include <QLocale>
@@ -157,7 +157,7 @@ static bool keyWordReplacement(const QString &keyWord,
return true;
}
if (keyWord == QLatin1String("%FILENAME%")) {
- *value = QFileInfo(file).fileName();
+ *value = Utils::FileName::fromString(file).fileName();
return true;
}
if (keyWord == QLatin1String("%DATE%")) {
diff --git a/src/plugins/cpptools/cppfindreferences.cpp b/src/plugins/cpptools/cppfindreferences.cpp
index 369e05f82df..514dd577812 100644
--- a/src/plugins/cpptools/cppfindreferences.cpp
+++ b/src/plugins/cpptools/cppfindreferences.cpp
@@ -55,7 +55,7 @@ using namespace CppTools::Internal;
using namespace CppTools;
using namespace CPlusPlus;
-static QByteArray getSource(const QString &fileName,
+static QByteArray getSource(const Utils::FileName &fileName,
const WorkingCopy &workingCopy)
{
if (workingCopy.contains(fileName)) {
@@ -66,7 +66,7 @@ static QByteArray getSource(const QString &fileName,
QString error;
QTextCodec *defaultCodec = EditorManager::defaultTextCodec();
Utils::TextFileFormat::ReadResult result = Utils::TextFileFormat::readFile(
- fileName, defaultCodec, &fileContents, &format, &error);
+ fileName.toString(), defaultCodec, &fileContents, &format, &error);
if (result != Utils::TextFileFormat::ReadSuccess)
qWarning() << "Could not read " << fileName << ". Error: " << error;
@@ -141,8 +141,8 @@ static QByteArray idForSymbol(Symbol *symbol)
// add the index of this symbol within its enclosing scope
// (counting symbols without identifier of the same type)
int count = 0;
- Scope::iterator it = scope->firstMember();
- while (it != scope->lastMember() && *it != symbol) {
+ Scope::iterator it = scope->memberBegin();
+ while (it != scope->memberEnd() && *it != symbol) {
Symbol *val = *it;
++it;
if (val->identifier() || typeId(val) != uid)
@@ -188,7 +188,7 @@ public:
future(future)
{ }
- QList<Usage> operator()(const QString &fileName)
+ QList<Usage> operator()(const Utils::FileName &fileName)
{
QList<Usage> usages;
if (future->isPaused())
@@ -205,7 +205,7 @@ public:
Document::Ptr doc;
const QByteArray unpreprocessedSource = getSource(fileName, workingCopy);
- if (symbolDocument && fileName == symbolDocument->fileName()) {
+ if (symbolDocument && fileName == Utils::FileName::fromString(symbolDocument->fileName())) {
doc = symbolDocument;
} else {
doc = snapshot.preprocessedDocument(unpreprocessedSource, fileName);
@@ -278,22 +278,24 @@ static void find_helper(QFutureInterface<Usage> &future,
const Snapshot snapshot = context.snapshot();
- const QString sourceFile = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());
- QStringList files(sourceFile);
+ const Utils::FileName sourceFile = Utils::FileName::fromUtf8(symbol->fileName(),
+ symbol->fileNameLength());
+ Utils::FileNameList files(sourceFile);
if (symbol->isClass()
|| symbol->isForwardClassDeclaration()
|| (symbol->enclosingScope()
&& !symbol->isStatic()
&& symbol->enclosingScope()->isNamespace())) {
- foreach (const Document::Ptr &doc, context.snapshot()) {
- if (doc->fileName() == sourceFile)
+ const Snapshot snapshotFromContext = context.snapshot();
+ for (auto i = snapshotFromContext.begin(), ei = snapshotFromContext.end(); i != ei; ++i) {
+ if (i.key() == sourceFile)
continue;
- Control *control = doc->control();
+ const Control *control = i.value()->control();
if (control->findIdentifier(symbolId->chars(), symbolId->size()))
- files.append(doc->fileName());
+ files.append(i.key());
}
} else {
files += snapshot.filesDependingOn(sourceFile);
@@ -312,24 +314,23 @@ static void find_helper(QFutureInterface<Usage> &future,
future.setProgressValue(files.size());
}
-void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol,
- const CPlusPlus::LookupContext &context)
+void CppFindReferences::findUsages(Symbol *symbol, const LookupContext &context)
{
findUsages(symbol, context, QString(), false);
}
-void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol,
- const CPlusPlus::LookupContext &context,
+void CppFindReferences::findUsages(Symbol *symbol,
+ const LookupContext &context,
const QString &replacement,
bool replace)
{
Overview overview;
- Core::SearchResult *search = Core::SearchResultWindow::instance()->startNewSearch(tr("C++ Usages:"),
+ SearchResult *search = SearchResultWindow::instance()->startNewSearch(tr("C++ Usages:"),
QString(),
overview.prettyName(context.fullyQualifiedName(symbol)),
- replace ? Core::SearchResultWindow::SearchAndReplace
- : Core::SearchResultWindow::SearchOnly,
- Core::SearchResultWindow::PreserveCaseDisabled,
+ replace ? SearchResultWindow::SearchAndReplace
+ : SearchResultWindow::SearchOnly,
+ SearchResultWindow::PreserveCaseDisabled,
QLatin1String("CppEditor"));
search->setTextToReplace(replacement);
connect(search, SIGNAL(replaceButtonClicked(QString,QList<Core::SearchResultItem>,bool)),
@@ -344,7 +345,7 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol,
findAll_helper(search, symbol, context);
}
-void CppFindReferences::renameUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context,
+void CppFindReferences::renameUsages(Symbol *symbol, const LookupContext &context,
const QString &replacement)
{
if (const Identifier *id = symbol->identifier()) {
@@ -354,8 +355,8 @@ void CppFindReferences::renameUsages(CPlusPlus::Symbol *symbol, const CPlusPlus:
}
}
-void CppFindReferences::findAll_helper(Core::SearchResult *search, CPlusPlus::Symbol *symbol,
- const CPlusPlus::LookupContext &context)
+void CppFindReferences::findAll_helper(SearchResult *search, Symbol *symbol,
+ const LookupContext &context)
{
if (!(symbol && symbol->identifier())) {
search->finishSearch(false);
@@ -365,7 +366,7 @@ void CppFindReferences::findAll_helper(Core::SearchResult *search, CPlusPlus::Sy
connect(search, SIGNAL(activated(Core::SearchResultItem)),
this, SLOT(openEditor(Core::SearchResultItem)));
- Core::SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
+ SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
const WorkingCopy workingCopy = m_modelManager->workingCopy();
QFuture<Usage> result;
result = QtConcurrent::run(&find_helper, workingCopy, context, symbol);
@@ -378,19 +379,19 @@ void CppFindReferences::findAll_helper(Core::SearchResult *search, CPlusPlus::Sy
}
void CppFindReferences::onReplaceButtonClicked(const QString &text,
- const QList<Core::SearchResultItem> &items,
+ const QList<SearchResultItem> &items,
bool preserveCase)
{
const QStringList fileNames = TextEditor::BaseFileFind::replaceAll(text, items, preserveCase);
if (!fileNames.isEmpty()) {
m_modelManager->updateSourceFiles(fileNames.toSet());
- Core::SearchResultWindow::instance()->hide();
+ SearchResultWindow::instance()->hide();
}
}
void CppFindReferences::searchAgain()
{
- Core::SearchResult *search = qobject_cast<Core::SearchResult *>(sender());
+ SearchResult *search = qobject_cast<SearchResult *>(sender());
CppFindReferencesParameters parameters = search->userData().value<CppFindReferencesParameters>();
Snapshot snapshot = CppModelManager::instance()->snapshot();
search->restart();
@@ -442,7 +443,7 @@ private:
};
}
-CPlusPlus::Symbol *CppFindReferences::findSymbol(const CppFindReferencesParameters &parameters,
+Symbol *CppFindReferences::findSymbol(const CppFindReferencesParameters &parameters,
const Snapshot &snapshot, LookupContext *context)
{
QTC_ASSERT(context, return 0);
@@ -452,7 +453,8 @@ CPlusPlus::Symbol *CppFindReferences::findSymbol(const CppFindReferencesParamete
Document::Ptr newSymbolDocument = snapshot.document(symbolFile);
// document is not parsed and has no bindings yet, do it
- QByteArray source = getSource(newSymbolDocument->fileName(), m_modelManager->workingCopy());
+ QByteArray source = getSource(Utils::FileName::fromString(newSymbolDocument->fileName()),
+ m_modelManager->workingCopy());
Document::Ptr doc =
snapshot.preprocessedDocument(source, newSymbolDocument->fileName());
doc->check();
@@ -470,7 +472,7 @@ CPlusPlus::Symbol *CppFindReferences::findSymbol(const CppFindReferencesParamete
void CppFindReferences::displayResults(int first, int last)
{
QFutureWatcher<Usage> *watcher = static_cast<QFutureWatcher<Usage> *>(sender());
- Core::SearchResult *search = m_watchers.value(watcher);
+ SearchResult *search = m_watchers.value(watcher);
if (!search) {
// search was deleted while it was running
watcher->cancel();
@@ -489,7 +491,7 @@ void CppFindReferences::displayResults(int first, int last)
void CppFindReferences::searchFinished()
{
QFutureWatcher<Usage> *watcher = static_cast<QFutureWatcher<Usage> *>(sender());
- Core::SearchResult *search = m_watchers.value(watcher);
+ SearchResult *search = m_watchers.value(watcher);
if (search)
search->finishSearch(watcher->isCanceled());
m_watchers.remove(watcher);
@@ -498,7 +500,7 @@ void CppFindReferences::searchFinished()
void CppFindReferences::cancel()
{
- Core::SearchResult *search = qobject_cast<Core::SearchResult *>(sender());
+ SearchResult *search = qobject_cast<SearchResult *>(sender());
QTC_ASSERT(search, return);
QFutureWatcher<Usage> *watcher = m_watchers.key(search);
QTC_ASSERT(watcher, return);
@@ -507,7 +509,7 @@ void CppFindReferences::cancel()
void CppFindReferences::setPaused(bool paused)
{
- Core::SearchResult *search = qobject_cast<Core::SearchResult *>(sender());
+ SearchResult *search = qobject_cast<SearchResult *>(sender());
QTC_ASSERT(search, return);
QFutureWatcher<Usage> *watcher = m_watchers.key(search);
QTC_ASSERT(watcher, return);
@@ -515,7 +517,7 @@ void CppFindReferences::setPaused(bool paused)
watcher->setPaused(paused);
}
-void CppFindReferences::openEditor(const Core::SearchResultItem &item)
+void CppFindReferences::openEditor(const SearchResultItem &item)
{
if (item.path.size() > 0) {
EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
@@ -543,7 +545,7 @@ public:
: workingCopy(workingCopy), snapshot(snapshot), macro(macro), future(future)
{ }
- QList<Usage> operator()(const QString &fileName)
+ QList<Usage> operator()(const Utils::FileName &fileName)
{
QList<Usage> usages;
Document::Ptr doc = snapshot.document(fileName);
@@ -573,7 +575,7 @@ restart_search:
if (macro.name() == useMacro.name()) {
unsigned column;
const QString &lineSource = matchingLine(use.bytesBegin(), source, &column);
- usages.append(Usage(fileName, lineSource, use.beginLine(), column,
+ usages.append(Usage(fileName.toString(), lineSource, use.beginLine(), column,
useMacro.nameToQString().size()));
}
}
@@ -614,8 +616,8 @@ static void findMacroUses_helper(QFutureInterface<Usage> &future,
const Snapshot snapshot,
const Macro macro)
{
- const QString& sourceFile = macro.fileName();
- QStringList files(sourceFile);
+ const Utils::FileName sourceFile = Utils::FileName::fromString(macro.fileName());
+ Utils::FileNameList files(sourceFile);
files += snapshot.filesDependingOn(sourceFile);
files.removeDuplicates();
@@ -637,20 +639,20 @@ void CppFindReferences::findMacroUses(const Macro &macro)
void CppFindReferences::findMacroUses(const Macro &macro, const QString &replacement, bool replace)
{
- Core::SearchResult *search = Core::SearchResultWindow::instance()->startNewSearch(
+ SearchResult *search = SearchResultWindow::instance()->startNewSearch(
tr("C++ Macro Usages:"),
QString(),
macro.nameToQString(),
- replace ? Core::SearchResultWindow::SearchAndReplace
- : Core::SearchResultWindow::SearchOnly,
- Core::SearchResultWindow::PreserveCaseDisabled,
+ replace ? SearchResultWindow::SearchAndReplace
+ : SearchResultWindow::SearchOnly,
+ SearchResultWindow::PreserveCaseDisabled,
QLatin1String("CppEditor"));
search->setTextToReplace(replacement);
connect(search, SIGNAL(replaceButtonClicked(QString,QList<Core::SearchResultItem>,bool)),
SLOT(onReplaceButtonClicked(QString,QList<Core::SearchResultItem>,bool)));
- Core::SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
+ SearchResultWindow::instance()->popup(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
connect(search, SIGNAL(activated(Core::SearchResultItem)),
this, SLOT(openEditor(Core::SearchResultItem)));
@@ -662,7 +664,8 @@ void CppFindReferences::findMacroUses(const Macro &macro, const QString &replace
// add the macro definition itself
{
- const QByteArray &source = getSource(macro.fileName(), workingCopy);
+ const QByteArray &source = getSource(Utils::FileName::fromString(macro.fileName()),
+ workingCopy);
unsigned column;
const QString line = FindMacroUsesInFile::matchingLine(macro.bytesOffset(), source,
&column);
@@ -685,7 +688,7 @@ void CppFindReferences::renameMacroUses(const Macro &macro, const QString &repla
findMacroUses(macro, textToReplace, true);
}
-void CppFindReferences::createWatcher(const QFuture<Usage> &future, Core::SearchResult *search)
+void CppFindReferences::createWatcher(const QFuture<Usage> &future, SearchResult *search)
{
QFutureWatcher<Usage> *watcher = new QFutureWatcher<Usage>();
watcher->setPendingResultsLimit(1);
diff --git a/src/plugins/cpptools/cppheadersource_test.cpp b/src/plugins/cpptools/cppheadersource_test.cpp
index 7d82d999147..a18fd326e47 100644
--- a/src/plugins/cpptools/cppheadersource_test.cpp
+++ b/src/plugins/cpptools/cppheadersource_test.cpp
@@ -30,6 +30,7 @@
#include "cpptoolsplugin.h"
#include "cpptoolsreuse.h"
+#include "cpptoolstestcase.h"
#include "cppfilesettingspage.h"
#include <utils/fileutils.h>
@@ -60,15 +61,16 @@ void CppToolsPlugin::test_headersource()
QFETCH(QString, sourceFileName);
QFETCH(QString, headerFileName);
- bool wasHeader;
- const QString baseDir = baseTestDir();
- QDir path = QDir(baseDir + _(QTest::currentDataTag()));
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+ const QDir path = QDir(temporaryDir.path() + QLatin1Char('/') + _(QTest::currentDataTag()));
const QString sourcePath = path.absoluteFilePath(sourceFileName);
const QString headerPath = path.absoluteFilePath(headerFileName);
createTempFile(sourcePath);
createTempFile(headerPath);
+ bool wasHeader;
clearHeaderSourceCache();
QCOMPARE(correspondingHeaderOrSource(sourcePath, &wasHeader), headerPath);
QVERIFY(!wasHeader);
diff --git a/src/plugins/cpptools/cppincludesfilter.cpp b/src/plugins/cpptools/cppincludesfilter.cpp
new file mode 100644
index 00000000000..1ed1d19c375
--- /dev/null
+++ b/src/plugins/cpptools/cppincludesfilter.cpp
@@ -0,0 +1,189 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "cppincludesfilter.h"
+
+#include "cppmodelmanager.h"
+
+#include <cplusplus/CppDocument.h>
+#include <coreplugin/editormanager/documentmodel.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/session.h>
+
+#include <QTimer>
+
+using namespace Core;
+using namespace CppTools;
+using namespace CppTools::Internal;
+using namespace ProjectExplorer;
+namespace CppTools {
+namespace Internal {
+
+class CppIncludesIterator : public BaseFileFilter::Iterator
+{
+public:
+ CppIncludesIterator(CPlusPlus::Snapshot snapshot, const QSet<QString> &seedPaths);
+
+ void toFront();
+ bool hasNext() const;
+ QString next();
+ QString filePath() const;
+ QString fileName() const;
+
+private:
+ void fetchMore();
+
+ CPlusPlus::Snapshot m_snapshot;
+ QSet<QString> m_paths;
+ QSet<QString> m_queuedPaths;
+ QSet<QString> m_allResultPaths;
+ QStringList m_resultQueue;
+ QString m_currentPath;
+};
+
+} // Internal
+} // CppTools
+
+
+CppIncludesIterator::CppIncludesIterator(CPlusPlus::Snapshot snapshot,
+ const QSet<QString> &seedPaths)
+ : m_snapshot(snapshot),
+ m_paths(seedPaths)
+{
+ toFront();
+}
+
+void CppIncludesIterator::toFront()
+{
+ m_queuedPaths = m_paths;
+ m_allResultPaths.clear();
+ m_resultQueue.clear();
+ fetchMore();
+}
+
+bool CppIncludesIterator::hasNext() const
+{
+ return !m_resultQueue.isEmpty();
+}
+
+QString CppIncludesIterator::next()
+{
+ if (m_resultQueue.isEmpty())
+ return QString();
+ m_currentPath = m_resultQueue.takeFirst();
+ if (m_resultQueue.isEmpty())
+ fetchMore();
+ return m_currentPath;
+}
+
+QString CppIncludesIterator::filePath() const
+{
+ return m_currentPath;
+}
+
+QString CppIncludesIterator::fileName() const
+{
+ return QFileInfo(m_currentPath).fileName();
+}
+
+void CppIncludesIterator::fetchMore()
+{
+ while (!m_queuedPaths.isEmpty() && m_resultQueue.isEmpty()) {
+ const QString filePath = *m_queuedPaths.begin();
+ m_queuedPaths.remove(filePath);
+ CPlusPlus::Document::Ptr doc = m_snapshot.document(filePath);
+ if (!doc)
+ continue;
+ foreach (const QString &includedPath, doc->includedFiles()) {
+ if (!m_allResultPaths.contains(includedPath)) {
+ m_allResultPaths.insert(includedPath);
+ m_queuedPaths.insert(includedPath);
+ m_resultQueue.append(includedPath);
+ }
+ }
+ }
+}
+
+CppIncludesFilter::CppIncludesFilter()
+ : m_needsUpdate(true)
+{
+ setId("All Included C/C++ Files");
+ setDisplayName(tr("All Included C/C++ Files"));
+ setShortcutString(QString(QLatin1Char('a')));
+ setIncludedByDefault(true);
+ setPriority(ILocatorFilter::Low);
+
+ connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::fileListChanged,
+ this, &CppIncludesFilter::markOutdated);
+ connect(CppModelManager::instance(), &CppModelManager::documentUpdated,
+ this, &CppIncludesFilter::markOutdated);
+ connect(CppModelManager::instance(), &CppModelManager::aboutToRemoveFiles,
+ this, &CppIncludesFilter::markOutdated);
+ connect(DocumentModel::model(), &QAbstractItemModel::rowsInserted,
+ this, &CppIncludesFilter::markOutdated);
+ connect(DocumentModel::model(), &QAbstractItemModel::rowsRemoved,
+ this, &CppIncludesFilter::markOutdated);
+ connect(DocumentModel::model(), &QAbstractItemModel::dataChanged,
+ this, &CppIncludesFilter::markOutdated);
+ connect(DocumentModel::model(), &QAbstractItemModel::modelReset,
+ this, &CppIncludesFilter::markOutdated);
+}
+
+void CppIncludesFilter::prepareSearch(const QString &entry)
+{
+ Q_UNUSED(entry)
+ if (m_needsUpdate) {
+ m_needsUpdate = false;
+ QSet<QString> seedPaths;
+ foreach (Project *project, SessionManager::projects()) {
+ foreach (const QString &filePath, project->files(Project::AllFiles))
+ seedPaths.insert(filePath);
+ }
+ foreach (DocumentModel::Entry *entry, DocumentModel::entries()) {
+ if (entry)
+ seedPaths.insert(entry->fileName());
+ }
+ CPlusPlus::Snapshot snapshot = CppModelManager::instance()->snapshot();
+ setFileIterator(new CppIncludesIterator(snapshot, seedPaths));
+ }
+ BaseFileFilter::prepareSearch(entry);
+}
+
+void CppIncludesFilter::refresh(QFutureInterface<void> &future)
+{
+ Q_UNUSED(future)
+ QTimer::singleShot(0, this, SLOT(markOutdated()));
+}
+
+void CppIncludesFilter::markOutdated()
+{
+ m_needsUpdate = true;
+ setFileIterator(0); // clean up
+}
diff --git a/src/plugins/cpptools/cppincludesfilter.h b/src/plugins/cpptools/cppincludesfilter.h
new file mode 100644
index 00000000000..8de49179446
--- /dev/null
+++ b/src/plugins/cpptools/cppincludesfilter.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 CPPINCLUDESFILTER_H
+#define CPPINCLUDESFILTER_H
+
+#include <coreplugin/locator/basefilefilter.h>
+
+namespace CppTools {
+namespace Internal {
+
+class CppIncludesFilter : public Core::BaseFileFilter
+{
+ Q_OBJECT
+
+public:
+ CppIncludesFilter();
+
+ // ILocatorFilter interface
+public:
+ void prepareSearch(const QString &entry);
+ void refresh(QFutureInterface<void> &future);
+
+private slots:
+ void markOutdated();
+
+private:
+ bool m_needsUpdate;
+};
+
+} // namespace Internal
+} // namespace CppTools
+
+#endif // CPPINCLUDESFILTER_H
diff --git a/src/plugins/cpptools/cpplocalsymbols.cpp b/src/plugins/cpptools/cpplocalsymbols.cpp
index 19cc722a690..0f1c7bafacd 100644
--- a/src/plugins/cpptools/cpplocalsymbols.cpp
+++ b/src/plugins/cpptools/cpplocalsymbols.cpp
@@ -306,7 +306,7 @@ private:
} // end of anonymous namespace
-LocalSymbols::LocalSymbols(CPlusPlus::Document::Ptr doc, CPlusPlus::DeclarationAST *ast)
+LocalSymbols::LocalSymbols(Document::Ptr doc, DeclarationAST *ast)
{
FindLocalSymbols findLocalSymbols(doc);
findLocalSymbols(ast);
diff --git a/src/plugins/cpptools/cpplocatordata.cpp b/src/plugins/cpptools/cpplocatordata.cpp
index eea0ec55f92..3ca5374dbfc 100644
--- a/src/plugins/cpptools/cpplocatordata.cpp
+++ b/src/plugins/cpptools/cpplocatordata.cpp
@@ -54,8 +54,7 @@ void CppLocatorData::onDocumentUpdated(const CPlusPlus::Document::Ptr &document)
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()) {
+ if (doc->fileName() == document->fileName() && doc->revision() <= document->revision()) {
m_pendingDocuments[i] = document;
break;
}
diff --git a/src/plugins/cpptools/cpplocatorfilter.cpp b/src/plugins/cpptools/cpplocatorfilter.cpp
index 6c493fd52e1..9436736cc94 100644
--- a/src/plugins/cpptools/cpplocatorfilter.cpp
+++ b/src/plugins/cpptools/cpplocatorfilter.cpp
@@ -120,6 +120,6 @@ QList<Core::LocatorFilterEntry> CppLocatorFilter::matchesFor(
void CppLocatorFilter::accept(Core::LocatorFilterEntry selection) const
{
- IndexItem::Ptr info = qvariant_cast<CppTools::IndexItem::Ptr>(selection.internalData);
+ IndexItem::Ptr info = qvariant_cast<IndexItem::Ptr>(selection.internalData);
Core::EditorManager::openEditorAt(info->fileName(), info->line(), info->column());
}
diff --git a/src/plugins/cpptools/cpplocatorfilter_test.cpp b/src/plugins/cpptools/cpplocatorfilter_test.cpp
index 467f64869ed..42c67664bcc 100644
--- a/src/plugins/cpptools/cpplocatorfilter_test.cpp
+++ b/src/plugins/cpptools/cpplocatorfilter_test.cpp
@@ -153,6 +153,8 @@ void CppToolsPlugin::test_cpplocatorfilters_CppLocatorFilter()
QFETCH(QString, searchText);
QFETCH(ResultDataList, expectedResults);
+ Tests::VerifyCleanCppModelManager verify;
+
CppLocatorFilterTestCase(filter, testFile, searchText, expectedResults);
}
diff --git a/src/plugins/cpptools/cppmodelmanager.cpp b/src/plugins/cpptools/cppmodelmanager.cpp
index dec6c5d8937..cf9858498d5 100644
--- a/src/plugins/cpptools/cppmodelmanager.cpp
+++ b/src/plugins/cpptools/cppmodelmanager.cpp
@@ -49,6 +49,7 @@
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <extensionsystem/pluginmanager.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
@@ -124,13 +125,13 @@ class CppModelManagerPrivate
public:
// Snapshot
mutable QMutex m_snapshotMutex;
- CPlusPlus::Snapshot m_snapshot;
+ Snapshot m_snapshot;
// Project integration
mutable QMutex m_projectMutex;
QMap<ProjectExplorer::Project *, ProjectInfo> m_projectToProjectsInfo;
- QMap<QString, QList<CppTools::ProjectPart::Ptr> > m_fileToProjectParts;
- QMap<QString, CppTools::ProjectPart::Ptr> m_projectFileToProjectPart;
+ QMap<Utils::FileName, QList<ProjectPart::Ptr> > m_fileToProjectParts;
+ QMap<QString, ProjectPart::Ptr> m_projectFileToProjectPart;
// The members below are cached/(re)calculated from the projects and/or their project parts
bool m_dirty;
QStringList m_projectFiles;
@@ -138,8 +139,8 @@ public:
QByteArray m_definedMacros;
// Editor integration
- mutable QMutex m_cppEditorsMutex;
- QMap<QString, EditorDocumentHandle *> m_cppEditors;
+ mutable QMutex m_cppEditorDocumentsMutex;
+ QMap<QString, CppEditorDocumentHandle *> m_cppEditorDocuments;
QSet<AbstractEditorSupport *> m_extraEditorSupports;
// Completion & highlighting
@@ -235,7 +236,7 @@ QString CppModelManager::editorConfigurationFileName()
QString CppModelManager::configurationFileName()
{
- return CPlusPlus::Preprocessor::configurationFileName;
+ return Preprocessor::configurationFileName;
}
void CppModelManager::updateModifiedSourceFiles()
@@ -311,7 +312,7 @@ CppModelManager::CppModelManager(QObject *parent)
this, SLOT(onCoreAboutToClose()));
qRegisterMetaType<CPlusPlus::Document::Ptr>("CPlusPlus::Document::Ptr");
- qRegisterMetaType<QList<CPlusPlus::Document::DiagnosticMessage>>(
+ qRegisterMetaType<QList<Document::DiagnosticMessage>>(
"QList<CPlusPlus::Document::DiagnosticMessage>");
d->m_modelManagerSupportFallback.reset(new ModelManagerSupportInternal);
@@ -461,27 +462,27 @@ void CppModelManager::removeExtraEditorSupport(AbstractEditorSupport *editorSupp
d->m_extraEditorSupports.remove(editorSupport);
}
-EditorDocumentHandle *CppModelManager::editorDocument(const QString &filePath) const
+CppEditorDocumentHandle *CppModelManager::cppEditorDocument(const QString &filePath) const
{
if (filePath.isEmpty())
return 0;
- QMutexLocker locker(&d->m_cppEditorsMutex);
- return d->m_cppEditors.value(filePath, 0);
+ QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
+ return d->m_cppEditorDocuments.value(filePath, 0);
}
-void CppModelManager::registerEditorDocument(EditorDocumentHandle *editorDocument)
+void CppModelManager::registerCppEditorDocument(CppEditorDocumentHandle *editorDocument)
{
QTC_ASSERT(editorDocument, return);
const QString filePath = editorDocument->filePath();
QTC_ASSERT(!filePath.isEmpty(), return);
- QMutexLocker locker(&d->m_cppEditorsMutex);
- QTC_ASSERT(d->m_cppEditors.value(filePath, 0) == 0, return);
- d->m_cppEditors.insert(filePath, editorDocument);
+ QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
+ QTC_ASSERT(d->m_cppEditorDocuments.value(filePath, 0) == 0, return);
+ d->m_cppEditorDocuments.insert(filePath, editorDocument);
}
-void CppModelManager::unregisterEditorDocument(const QString &filePath)
+void CppModelManager::unregisterCppEditorDocument(const QString &filePath)
{
QTC_ASSERT(!filePath.isEmpty(), return);
@@ -489,10 +490,10 @@ void CppModelManager::unregisterEditorDocument(const QString &filePath)
int openCppDocuments = 0;
{
- QMutexLocker locker(&d->m_cppEditorsMutex);
- QTC_ASSERT(d->m_cppEditors.value(filePath, 0), return);
- QTC_CHECK(d->m_cppEditors.remove(filePath) == 1);
- openCppDocuments = d->m_cppEditors.size();
+ QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
+ QTC_ASSERT(d->m_cppEditorDocuments.value(filePath, 0), return);
+ QTC_CHECK(d->m_cppEditorDocuments.remove(filePath) == 1);
+ openCppDocuments = d->m_cppEditorDocuments.size();
}
++closedCppDocuments;
@@ -502,36 +503,36 @@ void CppModelManager::unregisterEditorDocument(const QString &filePath)
}
}
-QList<int> CppModelManager::references(CPlusPlus::Symbol *symbol, const LookupContext &context)
+QList<int> CppModelManager::references(Symbol *symbol, const LookupContext &context)
{
return d->m_findReferences->references(symbol, context);
}
-void CppModelManager::findUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context)
+void CppModelManager::findUsages(Symbol *symbol, const LookupContext &context)
{
if (symbol->identifier())
d->m_findReferences->findUsages(symbol, context);
}
-void CppModelManager::renameUsages(CPlusPlus::Symbol *symbol,
- const CPlusPlus::LookupContext &context,
+void CppModelManager::renameUsages(Symbol *symbol,
+ const LookupContext &context,
const QString &replacement)
{
if (symbol->identifier())
d->m_findReferences->renameUsages(symbol, context, replacement);
}
-void CppModelManager::findMacroUsages(const CPlusPlus::Macro &macro)
+void CppModelManager::findMacroUsages(const Macro &macro)
{
d->m_findReferences->findMacroUses(macro);
}
-void CppModelManager::renameMacroUsages(const CPlusPlus::Macro &macro, const QString &replacement)
+void CppModelManager::renameMacroUsages(const Macro &macro, const QString &replacement)
{
d->m_findReferences->renameMacroUses(macro, replacement);
}
-void CppModelManager::replaceSnapshot(const CPlusPlus::Snapshot &newSnapshot)
+void CppModelManager::replaceSnapshot(const Snapshot &newSnapshot)
{
QMutexLocker snapshotLocker(&d->m_snapshotMutex);
d->m_snapshot = newSnapshot;
@@ -541,8 +542,11 @@ WorkingCopy CppModelManager::buildWorkingCopyList()
{
WorkingCopy workingCopy;
- foreach (const EditorDocumentHandle *cppEditor, cppEditors())
- workingCopy.insert(cppEditor->filePath(), cppEditor->contents(), cppEditor->revision());
+ foreach (const CppEditorDocumentHandle *cppEditorDocument, cppEditorDocuments()) {
+ workingCopy.insert(cppEditorDocument->filePath(),
+ cppEditorDocument->contents(),
+ cppEditorDocument->revision());
+ }
QSetIterator<AbstractEditorSupport *> it(d->m_extraEditorSupports);
while (it.hasNext()) {
@@ -588,7 +592,7 @@ QList<ProjectInfo> CppModelManager::projectInfos() const
ProjectInfo CppModelManager::projectInfo(ProjectExplorer::Project *project) const
{
QMutexLocker locker(&d->m_projectMutex);
- return d->m_projectToProjectsInfo.value(project, ProjectInfo(project));
+ return d->m_projectToProjectsInfo.value(project, ProjectInfo());
}
/// \brief Remove all files and their includes (recursively) of given ProjectInfo from the snapshot.
@@ -607,10 +611,10 @@ void CppModelManager::removeProjectInfoFilesAndIncludesFromSnapshot(const Projec
}
}
-QList<EditorDocumentHandle *> CppModelManager::cppEditors() const
+QList<CppEditorDocumentHandle *> CppModelManager::cppEditorDocuments() const
{
- QMutexLocker locker(&d->m_cppEditorsMutex);
- return d->m_cppEditors.values();
+ QMutexLocker locker(&d->m_cppEditorDocumentsMutex);
+ return d->m_cppEditorDocuments.values();
}
/// \brief Remove all given files from the snapshot.
@@ -685,7 +689,8 @@ void CppModelManager::recalculateFileToProjectParts()
foreach (const ProjectPart::Ptr &projectPart, projectInfo.projectParts()) {
d->m_projectFileToProjectPart[projectPart->projectFile] = projectPart;
foreach (const ProjectFile &cxxFile, projectPart->files)
- d->m_fileToProjectParts[cxxFile.path].append(projectPart);
+ d->m_fileToProjectParts[Utils::FileName::fromString(cxxFile.path)].append(
+ projectPart);
}
}
@@ -697,9 +702,10 @@ void CppModelManager::updateCppEditorDocuments() const
QSet<Core::IDocument *> visibleCppEditorDocuments;
foreach (Core::IEditor *editor, Core::EditorManager::visibleEditors()) {
if (Core::IDocument *document = editor->document()) {
- if (EditorDocumentHandle *cppEditorDocument = editorDocument(document->filePath())) {
+ const QString filePath = document->filePath().toString();
+ if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath)) {
visibleCppEditorDocuments.insert(document);
- cppEditorDocument->processor()->run();
+ theCppEditorDocument->processor()->run();
}
}
}
@@ -709,8 +715,9 @@ void CppModelManager::updateCppEditorDocuments() const
= Core::DocumentModel::openedDocuments().toSet();
invisibleCppEditorDocuments.subtract(visibleCppEditorDocuments);
foreach (Core::IDocument *document, invisibleCppEditorDocuments) {
- if (EditorDocumentHandle *cppEditorDocument = editorDocument(document->filePath()))
- cppEditorDocument->setNeedsRefresh(true);
+ const QString filePath = document->filePath().toString();
+ if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath))
+ theCppEditorDocument->setNeedsRefresh(true);
}
}
@@ -804,21 +811,21 @@ ProjectPart::Ptr CppModelManager::projectPartForProjectFile(const QString &proje
return d->m_projectFileToProjectPart.value(projectFile);
}
-QList<ProjectPart::Ptr> CppModelManager::projectPart(const QString &fileName) const
+QList<ProjectPart::Ptr> CppModelManager::projectPart(const Utils::FileName &fileName) const
{
QMutexLocker locker(&d->m_projectMutex);
return d->m_fileToProjectParts.value(fileName);
}
-QList<ProjectPart::Ptr> CppModelManager::projectPartFromDependencies(const QString &fileName) const
+QList<ProjectPart::Ptr> CppModelManager::projectPartFromDependencies(
+ const Utils::FileName &fileName) const
{
QSet<ProjectPart::Ptr> parts;
- const QStringList deps = snapshot().filesDependingOn(fileName);
+ const Utils::FileNameList deps = snapshot().filesDependingOn(fileName);
- {
- QMutexLocker locker(&d->m_projectMutex);
- foreach (const QString &dep, deps)
- parts.unite(QSet<ProjectPart::Ptr>::fromList(d->m_fileToProjectParts.value(dep)));
+ QMutexLocker locker(&d->m_projectMutex);
+ foreach (const Utils::FileName &dep, deps) {
+ parts.unite(QSet<ProjectPart::Ptr>::fromList(d->m_fileToProjectParts.value(dep)));
}
return parts.values();
@@ -885,10 +892,11 @@ void CppModelManager::onCurrentEditorChanged(Core::IEditor *editor)
if (!editor || !editor->document())
return;
- if (EditorDocumentHandle *cppEditorDocument = editorDocument(editor->document()->filePath())) {
- if (cppEditorDocument->needsRefresh()) {
- cppEditorDocument->setNeedsRefresh(false);
- cppEditorDocument->processor()->run();
+ const QString filePath = editor->document()->filePath().toString();
+ if (CppEditorDocumentHandle *theCppEditorDocument = cppEditorDocument(filePath)) {
+ if (theCppEditorDocument->needsRefresh()) {
+ theCppEditorDocument->setNeedsRefresh(false);
+ theCppEditorDocument->processor()->run();
}
}
}
@@ -952,8 +960,8 @@ void CppModelManager::GC()
// Collect files of opened editors and editor supports (e.g. ui code model)
QStringList filesInEditorSupports;
- foreach (const EditorDocumentHandle *cppEditor, cppEditors())
- filesInEditorSupports << cppEditor->filePath();
+ foreach (const CppEditorDocumentHandle *editorDocument, cppEditorDocuments())
+ filesInEditorSupports << editorDocument->filePath();
QSetIterator<AbstractEditorSupport *> jt(d->m_extraEditorSupports);
while (jt.hasNext()) {
@@ -962,7 +970,7 @@ void CppModelManager::GC()
}
Snapshot currentSnapshot = snapshot();
- QSet<QString> reachableFiles;
+ QSet<Utils::FileName> 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.
@@ -973,9 +981,10 @@ void CppModelManager::GC()
const QString file = todo.last();
todo.removeLast();
- if (reachableFiles.contains(file))
+ const Utils::FileName fileName = Utils::FileName::fromString(file);
+ if (reachableFiles.contains(fileName))
continue;
- reachableFiles.insert(file);
+ reachableFiles.insert(fileName);
if (Document::Ptr doc = currentSnapshot.document(file))
todo += doc->includedFiles();
@@ -985,12 +994,12 @@ void CppModelManager::GC()
QStringList notReachableFiles;
Snapshot newSnapshot;
for (Snapshot::const_iterator it = currentSnapshot.begin(); it != currentSnapshot.end(); ++it) {
- const QString fileName = it.key();
+ const Utils::FileName &fileName = it.key();
if (reachableFiles.contains(fileName))
newSnapshot.insert(it.value());
else
- notReachableFiles.append(fileName);
+ notReachableFiles.append(fileName.toString());
}
// Announce removing files and replace the snapshot
diff --git a/src/plugins/cpptools/cppmodelmanager.h b/src/plugins/cpptools/cppmodelmanager.h
index 03d20232607..929275fee20 100644
--- a/src/plugins/cpptools/cppmodelmanager.h
+++ b/src/plugins/cpptools/cppmodelmanager.h
@@ -55,7 +55,7 @@ namespace CppTools {
class AbstractEditorSupport;
class BaseEditorDocumentProcessor;
class CppCompletionAssistProvider;
-class EditorDocumentHandle;
+class CppEditorDocumentHandle;
class CppIndexingSupport;
class ModelManagerSupport;
class WorkingCopy;
@@ -63,6 +63,7 @@ class WorkingCopy;
namespace Internal {
class CppSourceProcessor;
class CppModelManagerPrivate;
+class ModelManagerTestHelper;
}
class CPPTOOLS_EXPORT CppModelManager : public CPlusPlus::CppModelManagerBase
@@ -96,10 +97,12 @@ public:
/// \return The project part with the given project file
ProjectPart::Ptr projectPartForProjectFile(const QString &projectFile) const;
/// \return All project parts that mention the given file name as one of the sources/headers.
- QList<ProjectPart::Ptr> projectPart(const QString &fileName) const;
+ QList<ProjectPart::Ptr> projectPart(const Utils::FileName &fileName) const;
+ QList<ProjectPart::Ptr> projectPart(const QString &fileName) const
+ { return projectPart(Utils::FileName::fromString(fileName)); }
/// This is a fall-back function: find all files that includes the file directly or indirectly,
/// and return its \c ProjectPart list for use with this file.
- QList<ProjectPart::Ptr> projectPartFromDependencies(const QString &fileName) const;
+ QList<ProjectPart::Ptr> projectPartFromDependencies(const Utils::FileName &fileName) const;
/// \return A synthetic \c ProjectPart which consists of all defines/includes/frameworks from
/// all loaded projects.
ProjectPart::Ptr fallbackProjectPart() const;
@@ -115,9 +118,9 @@ public:
void addExtraEditorSupport(AbstractEditorSupport *editorSupport);
void removeExtraEditorSupport(AbstractEditorSupport *editorSupport);
- EditorDocumentHandle *editorDocument(const QString &filePath) const;
- void registerEditorDocument(EditorDocumentHandle *editorDocument);
- void unregisterEditorDocument(const QString &filePath);
+ CppEditorDocumentHandle *cppEditorDocument(const QString &filePath) const;
+ void registerCppEditorDocument(CppEditorDocumentHandle *cppEditorDocument);
+ void unregisterCppEditorDocument(const QString &filePath);
QList<int> references(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context);
@@ -173,11 +176,12 @@ signals:
void gcFinished(); // Needed for tests.
public slots:
- virtual void updateModifiedSourceFiles();
- virtual void GC();
+ void updateModifiedSourceFiles();
+ void GC();
private slots:
// This should be executed in the GUI thread.
+ friend class Internal::ModelManagerTestHelper;
void onAboutToLoadSession();
void onAboutToUnloadSession();
void renameIncludes(const QString &oldFileName, const QString &newFileName);
@@ -196,7 +200,7 @@ private:
void removeFilesFromSnapshot(const QSet<QString> &removedFiles);
void removeProjectInfoFilesAndIncludesFromSnapshot(const ProjectInfo &projectInfo);
- QList<EditorDocumentHandle *> cppEditors() const;
+ QList<CppEditorDocumentHandle *> cppEditorDocuments() const;
WorkingCopy buildWorkingCopyList();
diff --git a/src/plugins/cpptools/cppmodelmanager_test.cpp b/src/plugins/cpptools/cppmodelmanager_test.cpp
index 37946a99dfa..a9ee6ccddd0 100644
--- a/src/plugins/cpptools/cppmodelmanager_test.cpp
+++ b/src/plugins/cpptools/cppmodelmanager_test.cpp
@@ -45,13 +45,12 @@
#include <utils/hostosinfo.h>
#include <QDebug>
-#include <QFileInfo>
-#include <QTemporaryDir>
#include <QtTest>
+using namespace CppTools;
using namespace CppTools::Internal;
+using namespace CppTools::Tests;
using namespace ProjectExplorer;
-using namespace CppTools;
typedef CPlusPlus::Document Document;
@@ -78,6 +77,15 @@ public:
{ return directory(_("sources")) + QLatin1Char('/') + fileName; }
};
+QStringList toAbsolutePaths(const QStringList &relativePathList,
+ const Tests::TemporaryCopiedDir &temporaryDir)
+{
+ QStringList result;
+ foreach (const QString &file, relativePathList)
+ result << temporaryDir.absolutePath(file.toUtf8());
+ return result;
+}
+
// TODO: When possible, use this helper class in all tests
class ProjectCreator
{
@@ -94,8 +102,7 @@ public:
projectFiles << projectDir.file(file);
Project *project = modelManagerTestHelper->createProject(name);
- projectInfo = CppModelManager::instance()->projectInfo(project);
- QCOMPARE(projectInfo.project().data(), project);
+ projectInfo = ProjectInfo(project);
ProjectPart::Ptr part(new ProjectPart);
part->languageVersion = ProjectPart::CXX14;
@@ -113,46 +120,6 @@ public:
QStringList projectFiles;
};
-/// Open and configure given project as example project and remove
-/// generated *.user file on destruction.
-///
-/// Requirement: No *.user file exists for the project.
-class ExampleProjectConfigurator
-{
-public:
- ExampleProjectConfigurator(const QString &projectFile)
- {
- const QString projectUserFile = projectFile + _(".user");
- QVERIFY(!QFileInfo::exists(projectUserFile));
-
- // Open project
- QString errorOpeningProject;
- m_project = ProjectExplorerPlugin::openProject(projectFile, &errorOpeningProject);
- QVERIFY(m_project);
- QVERIFY(errorOpeningProject.isEmpty());
-
- // Configure project
- m_project->configureAsExampleProject(QStringList());
-
- m_fileToRemove = projectUserFile;
- }
-
- ~ExampleProjectConfigurator()
- {
- QVERIFY(!m_fileToRemove.isEmpty());
- QVERIFY(QFile::remove(m_fileToRemove));
- }
-
- Project *project() const
- {
- return m_project;
- }
-
-private:
- Project *m_project;
- QString m_fileToRemove;
-};
-
/// Changes a file on the disk and restores its original contents on destruction
class FileChangerAndRestorer
{
@@ -182,13 +149,13 @@ public:
bool writeContents(const QByteArray &contents) const
{
- return CppTools::Tests::TestCase::writeFile(m_filePath, contents);
+ return TestCase::writeFile(m_filePath, contents);
}
private:
void restoreContents() const
{
- CppTools::Tests::TestCase::writeFile(m_filePath, m_originalFileContents);
+ TestCase::writeFile(m_filePath, m_originalFileContents);
}
QByteArray m_originalFileContents;
@@ -215,8 +182,7 @@ void CppToolsPlugin::test_modelmanager_paths_are_clean()
const MyTestDataDir testDataDir(_("testdata"));
Project *project = helper.createProject(_("test_modelmanager_paths_are_clean"));
- ProjectInfo pi = mm->projectInfo(project);
- QCOMPARE(pi.project().data(), project);
+ ProjectInfo pi = ProjectInfo(project);
typedef ProjectPart::HeaderPath HeaderPath;
@@ -251,8 +217,7 @@ void CppToolsPlugin::test_modelmanager_framework_headers()
const MyTestDataDir testDataDir(_("testdata"));
Project *project = helper.createProject(_("test_modelmanager_framework_headers"));
- ProjectInfo pi = mm->projectInfo(project);
- QCOMPARE(pi.project().data(), project);
+ ProjectInfo pi = ProjectInfo(project);
typedef ProjectPart::HeaderPath HeaderPath;
@@ -304,8 +269,7 @@ void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files()
Project *project = helper.createProject(
_("test_modelmanager_refresh_also_includes_of_project_files"));
- ProjectInfo pi = mm->projectInfo(project);
- QCOMPARE(pi.project().data(), project);
+ ProjectInfo pi = ProjectInfo(project);
typedef ProjectPart::HeaderPath HeaderPath;
@@ -333,7 +297,7 @@ void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files()
// Introduce a define that will enable another define once the document is reparsed.
part->projectDefines = QByteArray("#define TEST_DEFINE 1\n");
- pi.clearProjectParts();
+ pi = ProjectInfo(project);
pi.appendProjectPart(part);
pi.finish();
@@ -367,8 +331,7 @@ void CppToolsPlugin::test_modelmanager_refresh_several_times()
const QString testCpp(testDataDir.file(_("source.cpp")));
Project *project = helper.createProject(_("test_modelmanager_refresh_several_times"));
- ProjectInfo pi = mm->projectInfo(project);
- QCOMPARE(pi.project().data(), project);
+ ProjectInfo pi = ProjectInfo(project);
ProjectPart::Ptr part(new ProjectPart);
part->languageVersion = ProjectPart::CXX14;
@@ -386,7 +349,7 @@ void CppToolsPlugin::test_modelmanager_refresh_several_times()
QByteArray defines = "#define FIRST_DEFINE";
for (int i = 0; i < 2; ++i) {
- pi.clearProjectParts();
+ pi = ProjectInfo(project);
ProjectPart::Ptr part(new ProjectPart);
// Simulate project configuration change by having different defines each time.
defines += "\n#define ANOTHER_DEFINE";
@@ -434,8 +397,7 @@ void CppToolsPlugin::test_modelmanager_refresh_test_for_changes()
const QString testCpp(testDataDir.file(_("source.cpp")));
Project *project = helper.createProject(_("test_modelmanager_refresh_2"));
- ProjectInfo pi = mm->projectInfo(project);
- QCOMPARE(pi.project().data(), project);
+ ProjectInfo pi = ProjectInfo(project);
ProjectPart::Ptr part(new ProjectPart);
part->languageVersion = ProjectPart::CXX14;
@@ -472,8 +434,7 @@ void CppToolsPlugin::test_modelmanager_refresh_added_and_purge_removed()
const QString testCpp(testDataDir.file(_("source.cpp")));
Project *project = helper.createProject(_("test_modelmanager_refresh_3"));
- ProjectInfo pi = mm->projectInfo(project);
- QCOMPARE(pi.project().data(), project);
+ ProjectInfo pi = ProjectInfo(project);
ProjectPart::Ptr part(new ProjectPart);
part->languageVersion = ProjectPart::CXX14;
@@ -497,7 +458,7 @@ void CppToolsPlugin::test_modelmanager_refresh_added_and_purge_removed()
QVERIFY(snapshot.contains(testCpp));
// Now add testHeader2 and remove testHeader1
- pi.clearProjectParts();
+ pi = ProjectInfo(project);
ProjectPart::Ptr newPart(new ProjectPart);
newPart->languageVersion = ProjectPart::CXX14;
newPart->qtVersion = ProjectPart::Qt5;
@@ -524,22 +485,27 @@ void CppToolsPlugin::test_modelmanager_refresh_added_and_purge_removed()
void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change()
{
QFETCH(QString, fileToChange);
- QFETCH(QList<ProjectFile>, initialProjectFiles);
- QFETCH(QList<ProjectFile>, finalProjectFiles);
+ QFETCH(QStringList, initialProjectFiles);
+ QFETCH(QStringList, finalProjectFiles);
+
+ Tests::TemporaryCopiedDir temporaryDir(
+ MyTestDataDir(QLatin1String("testdata_refresh2")).path());
+ fileToChange = temporaryDir.absolutePath(fileToChange.toUtf8());
+ initialProjectFiles = toAbsolutePaths(initialProjectFiles, temporaryDir);
+ finalProjectFiles = toAbsolutePaths(finalProjectFiles, temporaryDir);
ModelManagerTestHelper helper;
CppModelManager *mm = CppModelManager::instance();
Project *project = helper.createProject(_("test_modelmanager_refresh_timeStampModified"));
- ProjectInfo pi = mm->projectInfo(project);
- QCOMPARE(pi.project().data(), project);
+ ProjectInfo pi = ProjectInfo(project);
ProjectPart::Ptr part(new ProjectPart);
part->languageVersion = ProjectPart::CXX14;
part->qtVersion = ProjectPart::Qt5;
- foreach (const ProjectFile &file, initialProjectFiles)
- part->files.append(file);
- pi.clearProjectParts();
+ foreach (const QString &file, initialProjectFiles)
+ part->files.append(ProjectFile(file, ProjectFile::CXXSource));
+ pi = ProjectInfo(project);
pi.appendProjectPart(part);
pi.finish();
@@ -551,9 +517,9 @@ void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_
QCOMPARE(refreshedFiles.size(), initialProjectFiles.size());
snapshot = mm->snapshot();
- foreach (const ProjectFile &file, initialProjectFiles) {
- QVERIFY(refreshedFiles.contains(file.path));
- QVERIFY(snapshot.contains(file.path));
+ foreach (const QString &file, initialProjectFiles) {
+ QVERIFY(refreshedFiles.contains(file));
+ QVERIFY(snapshot.contains(file));
}
document = snapshot.document(fileToChange);
@@ -571,9 +537,9 @@ void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_
// Add or remove source file. The configuration stays the same.
part->files.clear();
- foreach (const ProjectFile &file, finalProjectFiles)
- part->files.append(file);
- pi.clearProjectParts();
+ foreach (const QString &file, finalProjectFiles)
+ part->files.append(ProjectFile(file, ProjectFile::CXXSource));
+ pi = ProjectInfo(project);
pi.appendProjectPart(part);
pi.finish();
@@ -581,9 +547,9 @@ void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_
QCOMPARE(refreshedFiles.size(), finalProjectFiles.size());
snapshot = mm->snapshot();
- foreach (const ProjectFile &file, finalProjectFiles) {
- QVERIFY(refreshedFiles.contains(file.path));
- QVERIFY(snapshot.contains(file.path));
+ foreach (const QString &file, finalProjectFiles) {
+ QVERIFY(refreshedFiles.contains(file));
+ QVERIFY(snapshot.contains(file));
}
document = snapshot.document(fileToChange);
const QDateTime lastModifiedAfter = document->lastModified();
@@ -596,19 +562,15 @@ void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_
void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change_data()
{
QTest::addColumn<QString>("fileToChange");
- QTest::addColumn<QList<ProjectFile> >("initialProjectFiles");
- QTest::addColumn<QList<ProjectFile> >("finalProjectFiles");
+ QTest::addColumn<QStringList>("initialProjectFiles");
+ QTest::addColumn<QStringList>("finalProjectFiles");
- const MyTestDataDir testDataDir(_("testdata_refresh2"));
- const QString testCpp(testDataDir.file(_("source.cpp")));
- const QString testCpp2(testDataDir.file(_("source2.cpp")));
+ const QString testCpp = QLatin1String("source.cpp");
+ const QString testCpp2 = 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);
+ const QStringList projectFiles1 = QStringList() << testCpp;
+ const QStringList projectFiles2 = QStringList() << testCpp << testCpp2;
// Add a file
QTest::newRow("case: add project file") << fileToChange << projectFiles1 << projectFiles2;
@@ -665,16 +627,19 @@ void CppToolsPlugin::test_modelmanager_snapshot_after_two_projects()
/// is added for the ui_* file.
/// Check: (2) The CppSourceProcessor can successfully resolve the ui_* file
/// though it might not be actually generated in the build dir.
+///
+
void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
{
- ModelManagerTestHelper helper;
+ VerifyCleanCppModelManager verify;
- MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
- const QString projectFile = testDataDirectory.file(_("testdata_guiproject1.pro"));
+ TemporaryCopiedDir temporaryDir(MyTestDataDir(QLatin1String("testdata_guiproject1")).path());
+ QVERIFY(temporaryDir.isValid());
+ const QString projectFile = temporaryDir.absolutePath("testdata_guiproject1.pro");
- // Open project with *.ui file
- ExampleProjectConfigurator exampleProjectConfigurator(projectFile);
- Project *project = exampleProjectConfigurator.project();
+ ProjectOpenerAndCloser projects;
+ ProjectInfo projectInfo = projects.open(projectFile, /*configureAsExampleProject=*/ true);
+ QVERIFY(projectInfo.isValid());
// Check working copy.
// An AbstractEditorSupport object should have been added for the ui_* file.
@@ -684,10 +649,10 @@ void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
QCOMPARE(workingCopy.size(), 2); // mm->configurationFileName() and "ui_*.h"
QStringList fileNamesInWorkinCopy;
- QHashIterator<QString, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
+ QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
while (it.hasNext()) {
it.next();
- fileNamesInWorkinCopy << QFileInfo(it.key()).fileName();
+ fileNamesInWorkinCopy << Utils::FileName::fromString(it.key().toString()).fileName();
}
fileNamesInWorkinCopy.sort();
const QString expectedUiHeaderFileName = _("ui_mainwindow.h");
@@ -696,7 +661,7 @@ void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
// Check CppSourceProcessor / includes.
// The CppSourceProcessor is expected to find the ui_* file in the working copy.
- const QString fileIncludingTheUiFile = testDataDirectory.file(_("mainwindow.cpp"));
+ const QString fileIncludingTheUiFile = temporaryDir.absolutePath("mainwindow.cpp");
while (!mm->snapshot().document(fileIncludingTheUiFile))
QCoreApplication::processEvents();
@@ -705,12 +670,8 @@ void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
QVERIFY(document);
const QStringList includedFiles = document->includedFiles();
QCOMPARE(includedFiles.size(), 2);
- QCOMPARE(QFileInfo(includedFiles.at(0)).fileName(), _("mainwindow.h"));
- QCOMPARE(QFileInfo(includedFiles.at(1)).fileName(), _("ui_mainwindow.h"));
-
- // Close Project
- SessionManager::removeProject(project);
- helper.waitForFinishedGc();
+ QCOMPARE(Utils::FileName::fromString(includedFiles.at(0)).fileName(), _("mainwindow.h"));
+ QCOMPARE(Utils::FileName::fromString(includedFiles.at(1)).fileName(), _("ui_mainwindow.h"));
}
/// QTCREATORBUG-9828: Locator shows symbols of closed files
@@ -844,7 +805,7 @@ void CppToolsPlugin::test_modelmanager_defines_per_project()
part2->headerPaths = QList<HeaderPath>()
<< HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
- ProjectInfo pi = mm->projectInfo(project);
+ ProjectInfo pi = ProjectInfo(project);
pi.appendProjectPart(part1);
pi.appendProjectPart(part2);
pi.finish();
@@ -915,7 +876,7 @@ void CppToolsPlugin::test_modelmanager_precompiled_headers()
part2->headerPaths = QList<HeaderPath>()
<< HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
- ProjectInfo pi = mm->projectInfo(project);
+ ProjectInfo pi = ProjectInfo(project);
pi.appendProjectPart(part1);
pi.appendProjectPart(part2);
pi.finish();
@@ -997,7 +958,7 @@ void CppToolsPlugin::test_modelmanager_defines_per_editor()
part2->headerPaths = QList<HeaderPath>()
<< HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
- ProjectInfo pi = mm->projectInfo(project);
+ ProjectInfo pi = ProjectInfo(project);
pi.appendProjectPart(part1);
pi.appendProjectPart(part2);
pi.finish();
@@ -1027,7 +988,7 @@ void CppToolsPlugin::test_modelmanager_defines_per_editor()
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
QVERIFY(mm->isCppEditor(editor));
- const QString filePath = editor->document()->filePath();
+ const QString filePath = editor->document()->filePath().toString();
BaseEditorDocumentParser *parser = BaseEditorDocumentParser::get(filePath);
parser->setEditorDefines(editorDefines.toUtf8());
parser->update(mm->workingCopy());
@@ -1052,7 +1013,7 @@ void CppToolsPlugin::test_modelmanager_updateEditorsAfterProjectUpdate()
EditorCloser closerA(editorA);
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
- EditorDocumentHandle *editorDocumentA = mm->editorDocument(fileA);
+ CppEditorDocumentHandle *editorDocumentA = mm->cppEditorDocument(fileA);
QVERIFY(editorDocumentA);
ProjectPart::Ptr documentAProjectPart = editorDocumentA->processor()->parser()->projectPart();
QVERIFY(!documentAProjectPart->project);
@@ -1063,7 +1024,7 @@ void CppToolsPlugin::test_modelmanager_updateEditorsAfterProjectUpdate()
EditorCloser closerB(editorB);
QCOMPARE(Core::DocumentModel::openedDocuments().size(), 2);
- EditorDocumentHandle *editorDocumentB = mm->editorDocument(fileB);
+ CppEditorDocumentHandle *editorDocumentB = mm->cppEditorDocument(fileB);
QVERIFY(editorDocumentB);
ProjectPart::Ptr documentBProjectPart = editorDocumentB->processor()->parser()->projectPart();
QVERIFY(!documentBProjectPart->project);
@@ -1081,7 +1042,7 @@ void CppToolsPlugin::test_modelmanager_updateEditorsAfterProjectUpdate()
part->languageVersion = ProjectPart::CXX11;
part->qtVersion = ProjectPart::NoQt;
- ProjectInfo pi = mm->projectInfo(project);
+ ProjectInfo pi = ProjectInfo(project);
pi.appendProjectPart(part);
pi.finish();
updateProjectInfo(mm, &helper, pi);
@@ -1107,7 +1068,7 @@ void CppToolsPlugin::test_modelmanager_renameIncludes()
} GCHelper;
Q_UNUSED(GCHelper); // do not warn about being unused
- QTemporaryDir tmpDir;
+ TemporaryDir tmpDir;
QVERIFY(tmpDir.isValid());
const QDir workingDir(tmpDir.path());
diff --git a/src/plugins/cpptools/cpppointerdeclarationformatter.cpp b/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
index 7cf1ddf4808..74a2df3d7e7 100644
--- a/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
+++ b/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
@@ -353,7 +353,7 @@ void PointerDeclarationFormatter::processIfWhileForStatement(ExpressionAST *expr
//
// The declaration for 's' will be handled in visit(SimpleDeclarationAST *ast),
// so handle declaration for 't' here.
- Scope::iterator it = block->lastMember() - 1;
+ Scope::iterator it = block->memberEnd() - 1;
Symbol *symbol = *it;
if (symbol && symbol->asScope()) { // True if there is a "{ ... }" following.
--it;
diff --git a/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp b/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp
index 7209a534023..90aca43ce9a 100644
--- a/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp
+++ b/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp
@@ -67,7 +67,7 @@ QString stripCursor(const QString &source)
return copy;
}
-class PointerDeclarationFormatterTestCase : public CppTools::Tests::TestCase
+class PointerDeclarationFormatterTestCase : public Tests::TestCase
{
public:
PointerDeclarationFormatterTestCase(const QByteArray &source,
@@ -87,15 +87,18 @@ public:
}
// Write source to temprorary file
- const QString filePath = QDir::tempPath() + QLatin1String("/file.h");
- Document::Ptr document = Document::create(filePath);
- QVERIFY(writeFile(document->fileName(), sourceWithoutCursorMarker.toUtf8()));
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+ const QString filePath = temporaryDir.createFile("file.h",
+ sourceWithoutCursorMarker.toUtf8());
+ QVERIFY(!filePath.isEmpty());
// Preprocess source
Environment env;
Preprocessor preprocess(0, &env);
const QByteArray preprocessedSource = preprocess.run(filePath, sourceWithoutCursorMarker);
+ Document::Ptr document = Document::create(filePath);
document->setUtf8Source(preprocessedSource);
document->parse(parseMode);
document->check();
@@ -114,7 +117,7 @@ public:
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, cursorPosition);
editor->setTextCursor(cursor);
- QTextDocument *qtextDocument = editor->qdocument();
+ QTextDocument *qtextDocument = editor->textDocument()->document();
CppRefactoringFilePtr cppRefactoringFile
= CppRefactoringChanges::file(editor->editorWidget(), document);
diff --git a/src/plugins/cpptools/cppprojectfile.cpp b/src/plugins/cpptools/cppprojectfile.cpp
index 8ec2fce0d9c..8936b2e2405 100644
--- a/src/plugins/cpptools/cppprojectfile.cpp
+++ b/src/plugins/cpptools/cppprojectfile.cpp
@@ -102,6 +102,28 @@ bool ProjectFile::isSource(ProjectFile::Kind kind)
}
}
+QDebug operator<<(QDebug stream, const CppTools::ProjectFile &cxxFile)
+{
+ const char *kind;
+ switch (cxxFile.kind) {
+ case CppTools::ProjectFile::CHeader: kind = "CHeader"; break;
+ case CppTools::ProjectFile::CSource: kind = "CSource"; break;
+ case CppTools::ProjectFile::CXXHeader: kind = "CXXHeader"; break;
+ case CppTools::ProjectFile::CXXSource: kind = "CXXSource"; break;
+ case CppTools::ProjectFile::ObjCHeader: kind = "ObjCHeader"; break;
+ case CppTools::ProjectFile::ObjCSource: kind = "ObjCSource"; break;
+ case CppTools::ProjectFile::ObjCXXHeader: kind = "ObjCXXHeader"; break;
+ case CppTools::ProjectFile::ObjCXXSource: kind = "ObjCXXSource"; break;
+ case CppTools::ProjectFile::CudaSource: kind = "CudaSource"; break;
+ case CppTools::ProjectFile::OpenCLSource: kind = "OpenCLSource"; break;
+ default: kind = "INVALID"; break;
+ }
+ stream << cxxFile.path << QLatin1String(", ") << kind;
+ return stream;
+}
+
+namespace Internal {
+
ProjectFileAdder::ProjectFileAdder(QList<ProjectFile> &files)
: m_files(files)
{
@@ -135,24 +157,6 @@ void ProjectFileAdder::addMapping(const char *mimeName, ProjectFile::Kind kind)
m_mapping.append(Pair(mimeType, kind));
}
-QDebug operator<<(QDebug stream, const CppTools::ProjectFile &cxxFile)
-{
- const char *kind;
- switch (cxxFile.kind) {
- case CppTools::ProjectFile::CHeader: kind = "CHeader"; break;
- case CppTools::ProjectFile::CSource: kind = "CSource"; break;
- case CppTools::ProjectFile::CXXHeader: kind = "CXXHeader"; break;
- case CppTools::ProjectFile::CXXSource: kind = "CXXSource"; break;
- case CppTools::ProjectFile::ObjCHeader: kind = "ObjCHeader"; break;
- case CppTools::ProjectFile::ObjCSource: kind = "ObjCSource"; break;
- case CppTools::ProjectFile::ObjCXXHeader: kind = "ObjCXXHeader"; break;
- case CppTools::ProjectFile::ObjCXXSource: kind = "ObjCXXSource"; break;
- case CppTools::ProjectFile::CudaSource: kind = "CudaSource"; break;
- case CppTools::ProjectFile::OpenCLSource: kind = "OpenCLSource"; break;
- default: kind = "INVALID"; break;
- }
- stream << cxxFile.path << QLatin1String(", ") << kind;
- return stream;
-}
-
+} // namespace Internal
} // namespace CppTools
+
diff --git a/src/plugins/cpptools/cppprojectfile.h b/src/plugins/cpptools/cppprojectfile.h
index c5f7204f3ac..8202820dc9b 100644
--- a/src/plugins/cpptools/cppprojectfile.h
+++ b/src/plugins/cpptools/cppprojectfile.h
@@ -68,7 +68,11 @@ public:
Kind kind;
};
-class CPPTOOLS_EXPORT ProjectFileAdder
+QDebug operator<<(QDebug stream, const CppTools::ProjectFile &cxxFile);
+
+namespace Internal {
+
+class ProjectFileAdder
{
public:
ProjectFileAdder(QList<ProjectFile> &files);
@@ -86,8 +90,7 @@ private:
QFileInfo m_fileInfo;
};
-QDebug operator<<(QDebug stream, const CppTools::ProjectFile &cxxFile);
-
+} // namespace Internal
} // namespace CppTools
#endif // CPPTOOLS_CPPPROJECTFILE_H
diff --git a/src/plugins/cpptools/cppprojects.cpp b/src/plugins/cpptools/cppprojects.cpp
index a54c8c246d6..4bea18d691f 100644
--- a/src/plugins/cpptools/cppprojects.cpp
+++ b/src/plugins/cpptools/cppprojects.cpp
@@ -43,6 +43,7 @@
#include <QTextStream>
using namespace CppTools;
+using namespace CppTools::Internal;
using namespace ProjectExplorer;
ProjectPart::ProjectPart()
@@ -50,7 +51,7 @@ ProjectPart::ProjectPart()
, languageVersion(CXX14)
, languageExtensions(NoExtensions)
, qtVersion(UnknownQt)
- , warningFlags(ProjectExplorer::ToolChain::WarningsDefault)
+ , warningFlags(ToolChain::WarningsDefault)
, selectedForBuilding(true)
{
}
@@ -62,7 +63,7 @@ ProjectPart::ProjectPart()
\param cxxflags C++ or Objective-C++ flags.
\param cflags C or ObjectiveC flags if possible, \a cxxflags otherwise.
*/
-void ProjectPart::evaluateToolchain(const ProjectExplorer::ToolChain *tc,
+void ProjectPart::evaluateToolchain(const ToolChain *tc,
const QStringList &commandLineFlags,
const Utils::FileName &sysRoot)
{
@@ -136,7 +137,7 @@ QByteArray ProjectPart::readProjectConfigFile(const ProjectPart::Ptr &part)
ProjectInfo::ProjectInfo()
{}
-ProjectInfo::ProjectInfo(QPointer<ProjectExplorer::Project> project)
+ProjectInfo::ProjectInfo(QPointer<Project> project)
: m_project(project)
{}
@@ -175,7 +176,7 @@ bool ProjectInfo::isValid() const
return !m_project.isNull();
}
-QPointer<ProjectExplorer::Project> ProjectInfo::project() const
+QPointer<Project> ProjectInfo::project() const
{
return m_project;
}
@@ -220,15 +221,6 @@ void ProjectInfo::finish()
}
}
-void ProjectInfo::clearProjectParts()
-{
- m_projectParts.clear();
- m_headerPaths.clear();
- m_sourceFiles.clear();
- m_defines.clear();
- m_compilerCallData.clear();
-}
-
const ProjectPart::HeaderPaths ProjectInfo::headerPaths() const
{
return m_headerPaths;
@@ -456,11 +448,11 @@ void ProjectPartBuilder::createProjectPart(const QStringList &theSources,
ProjectPart::LanguageVersion languageVersion,
ProjectPart::LanguageExtensions languageExtensions)
{
- CppTools::ProjectPart::Ptr part(m_templatePart->copy());
+ ProjectPart::Ptr part(m_templatePart->copy());
part->displayName = partName;
QTC_ASSERT(part->project, return);
- if (ProjectExplorer::Target *activeTarget = part->project->activeTarget()) {
+ if (Target *activeTarget = part->project->activeTarget()) {
if (Kit *kit = activeTarget->kit()) {
if (ToolChain *toolChain = ToolChainKitInformation::toolChain(kit)) {
const QStringList flags = languageVersion >= ProjectPart::CXX98 ? m_cxxFlags
@@ -472,7 +464,7 @@ void ProjectPartBuilder::createProjectPart(const QStringList &theSources,
part->languageExtensions |= languageExtensions;
- CppTools::ProjectFileAdder adder(part->files);
+ ProjectFileAdder adder(part->files);
foreach (const QString &file, theSources)
adder.maybeAdd(file);
@@ -482,9 +474,11 @@ void ProjectPartBuilder::createProjectPart(const QStringList &theSources,
QStringList CompilerOptionsBuilder::createHeaderPathOptions(
const ProjectPart::HeaderPaths &headerPaths,
- IsBlackListed isBlackListed)
+ IsBlackListed isBlackListed, const QString &toolchainType)
{
typedef ProjectPart::HeaderPath HeaderPath;
+ const QString defaultPrefix
+ = QLatin1String(toolchainType == QLatin1String("msvc") ? "/I" : "-I");
QStringList result;
@@ -503,7 +497,7 @@ QStringList CompilerOptionsBuilder::createHeaderPathOptions(
default: // This shouldn't happen, but let's be nice..:
// intentional fall-through:
case HeaderPath::IncludePath:
- prefix = QLatin1String("-I");
+ prefix = defaultPrefix;
break;
}
@@ -514,11 +508,20 @@ QStringList CompilerOptionsBuilder::createHeaderPathOptions(
}
QStringList CompilerOptionsBuilder::createDefineOptions(const QByteArray &defines,
- bool toolchainDefines)
+ bool toolchainDefines,
+ const QString &toolchainType)
{
+ QByteArray extendedDefines = defines;
QStringList result;
- foreach (QByteArray def, defines.split('\n')) {
+ // In gcc headers, lots of built-ins are referenced that clang does not understand.
+ // Therefore, prevent the inclusion of the header that references them. Of course, this
+ // will break if code actually requires stuff from there, but that should be the less common
+ // case.
+ if (toolchainType == QLatin1String("mingw") || toolchainType == QLatin1String("gcc"))
+ extendedDefines += "#define _X86INTRIN_H_INCLUDED\n";
+
+ foreach (QByteArray def, extendedDefines.split('\n')) {
if (def.isEmpty())
continue;
@@ -538,16 +541,22 @@ QStringList CompilerOptionsBuilder::createDefineOptions(const QByteArray &define
continue;
}
+ // gcc 4.9 has:
+ // #define __has_include(STR) __has_include__(STR)
+ // #define __has_include_next(STR) __has_include_next__(STR)
+ // The right-hand sides are gcc built-ins that clang does not understand, and they'd
+ // override clang's own (non-macro, it seems) definitions of the symbols on the left-hand
+ // side.
+ if (toolchainType == QLatin1String("gcc") && def.contains("has_include"))
+ continue;
+
QByteArray str = def.mid(8);
int spaceIdx = str.indexOf(' ');
- QString arg;
- if (spaceIdx != -1) {
- arg = QLatin1String("-D" + str.left(spaceIdx) + "=" + str.mid(spaceIdx + 1));
- } else {
- arg = QLatin1String("-D" + str);
- }
- arg = arg.replace(QLatin1String("\\\""), QLatin1String("\""));
- arg = arg.replace(QLatin1String("\""), QLatin1String(""));
+ const QString option = QLatin1String(toolchainType == QLatin1String("msvc") ? "/D" : "-D");
+ const bool hasValue = spaceIdx != -1;
+ QString arg = option + QLatin1String(str.left(hasValue ? spaceIdx : str.size()) + '=');
+ if (hasValue)
+ arg += QLatin1String(str.mid(spaceIdx + 1));
if (!result.contains(arg))
result.append(arg);
}
@@ -555,7 +564,7 @@ QStringList CompilerOptionsBuilder::createDefineOptions(const QByteArray &define
return result;
}
-QStringList CompilerOptionsBuilder::createLanguageOption(ProjectFile::Kind fileKind, bool objcExt)
+static QStringList createLanguageOptionGcc(ProjectFile::Kind fileKind, bool objcExt)
{
QStringList opts;
opts += QLatin1String("-x");
@@ -608,12 +617,40 @@ QStringList CompilerOptionsBuilder::createLanguageOption(ProjectFile::Kind fileK
return opts;
}
+static QStringList createLanguageOptionMsvc(ProjectFile::Kind fileKind)
+{
+ QStringList opts;
+ switch (fileKind) {
+ case ProjectFile::CHeader:
+ case ProjectFile::CSource:
+ opts << QLatin1String("/TC");
+ break;
+ case ProjectFile::CXXHeader:
+ case ProjectFile::CXXSource:
+ opts << QLatin1String("/TP");
+ break;
+ default:
+ break;
+ }
+ return opts;
+}
+
+QStringList CompilerOptionsBuilder::createLanguageOption(ProjectFile::Kind fileKind, bool objcExt,
+ const QString &toolchainType)
+{
+ return toolchainType == QLatin1String("msvc") ? createLanguageOptionMsvc(fileKind)
+ : createLanguageOptionGcc(fileKind, objcExt);
+}
+
QStringList CompilerOptionsBuilder::createOptionsForLanguage(
ProjectPart::LanguageVersion languageVersion,
ProjectPart::LanguageExtensions languageExtensions,
- bool checkForBorlandExtensions)
+ bool checkForBorlandExtensions,
+ const QString &toolchainType)
{
QStringList opts;
+ if (toolchainType == QLatin1String("msvc"))
+ return opts;
bool gnuExtensions = languageExtensions & ProjectPart::GnuExtensions;
switch (languageVersion) {
case ProjectPart::C89:
diff --git a/src/plugins/cpptools/cppprojects.h b/src/plugins/cpptools/cppprojects.h
index aad0656271e..ebdfd989ce1 100644
--- a/src/plugins/cpptools/cppprojects.h
+++ b/src/plugins/cpptools/cppprojects.h
@@ -154,7 +154,6 @@ public:
void appendProjectPart(const ProjectPart::Ptr &part);
void finish();
- void clearProjectParts();
const ProjectPart::HeaderPaths headerPaths() const;
const QSet<QString> sourceFiles() const;
@@ -209,15 +208,19 @@ class CPPTOOLS_EXPORT CompilerOptionsBuilder
public:
typedef std::function<bool (const QString &)> IsBlackListed;
static QStringList createHeaderPathOptions(const ProjectPart::HeaderPaths &headerPaths,
- IsBlackListed isBlackListed = IsBlackListed());
+ IsBlackListed isBlackListed = IsBlackListed(),
+ const QString &toolchainType = QLatin1String("clang"));
static QStringList createDefineOptions(const QByteArray &defines,
- bool toolchainDefines = false);
+ bool toolchainDefines = false,
+ const QString &toolchainType = QLatin1String("clang"));
- static QStringList createLanguageOption(ProjectFile::Kind fileKind, bool objcExt);
+ static QStringList createLanguageOption(ProjectFile::Kind fileKind, bool objcExt,
+ const QString &toolchainType = QLatin1String("clang"));
static QStringList createOptionsForLanguage(ProjectPart::LanguageVersion languageVersion,
ProjectPart::LanguageExtensions languageExtensions,
- bool checkForBorlandExtensions = true);
+ bool checkForBorlandExtensions = true,
+ const QString &toolchainType = QLatin1String("clang"));
};
} // namespace CppTools
diff --git a/src/plugins/cpptools/cppqtstyleindenter.cpp b/src/plugins/cpptools/cppqtstyleindenter.cpp
index 112505a1cda..70910554437 100644
--- a/src/plugins/cpptools/cppqtstyleindenter.cpp
+++ b/src/plugins/cpptools/cppqtstyleindenter.cpp
@@ -61,6 +61,7 @@ bool CppQtStyleIndenter::isElectricCharacter(const QChar &ch) const
case '#':
case '<':
case '>':
+ case ';':
return true;
}
return false;
@@ -69,6 +70,8 @@ bool CppQtStyleIndenter::isElectricCharacter(const QChar &ch) const
static bool isElectricInLine(const QChar ch, const QString &text)
{
switch (ch.toLatin1()) {
+ case ';':
+ return text.contains(QLatin1String("break"));
case ':':
// switch cases and access declarations should be reindented
if (text.contains(QLatin1String("case"))
@@ -104,7 +107,7 @@ void CppQtStyleIndenter::indentBlock(QTextDocument *doc,
{
Q_UNUSED(doc)
- CppTools::QtStyleCodeFormatter codeFormatter(tabSettings, codeStyleSettings());
+ QtStyleCodeFormatter codeFormatter(tabSettings, codeStyleSettings());
codeFormatter.updateStateUntil(block);
int indent;
@@ -137,7 +140,7 @@ void CppQtStyleIndenter::indent(QTextDocument *doc,
QTextBlock block = doc->findBlock(cursor.selectionStart());
const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next();
- CppTools::QtStyleCodeFormatter codeFormatter(tabSettings, codeStyleSettings());
+ QtStyleCodeFormatter codeFormatter(tabSettings, codeStyleSettings());
codeFormatter.updateStateUntil(block);
QTextCursor tc = cursor;
@@ -158,15 +161,15 @@ void CppQtStyleIndenter::indent(QTextDocument *doc,
void CppQtStyleIndenter::setCodeStylePreferences(TextEditor::ICodeStylePreferences *preferences)
{
- CppTools::CppCodeStylePreferences *cppCodeStylePreferences
- = qobject_cast<CppTools::CppCodeStylePreferences *>(preferences);
+ CppCodeStylePreferences *cppCodeStylePreferences
+ = qobject_cast<CppCodeStylePreferences *>(preferences);
if (cppCodeStylePreferences)
m_cppCodeStylePreferences = cppCodeStylePreferences;
}
void CppQtStyleIndenter::invalidateCache(QTextDocument *doc)
{
- CppTools::QtStyleCodeFormatter formatter;
+ QtStyleCodeFormatter formatter;
formatter.invalidateCache(doc);
}
diff --git a/src/plugins/cpptools/cpprefactoringchanges.cpp b/src/plugins/cpptools/cpprefactoringchanges.cpp
index d6edfb59923..5498ead451f 100644
--- a/src/plugins/cpptools/cpprefactoringchanges.cpp
+++ b/src/plugins/cpptools/cpprefactoringchanges.cpp
@@ -40,9 +40,10 @@
#include <utils/qtcassert.h>
using namespace CPlusPlus;
-using namespace CppTools;
-class CppTools::CppRefactoringChangesData : public TextEditor::RefactoringChangesData
+namespace CppTools {
+
+class CppRefactoringChangesData : public TextEditor::RefactoringChangesData
{
public:
CppRefactoringChangesData(const Snapshot &snapshot)
@@ -262,3 +263,5 @@ void CppRefactoringFile::fileChanged()
m_cppDocument.clear();
RefactoringFile::fileChanged();
}
+
+} // namespace CppTools
diff --git a/src/plugins/cpptools/cppsemanticinfoupdater.cpp b/src/plugins/cpptools/cppsemanticinfoupdater.cpp
index e6438a02d51..d9deea19267 100644
--- a/src/plugins/cpptools/cppsemanticinfoupdater.cpp
+++ b/src/plugins/cpptools/cppsemanticinfoupdater.cpp
@@ -53,11 +53,11 @@ namespace CppTools {
class SemanticInfoUpdaterPrivate
{
public:
- class FuturizedTopLevelDeclarationProcessor: public CPlusPlus::TopLevelDeclarationProcessor
+ class FuturizedTopLevelDeclarationProcessor: public TopLevelDeclarationProcessor
{
public:
FuturizedTopLevelDeclarationProcessor(QFutureInterface<void> &future): m_future(future) {}
- bool processDeclaration(CPlusPlus::DeclarationAST *) { return !isCanceled(); }
+ bool processDeclaration(DeclarationAST *) { return !isCanceled(); }
bool isCanceled() { return m_future.isCanceled(); }
private:
QFutureInterface<void> m_future;
@@ -125,7 +125,6 @@ SemanticInfo SemanticInfoUpdaterPrivate::update(const SemanticInfo::Source &sour
Document::Ptr doc = newSemanticInfo.snapshot.preprocessedDocument(source.code, source.fileName);
if (processor)
doc->control()->setTopLevelDeclarationProcessor(processor);
- doc->setRetryHarderToParseDeclarations(true);
doc->check();
if (processor && processor->isCanceled())
newSemanticInfo.complete = false;
diff --git a/src/plugins/cpptools/cppsourceprocessor.cpp b/src/plugins/cpptools/cppsourceprocessor.cpp
index 97fa1cc1da9..8a3e4549b6a 100644
--- a/src/plugins/cpptools/cppsourceprocessor.cpp
+++ b/src/plugins/cpptools/cppsourceprocessor.cpp
@@ -272,19 +272,33 @@ QString CppSourceProcessor::resolveFile_helper(const QString &fileName, IncludeT
if (QFileInfo(fileName).isAbsolute())
return checkFile(fileName) ? fileName : QString();
- if (type == IncludeLocal && m_currentDoc) {
- 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.
+ auto headerPathsIt = m_headerPaths.begin();
+ auto headerPathsEnd = m_headerPaths.end();
+ if (m_currentDoc) {
+ if (type == IncludeLocal) {
+ 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.
+
+ } else if (type == IncludeNext) {
+ const QFileInfo currentFileInfo(m_currentDoc->fileName());
+ const QString currentDirPath = cleanPath(currentFileInfo.dir().path());
+ for (; headerPathsIt != headerPathsEnd; ++headerPathsIt) {
+ if (headerPathsIt->path == currentDirPath) {
+ ++headerPathsIt;
+ break;
+ }
+ }
+ }
}
- foreach (const ProjectPart::HeaderPath &headerPath, m_headerPaths) {
- if (headerPath.isFrameworkPath())
+ for (; headerPathsIt != headerPathsEnd; ++headerPathsIt) {
+ if (headerPathsIt->isFrameworkPath())
continue;
- const QString path = headerPath.path + fileName;
+ const QString path = headerPathsIt->path + fileName;
if (m_workingCopy.contains(path) || checkFile(path))
return path;
}
diff --git a/src/plugins/cpptools/cppsourceprocessor_test.cpp b/src/plugins/cpptools/cppsourceprocessor_test.cpp
index 1016ceffc3b..378d1ae4134 100644
--- a/src/plugins/cpptools/cppsourceprocessor_test.cpp
+++ b/src/plugins/cpptools/cppsourceprocessor_test.cpp
@@ -37,6 +37,7 @@
#include "cpptoolstestcase.h"
#include "editordocumenthandle.h"
+#include <coreplugin/testdatadir.h>
#include <texteditor/texteditor.h>
#include <cplusplus/CppDocument.h>
@@ -62,22 +63,16 @@ public:
cleanUp();
}
- Document::Ptr run(const QByteArray &source)
+ Document::Ptr run(const QString &filePath)
{
- const QString fileName = TestIncludePaths::testFilePath();
-
- FileWriterAndRemover scopedFile(fileName, source);
- if (!scopedFile.writtenSuccessfully())
- return Document::Ptr();
-
QScopedPointer<CppSourceProcessor> sourceProcessor(
CppModelManager::createSourceProcessor());
const ProjectPart::HeaderPath hp(TestIncludePaths::directoryOfTestFile(),
ProjectPart::HeaderPath::IncludePath);
sourceProcessor->setHeaderPaths(ProjectPart::HeaderPaths() << hp);
- sourceProcessor->run(fileName);
+ sourceProcessor->run(filePath);
- Document::Ptr document = m_cmm->document(fileName);
+ Document::Ptr document = m_cmm->document(filePath);
return document;
}
@@ -100,14 +95,11 @@ private:
/// Check: Resolved and unresolved includes are properly tracked.
void CppToolsPlugin::test_cppsourceprocessor_includes_resolvedUnresolved()
{
- QByteArray source =
- "#include \"header.h\"\n"
- "#include \"notresolvable.h\"\n"
- "\n"
- ;
+ const QString testFilePath
+ = TestIncludePaths::testFilePath(QLatin1String("test_main_resolvedUnresolved.cpp"));
SourcePreprocessor processor;
- Document::Ptr document = processor.run(source);
+ Document::Ptr document = processor.run(testFilePath);
QVERIFY(document);
const QList<Document::Include> resolvedIncludes = document->resolvedIncludes();
@@ -142,7 +134,7 @@ void CppToolsPlugin::test_cppsourceprocessor_includes_cyclic()
testCase.closeEditorAtEndOfTestCase(editor);
// Check editor snapshot
- const QString filePath = editor->document()->filePath();
+ const QString filePath = editor->document()->filePath().toString();
auto *processor = BaseEditorDocumentProcessor::get(filePath);
QVERIFY(processor);
Snapshot snapshot = processor->snapshot();
@@ -166,15 +158,11 @@ void CppToolsPlugin::test_cppsourceprocessor_includes_cyclic()
/// Check: All include errors are reported as diagnostic messages.
void CppToolsPlugin::test_cppsourceprocessor_includes_allDiagnostics()
{
- QByteArray source =
- "#include <NotResolvable1>\n"
- "#include <NotResolvable2>\n"
- "#include \"/some/nonexisting/file123.h\"\n"
- "\n"
- ;
+ const QString testFilePath
+ = TestIncludePaths::testFilePath(QLatin1String("test_main_allDiagnostics.cpp"));
SourcePreprocessor processor;
- Document::Ptr document = processor.run(source);
+ Document::Ptr document = processor.run(testFilePath);
QVERIFY(document);
QCOMPARE(document->resolvedIncludes().size(), 0);
@@ -184,15 +172,11 @@ void CppToolsPlugin::test_cppsourceprocessor_includes_allDiagnostics()
void CppToolsPlugin::test_cppsourceprocessor_macroUses()
{
- QByteArray source =
- "#define SOMEDEFINE 1\n"
- "#if SOMEDEFINE == 1\n"
- " int someNumber;\n"
- "#endif\n"
- ;
+ const QString testFilePath
+ = TestIncludePaths::testFilePath(QLatin1String("test_main_macroUses.cpp"));
SourcePreprocessor processor;
- Document::Ptr document = processor.run(source);
+ Document::Ptr document = processor.run(testFilePath);
QVERIFY(document);
const QList<Document::MacroUse> macroUses = document->macroUses();
QCOMPARE(macroUses.size(), 1);
@@ -203,3 +187,38 @@ void CppToolsPlugin::test_cppsourceprocessor_macroUses()
QCOMPARE(macroUse.utf16charsEnd(), 35U);
QCOMPARE(macroUse.beginLine(), 2U);
}
+
+static bool isMacroDefinedInDocument(const QByteArray &macroName, const Document::Ptr &document)
+{
+ foreach (const Macro &macro, document->definedMacros()) {
+ if (macro.name() == macroName)
+ return true;
+ }
+
+ return false;
+}
+
+static inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
+
+void CppToolsPlugin::test_cppsourceprocessor_includeNext()
+{
+ const Core::Tests::TestDataDir data(
+ _(SRCDIR "/../../../tests/auto/cplusplus/preprocessor/data/include_next-data/"));
+ const QString mainFilePath = data.file(QLatin1String("main.cpp"));
+ const QString customHeaderPath = data.directory(QLatin1String("customIncludePath"));
+ const QString systemHeaderPath = data.directory(QLatin1String("systemIncludePath"));
+
+ CppSourceProcessor::DocumentCallback documentCallback = [](const Document::Ptr &){};
+ CppSourceProcessor sourceProcessor(Snapshot(), documentCallback);
+ ProjectPart::HeaderPaths headerPaths = ProjectPart::HeaderPaths()
+ << ProjectPart::HeaderPath(customHeaderPath, ProjectPart::HeaderPath::IncludePath)
+ << ProjectPart::HeaderPath(systemHeaderPath, ProjectPart::HeaderPath::IncludePath);
+ sourceProcessor.setHeaderPaths(headerPaths);
+
+ sourceProcessor.run(mainFilePath);
+ const Snapshot snapshot = sourceProcessor.snapshot();
+ QVERIFY(!snapshot.isEmpty());
+ const Document::Ptr mainDocument = snapshot.document(mainFilePath);
+ QVERIFY(mainDocument);
+ QVERIFY(isMacroDefinedInDocument("OK_FEATURE_X_ENABLED", mainDocument));
+}
diff --git a/src/plugins/cpptools/cpptools.pro b/src/plugins/cpptools/cpptools.pro
index 4408a94714b..a97e2499073 100644
--- a/src/plugins/cpptools/cpptools.pro
+++ b/src/plugins/cpptools/cpptools.pro
@@ -22,12 +22,15 @@ HEADERS += \
cppcodestylesettings.h \
cppcodestylesettingspage.h \
cppcompletionassist.h \
+ cppcompletionassistprocessor.h \
cppcompletionassistprovider.h \
cppcurrentdocumentfilter.h \
+ cppeditoroutline.h \
cppdoxygen.h \
cppfilesettingspage.h \
cppfindreferences.h \
cppfunctionsfilter.h \
+ cppincludesfilter.h \
cppindexingsupport.h \
cpplocalsymbols.h \
cpplocatordata.h \
@@ -83,12 +86,15 @@ SOURCES += \
cppcodestylesettings.cpp \
cppcodestylesettingspage.cpp \
cppcompletionassist.cpp \
+ cppcompletionassistprocessor.cpp \
cppcompletionassistprovider.cpp \
cppcurrentdocumentfilter.cpp \
+ cppeditoroutline.cpp \
cppdoxygen.cpp \
cppfilesettingspage.cpp \
cppfindreferences.cpp \
cppfunctionsfilter.cpp \
+ cppincludesfilter.cpp \
cppindexingsupport.cpp \
cpplocalsymbols.cpp \
cpplocatordata.cpp \
diff --git a/src/plugins/cpptools/cpptools.qbs b/src/plugins/cpptools/cpptools.qbs
index 8977c85f609..9d8e6c7d85f 100644
--- a/src/plugins/cpptools/cpptools.qbs
+++ b/src/plugins/cpptools/cpptools.qbs
@@ -40,12 +40,15 @@ QtcPlugin {
"cppcodestylesettings.cpp", "cppcodestylesettings.h",
"cppcodestylesettingspage.cpp", "cppcodestylesettingspage.h", "cppcodestylesettingspage.ui",
"cppcompletionassist.cpp", "cppcompletionassist.h",
+ "cppcompletionassistprocessor.cpp", "cppcompletionassistprocessor.h",
"cppcompletionassistprovider.cpp", "cppcompletionassistprovider.h",
"cppcurrentdocumentfilter.cpp", "cppcurrentdocumentfilter.h",
"cppdoxygen.cpp", "cppdoxygen.h",
+ "cppeditoroutline.cpp", "cppeditoroutline.h",
"cppfilesettingspage.cpp", "cppfilesettingspage.h", "cppfilesettingspage.ui",
"cppfindreferences.cpp", "cppfindreferences.h",
"cppfunctionsfilter.cpp", "cppfunctionsfilter.h",
+ "cppincludesfilter.cpp", "cppincludesfilter.h",
"cppindexingsupport.cpp", "cppindexingsupport.h",
"cpplocalsymbols.cpp", "cpplocalsymbols.h",
"cpplocatordata.cpp", "cpplocatordata.h",
diff --git a/src/plugins/cpptools/cpptoolsconstants.h b/src/plugins/cpptools/cpptoolsconstants.h
index 86dad773667..2b2bf859a9e 100644
--- a/src/plugins/cpptools/cpptoolsconstants.h
+++ b/src/plugins/cpptools/cpptoolsconstants.h
@@ -52,6 +52,7 @@ const char CPP_HEADER_MIMETYPE[] = "text/x-c++hdr";
const char CPPTOOLS_SETTINGSGROUP[] = "CppTools";
const char LOWERCASE_CPPFILES_KEY[] = "LowerCaseFiles";
enum { lowerCaseFilesDefault = 1 };
+const char CPPTOOLS_SORT_EDITOR_DOCUMENT_OUTLINE[] = "SortedMethodOverview";
const char CPPTOOLS_MODEL_MANAGER_SUPPORTERS_KEY[] = "ModelManagerSupporters";
const char CPPTOOLS_MODEL_MANAGER_PCH_USAGE[] = "PCHUsage";
diff --git a/src/plugins/cpptools/cpptoolsplugin.cpp b/src/plugins/cpptools/cpptoolsplugin.cpp
index 7631da86bc8..36c9552260d 100644
--- a/src/plugins/cpptools/cpptoolsplugin.cpp
+++ b/src/plugins/cpptools/cpptoolsplugin.cpp
@@ -44,6 +44,7 @@
#include "cpptoolsreuse.h"
#include "cppprojectfile.h"
#include "cpplocatordata.h"
+#include "cppincludesfilter.h"
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -53,6 +54,7 @@
#include <coreplugin/jsexpander.h>
#include <coreplugin/vcsmanager.h>
#include <cppeditor/cppeditorconstants.h>
+#include <projectexplorer/projecttree.h>
#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
@@ -150,15 +152,16 @@ bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
JsExpander::registerQObjectForJs(QLatin1String("Cpp"), new CppToolsJsExtension);
CppLocatorData *locatorData = new CppLocatorData;
- connect(modelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)),
- locatorData, SLOT(onDocumentUpdated(CPlusPlus::Document::Ptr)));
+ connect(modelManager, &CppModelManager::documentUpdated,
+ locatorData, &CppLocatorData::onDocumentUpdated);
- connect(modelManager, SIGNAL(aboutToRemoveFiles(QStringList)),
- locatorData, SLOT(onAboutToRemoveFiles(QStringList)));
+ connect(modelManager, &CppModelManager::aboutToRemoveFiles,
+ locatorData, &CppLocatorData::onAboutToRemoveFiles);
addAutoReleasedObject(locatorData);
addAutoReleasedObject(new CppLocatorFilter(locatorData));
addAutoReleasedObject(new CppClassesFilter(locatorData));
+ addAutoReleasedObject(new CppIncludesFilter);
addAutoReleasedObject(new CppFunctionsFilter(locatorData));
addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager, m_stringTable));
addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
@@ -181,7 +184,8 @@ bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
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()));
+ connect(switchAction, &QAction::triggered,
+ this, &CppToolsPlugin::switchHeaderSource);
QAction *openInNextSplitAction = new QAction(tr("Open Corresponding Header/Source in Next Split"), this);
command = ActionManager::registerAction(openInNextSplitAction, Constants::OPEN_HEADER_SOURCE_IN_NEXT_SPLIT, context, true);
@@ -189,7 +193,8 @@ bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
? tr("Meta+E, F4")
: tr("Ctrl+E, F4")));
mcpptools->addAction(command);
- connect(openInNextSplitAction, SIGNAL(triggered()), this, SLOT(switchHeaderSourceInNextSplit()));
+ connect(openInNextSplitAction, &QAction::triggered,
+ this, &CppToolsPlugin::switchHeaderSourceInNextSplit);
Utils::MacroExpander *expander = Utils::globalMacroExpander();
expander->registerVariable("Cpp:LicenseTemplate",
@@ -235,7 +240,7 @@ void CppToolsPlugin::switchHeaderSource()
void CppToolsPlugin::switchHeaderSourceInNextSplit()
{
QString otherFile = correspondingHeaderOrSource(
- EditorManager::currentDocument()->filePath());
+ EditorManager::currentDocument()->filePath().toString());
if (!otherFile.isEmpty())
EditorManager::openEditor(otherFile, Id(), EditorManager::OpenInOtherSplit);
}
@@ -431,7 +436,7 @@ QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader)
}
// Find files in the current project
- ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectTree::currentProject();
if (currentProject) {
const QString path = correspondingHeaderOrSourceInProject(fi, candidateFileNames,
currentProject);
diff --git a/src/plugins/cpptools/cpptoolsplugin.h b/src/plugins/cpptools/cpptoolsplugin.h
index c8296fed18b..128d9220850 100644
--- a/src/plugins/cpptools/cpptoolsplugin.h
+++ b/src/plugins/cpptools/cpptoolsplugin.h
@@ -133,6 +133,7 @@ private slots:
void test_cppsourceprocessor_includes_cyclic();
void test_cppsourceprocessor_includes_allDiagnostics();
void test_cppsourceprocessor_macroUses();
+ void test_cppsourceprocessor_includeNext();
void test_functionutils_virtualFunctions();
void test_functionutils_virtualFunctions_data();
diff --git a/src/plugins/cpptools/cpptoolsreuse.cpp b/src/plugins/cpptools/cpptoolsreuse.cpp
index 8797241c81a..d0dd2838e3d 100644
--- a/src/plugins/cpptools/cpptoolsreuse.cpp
+++ b/src/plugins/cpptools/cpptoolsreuse.cpp
@@ -92,7 +92,7 @@ static bool isOwnershipRAIIName(const QString &name)
return knownNames.contains(name);
}
-bool isOwnershipRAIIType(CPlusPlus::Symbol *symbol, const LookupContext &context)
+bool isOwnershipRAIIType(Symbol *symbol, const LookupContext &context)
{
if (!symbol)
return false;
@@ -196,7 +196,7 @@ void switchHeaderSource()
{
const Core::IDocument *currentDocument = Core::EditorManager::currentDocument();
QTC_ASSERT(currentDocument, return);
- const QString otherFile = correspondingHeaderOrSource(currentDocument->filePath());
+ const QString otherFile = correspondingHeaderOrSource(currentDocument->filePath().toString());
if (!otherFile.isEmpty())
Core::EditorManager::openEditor(otherFile);
}
@@ -227,4 +227,26 @@ const Macro *findCanonicalMacro(const QTextCursor &cursor, Document::Ptr documen
return 0;
}
+TextEditor::TextEditorWidget::Link linkToSymbol(Symbol *symbol)
+{
+ typedef TextEditor::TextEditorWidget::Link Link;
+
+ if (!symbol)
+ return Link();
+
+ const QString filename = QString::fromUtf8(symbol->fileName(),
+ symbol->fileNameLength());
+
+ unsigned line = symbol->line();
+ unsigned column = symbol->column();
+
+ if (column)
+ --column;
+
+ if (symbol->isGenerated())
+ column = 0;
+
+ return Link(filename, line, column);
+}
+
} // CppTools
diff --git a/src/plugins/cpptools/cpptoolsreuse.h b/src/plugins/cpptools/cpptoolsreuse.h
index 67fa0104c83..8881c6198a1 100644
--- a/src/plugins/cpptools/cpptoolsreuse.h
+++ b/src/plugins/cpptools/cpptoolsreuse.h
@@ -33,6 +33,8 @@
#include "cpptools_global.h"
+#include <texteditor/texteditor.h>
+
#include <cplusplus/CppDocument.h>
QT_BEGIN_NAMESPACE
@@ -59,6 +61,8 @@ bool CPPTOOLS_EXPORT isValidFirstIdentifierChar(const QChar &ch);
bool CPPTOOLS_EXPORT isValidIdentifierChar(const QChar &ch);
bool CPPTOOLS_EXPORT isValidIdentifier(const QString &s);
+TextEditor::TextEditorWidget::Link CPPTOOLS_EXPORT linkToSymbol(CPlusPlus::Symbol *symbol);
+
QString CPPTOOLS_EXPORT identifierUnderCursor(QTextCursor *cursor);
bool CPPTOOLS_EXPORT isOwnershipRAIIType(CPlusPlus::Symbol *symbol,
diff --git a/src/plugins/cpptools/cpptoolssettings.cpp b/src/plugins/cpptools/cpptoolssettings.cpp
index cc0b0179a22..f73001edbd2 100644
--- a/src/plugins/cpptools/cpptoolssettings.cpp
+++ b/src/plugins/cpptools/cpptoolssettings.cpp
@@ -49,6 +49,7 @@
static const char idKey[] = "CppGlobal";
+using namespace Core;
using namespace CppTools;
using namespace CppTools::Internal;
using namespace TextEditor;
@@ -64,6 +65,7 @@ public:
, m_completionSettingsPage(0)
{}
+ CommentsSettings m_commentsSettings;
CppCodeStylePreferences *m_globalCodeStyle;
CompletionSettingsPage *m_completionSettingsPage;
};
@@ -82,16 +84,13 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
qRegisterMetaType<CppTools::CppCodeStyleSettings>("CppTools::CppCodeStyleSettings");
+ QSettings *s = ICore::settings();
+ d->m_commentsSettings.fromSettings(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP), s);
d->m_completionSettingsPage = new CompletionSettingsPage(this);
ExtensionSystem::PluginManager::addObject(d->m_completionSettingsPage);
- connect(d->m_completionSettingsPage,
- SIGNAL(commentsSettingsChanged(CppTools::CommentsSettings)),
- this,
- SIGNAL(commentsSettingsChanged(CppTools::CommentsSettings)));
-
// code style factory
- ICodeStylePreferencesFactory *factory = new CppTools::CppCodeStylePreferencesFactory();
+ ICodeStylePreferencesFactory *factory = new CppCodeStylePreferencesFactory();
TextEditorSettings::registerCodeStyleFactory(factory);
// code style pool
@@ -170,7 +169,6 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
pool->loadCustomCodeStyles();
// load global settings (after built-in settings are added to the pool)
- QSettings *s = Core::ICore::settings();
d->m_globalCodeStyle->fromSettings(QLatin1String(CppTools::Constants::CPP_SETTINGS_ID), s);
// legacy handling start (Qt Creator Version < 2.4)
@@ -208,7 +206,7 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
// create custom code style out of old settings
QVariant v;
v.setValue(legacyCodeStyleSettings);
- TextEditor::ICodeStylePreferences *oldCreator = pool->createCodeStyle(
+ ICodeStylePreferences *oldCreator = pool->createCodeStyle(
"legacy", legacyTabSettings, v, tr("Old Creator"));
// change the current delegate and save
@@ -253,5 +251,33 @@ CppCodeStylePreferences *CppToolsSettings::cppCodeStyle() const
const CommentsSettings &CppToolsSettings::commentsSettings() const
{
- return d->m_completionSettingsPage->commentsSettings();
+ return d->m_commentsSettings;
+}
+
+void CppToolsSettings::setCommentsSettings(const CommentsSettings &commentsSettings)
+{
+ if (d->m_commentsSettings == commentsSettings)
+ return;
+
+ d->m_commentsSettings = commentsSettings;
+ d->m_commentsSettings.toSettings(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP),
+ ICore::settings());
+}
+
+static QString sortEditorDocumentOutlineKey()
+{
+ return QLatin1String(CppTools::Constants::CPPTOOLS_SETTINGSGROUP)
+ + QLatin1Char('/')
+ + QLatin1String(CppTools::Constants::CPPTOOLS_SORT_EDITOR_DOCUMENT_OUTLINE);
+}
+
+bool CppToolsSettings::sortedEditorDocumentOutline() const
+{
+ return ICore::settings()->value(sortEditorDocumentOutlineKey(), true).toBool();
+}
+
+void CppToolsSettings::setSortedEditorDocumentOutline(bool sorted)
+{
+ ICore::settings()->setValue(sortEditorDocumentOutlineKey(), sorted);
+ emit editorDocumentOutlineSortingChanged(sorted);
}
diff --git a/src/plugins/cpptools/cpptoolssettings.h b/src/plugins/cpptools/cpptoolssettings.h
index 94d0cec8a04..f281a1bfebd 100644
--- a/src/plugins/cpptools/cpptoolssettings.h
+++ b/src/plugins/cpptools/cpptoolssettings.h
@@ -59,10 +59,15 @@ public:
static CppToolsSettings *instance();
CppCodeStylePreferences *cppCodeStyle() const;
+
const CommentsSettings &commentsSettings() const;
+ void setCommentsSettings(const CommentsSettings &commentsSettings);
+
+ bool sortedEditorDocumentOutline() const;
+ void setSortedEditorDocumentOutline(bool sorted);
signals:
- void commentsSettingsChanged(const CppTools::CommentsSettings &settings);
+ void editorDocumentOutlineSortingChanged(bool isSorted);
private:
Internal::CppToolsSettingsPrivate *d;
diff --git a/src/plugins/cpptools/cpptoolstestcase.cpp b/src/plugins/cpptools/cpptoolstestcase.cpp
index c56c2ceeda3..45960a01d83 100644
--- a/src/plugins/cpptools/cpptoolstestcase.cpp
+++ b/src/plugins/cpptools/cpptoolstestcase.cpp
@@ -30,7 +30,11 @@
#include "cpptoolstestcase.h"
+#include "cppworkingcopy.h"
+
#include <coreplugin/editormanager/editormanager.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/session.h>
#include <texteditor/texteditor.h>
#include <texteditor/codeassist/iassistproposal.h>
#include <texteditor/codeassist/iassistproposalmodel.h>
@@ -40,6 +44,8 @@
#include <QtTest>
+using namespace ProjectExplorer;
+
static bool closeEditorsWithoutGarbageCollectorInvocation(const QList<Core::IEditor *> &editors)
{
CppTools::CppModelManager::instance()->enableGarbageCollector(false);
@@ -71,8 +77,12 @@ TestDocument::TestDocument(const QByteArray &fileName, const QByteArray &source,
QString TestDocument::filePath() const
{
+ if (!m_baseDirectory.isEmpty())
+ return QDir::cleanPath(m_baseDirectory + QLatin1Char('/') + m_fileName);
+
if (!QFileInfo(m_fileName).isAbsolute())
return QDir::tempPath() + QLatin1Char('/') + m_fileName;
+
return m_fileName;
}
@@ -181,6 +191,24 @@ QList<CPlusPlus::Document::Ptr> TestCase::waitForFilesInGlobalSnapshot(
return result;
}
+bool TestCase::waitUntilCppModelManagerIsAwareOf(Project *project, int timeOut)
+{
+ if (!project)
+ return false;
+
+ QTime t;
+ t.start();
+
+ CppModelManager *modelManager = CppModelManager::instance();
+ forever {
+ if (modelManager->projectInfo(project).isValid())
+ return true;
+ if (t.elapsed() > timeOut)
+ return false;
+ QCoreApplication::processEvents();
+ }
+}
+
bool TestCase::writeFile(const QString &filePath, const QByteArray &contents)
{
Utils::FileSaver saver(filePath);
@@ -192,6 +220,97 @@ bool TestCase::writeFile(const QString &filePath, const QByteArray &contents)
return true;
}
+ProjectOpenerAndCloser::ProjectOpenerAndCloser(bool waitForFinishedGcOnDestruction)
+ : m_waitForFinishedGcOnDestruction(waitForFinishedGcOnDestruction)
+ , m_gcFinished(false)
+{
+ QVERIFY(!SessionManager::hasProjects());
+ if (m_waitForFinishedGcOnDestruction) {
+ CppModelManager *mm = CppModelManager::instance();
+ connect(mm, &CppModelManager::gcFinished, this, &ProjectOpenerAndCloser::onGcFinished);
+ }
+}
+
+ProjectOpenerAndCloser::~ProjectOpenerAndCloser()
+{
+ foreach (Project *project, m_openProjects)
+ ProjectExplorerPlugin::unloadProject(project);
+
+ if (m_waitForFinishedGcOnDestruction) {
+ m_gcFinished = false;
+ while (!m_gcFinished)
+ QCoreApplication::processEvents();
+ }
+}
+
+ProjectInfo ProjectOpenerAndCloser::open(const QString &projectFile, bool configureAsExampleProject)
+{
+ QString error;
+ Project *project = ProjectExplorerPlugin::openProject(projectFile, &error);
+ if (!error.isEmpty())
+ qWarning() << error;
+ if (!project)
+ return ProjectInfo();
+ m_openProjects.append(project);
+
+ if (configureAsExampleProject)
+ project->configureAsExampleProject(QStringList());
+
+ if (TestCase::waitUntilCppModelManagerIsAwareOf(project))
+ return CppModelManager::instance()->projectInfo(project);
+
+ return ProjectInfo();
+}
+
+void ProjectOpenerAndCloser::onGcFinished()
+{
+ m_gcFinished = true;
+}
+
+TemporaryDir::TemporaryDir()
+ : m_temporaryDir(QFileInfo(QDir::tempPath()).canonicalFilePath()
+ + QLatin1String("/qtcreator-tests-XXXXXX"))
+ , m_isValid(m_temporaryDir.isValid())
+{
+}
+
+QString TemporaryDir::createFile(const QByteArray &relativePath, const QByteArray &contents)
+{
+ const QString relativePathString = QString::fromUtf8(relativePath);
+ if (relativePathString.isEmpty() || QFileInfo(relativePathString).isAbsolute())
+ return QString();
+
+ const QString filePath = m_temporaryDir.path() + QLatin1Char('/') + relativePathString;
+ if (!TestCase::writeFile(filePath, contents))
+ return QString();
+ return filePath;
+}
+
+TemporaryCopiedDir::TemporaryCopiedDir(const QString &sourceDirPath)
+{
+ if (!m_isValid)
+ return;
+
+ if (!sourceDirPath.isEmpty()) {
+ QFileInfo fi(sourceDirPath);
+ if (!fi.exists() || !fi.isReadable()) {
+ m_isValid = false;
+ return;
+ }
+
+ if (!Utils::FileUtils::copyRecursively(Utils::FileName::fromString(sourceDirPath),
+ Utils::FileName::fromString(path()))) {
+ m_isValid = false;
+ return;
+ }
+ }
+}
+
+QString TemporaryCopiedDir::absolutePath(const QByteArray &relativePath) const
+{
+ return m_temporaryDir.path() + QLatin1Char('/') + QString::fromUtf8(relativePath);
+}
+
FileWriterAndRemover::FileWriterAndRemover(const QString &filePath, const QByteArray &contents)
: m_filePath(filePath)
{
@@ -225,5 +344,32 @@ IAssistProposalScopedPointer::~IAssistProposalScopedPointer()
delete d->model();
}
+VerifyCleanCppModelManager::VerifyCleanCppModelManager()
+{
+ QVERIFY(isClean());
+}
+
+VerifyCleanCppModelManager::~VerifyCleanCppModelManager() {
+ QVERIFY(isClean());
+}
+
+#define RETURN_FALSE_IF_NOT(check) if (!(check)) return false;
+
+bool VerifyCleanCppModelManager::isClean()
+{
+ CppModelManager *mm = CppModelManager::instance();
+ RETURN_FALSE_IF_NOT(mm);
+ RETURN_FALSE_IF_NOT(mm->projectInfos().isEmpty());
+ RETURN_FALSE_IF_NOT(mm->headerPaths().isEmpty());
+ RETURN_FALSE_IF_NOT(mm->definedMacros().isEmpty());
+ RETURN_FALSE_IF_NOT(mm->projectFiles().isEmpty());
+ RETURN_FALSE_IF_NOT(mm->snapshot().isEmpty());
+ RETURN_FALSE_IF_NOT(mm->workingCopy().size() == 1);
+ RETURN_FALSE_IF_NOT(mm->workingCopy().contains(mm->configurationFileName()));
+ return true;
+}
+
+#undef RETURN_FALSE_IF_NOT
+
} // namespace Tests
} // namespace CppTools
diff --git a/src/plugins/cpptools/cpptoolstestcase.h b/src/plugins/cpptools/cpptoolstestcase.h
index 4e3e3190287..f96bd85dc1e 100644
--- a/src/plugins/cpptools/cpptoolstestcase.h
+++ b/src/plugins/cpptools/cpptoolstestcase.h
@@ -37,6 +37,7 @@
#include <coreplugin/editormanager/ieditor.h>
#include <QStringList>
+#include <QTemporaryDir>
namespace CPlusPlus {
class Document;
@@ -44,6 +45,7 @@ class Snapshot;
}
namespace Core { class IEditor; }
+namespace ProjectExplorer { class Project; }
namespace TextEditor {
class BaseTextEditor;
@@ -58,10 +60,14 @@ class CPPTOOLS_EXPORT TestDocument
public:
TestDocument(const QByteArray &fileName, const QByteArray &source, char cursorMarker = '@');
+ QString baseDirectory() const { return m_baseDirectory; }
+ void setBaseDirectory(const QString &baseDirectory) { m_baseDirectory = baseDirectory; }
+
QString filePath() const;
bool writeToDisk() const;
public:
+ QString m_baseDirectory;
QString m_fileName;
QString m_source;
char m_cursorMarker;
@@ -87,6 +93,8 @@ public:
static CPlusPlus::Snapshot globalSnapshot();
static bool garbageCollectGlobalSnapshot();
+ static bool waitUntilCppModelManagerIsAwareOf(ProjectExplorer::Project *project,
+ int timeOut = 30 * 1000 /*= 30 secs*/);
static CPlusPlus::Document::Ptr waitForFileInGlobalSnapshot(const QString &filePath);
static QList<CPlusPlus::Document::Ptr> waitForFilesInGlobalSnapshot(
const QStringList &filePaths);
@@ -102,6 +110,59 @@ private:
bool m_runGarbageCollector;
};
+class CPPTOOLS_EXPORT ProjectOpenerAndCloser : public QObject
+{
+ Q_OBJECT
+
+public:
+ ProjectOpenerAndCloser(bool waitForFinishedGcOnDestruction = true);
+ ~ProjectOpenerAndCloser(); // Closes opened projects
+
+ ProjectInfo open(const QString &projectFile, bool configureAsExampleProject = false);
+
+private:
+ void onGcFinished();
+
+ bool m_waitForFinishedGcOnDestruction;
+ bool m_gcFinished;
+ QList<ProjectExplorer::Project *> m_openProjects;
+};
+
+class CPPTOOLS_EXPORT TemporaryDir
+{
+ Q_DISABLE_COPY(TemporaryDir)
+
+public:
+ TemporaryDir();
+
+ bool isValid() const { return m_isValid; }
+ QString path() const { return m_temporaryDir.path(); }
+
+ QString createFile(const QByteArray &relativePath, const QByteArray &contents);
+
+protected:
+ QTemporaryDir m_temporaryDir;
+ bool m_isValid;
+};
+
+class CPPTOOLS_EXPORT TemporaryCopiedDir : public TemporaryDir
+{
+public:
+ TemporaryCopiedDir(const QString &sourceDirPath);
+ QString absolutePath(const QByteArray &relativePath) const;
+
+private:
+ TemporaryCopiedDir();
+};
+
+class CPPTOOLS_EXPORT VerifyCleanCppModelManager
+{
+public:
+ VerifyCleanCppModelManager();
+ ~VerifyCleanCppModelManager();
+ static bool isClean();
+};
+
class FileWriterAndRemover
{
public:
diff --git a/src/plugins/cpptools/cppworkingcopy.h b/src/plugins/cpptools/cppworkingcopy.h
index 890577de02e..21d95781dc3 100644
--- a/src/plugins/cpptools/cppworkingcopy.h
+++ b/src/plugins/cpptools/cppworkingcopy.h
@@ -33,6 +33,8 @@
#include "cpptools_global.h"
+#include <utils/fileutils.h>
+
#include <QHash>
#include <QString>
#include <QPair>
@@ -45,28 +47,43 @@ public:
WorkingCopy();
void insert(const QString &fileName, const QByteArray &source, unsigned revision = 0)
+ { insert(Utils::FileName::fromString(fileName), source, revision); }
+
+ void insert(const Utils::FileName &fileName, const QByteArray &source, unsigned revision = 0)
{ _elements.insert(fileName, qMakePair(source, revision)); }
bool contains(const QString &fileName) const
+ { return contains(Utils::FileName::fromString(fileName)); }
+
+ bool contains(const Utils::FileName &fileName) const
{ return _elements.contains(fileName); }
QByteArray source(const QString &fileName) const
+ { return source(Utils::FileName::fromString(fileName)); }
+
+ QByteArray source(const Utils::FileName &fileName) const
{ return _elements.value(fileName).first; }
unsigned revision(const QString &fileName) const
+ { return revision(Utils::FileName::fromString(fileName)); }
+
+ unsigned revision(const Utils::FileName &fileName) const
{ return _elements.value(fileName).second; }
QPair<QByteArray, unsigned> get(const QString &fileName) const
+ { return get(Utils::FileName::fromString(fileName)); }
+
+ QPair<QByteArray, unsigned> get(const Utils::FileName &fileName) const
{ return _elements.value(fileName); }
- QHashIterator<QString, QPair<QByteArray, unsigned> > iterator() const
- { return QHashIterator<QString, QPair<QByteArray, unsigned> >(_elements); }
+ QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > iterator() const
+ { return QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> >(_elements); }
int size() const
{ return _elements.size(); }
private:
- typedef QHash<QString, QPair<QByteArray, unsigned> > Table;
+ typedef QHash<Utils::FileName, QPair<QByteArray, unsigned> > Table;
Table _elements;
};
diff --git a/src/plugins/cpptools/doxygengenerator.cpp b/src/plugins/cpptools/doxygengenerator.cpp
index ff14aa5b25c..5d493a50021 100644
--- a/src/plugins/cpptools/doxygengenerator.cpp
+++ b/src/plugins/cpptools/doxygengenerator.cpp
@@ -119,7 +119,7 @@ QString DoxygenGenerator::generate(QTextCursor cursor)
return generate(cursor, doc->translationUnit()->ast()->asDeclaration());
}
-QString DoxygenGenerator::generate(QTextCursor cursor, CPlusPlus::DeclarationAST *decl)
+QString DoxygenGenerator::generate(QTextCursor cursor, DeclarationAST *decl)
{
SpecifierAST *spec = 0;
DeclaratorAST *decltr = 0;
diff --git a/src/plugins/cpptools/editordocumenthandle.cpp b/src/plugins/cpptools/editordocumenthandle.cpp
index e09924314a4..abf70ac9da3 100644
--- a/src/plugins/cpptools/editordocumenthandle.cpp
+++ b/src/plugins/cpptools/editordocumenthandle.cpp
@@ -39,21 +39,21 @@ namespace CppTools {
C++ editor document.
*/
-EditorDocumentHandle::EditorDocumentHandle()
+CppEditorDocumentHandle::CppEditorDocumentHandle()
: m_needsRefresh(false)
{
}
-EditorDocumentHandle::~EditorDocumentHandle()
+CppEditorDocumentHandle::~CppEditorDocumentHandle()
{
}
-bool EditorDocumentHandle::needsRefresh() const
+bool CppEditorDocumentHandle::needsRefresh() const
{
return m_needsRefresh;
}
-void EditorDocumentHandle::setNeedsRefresh(bool needsRefresh)
+void CppEditorDocumentHandle::setNeedsRefresh(bool needsRefresh)
{
m_needsRefresh = needsRefresh;
}
diff --git a/src/plugins/cpptools/editordocumenthandle.h b/src/plugins/cpptools/editordocumenthandle.h
index 3ece305fa7a..06ae5fc4df9 100644
--- a/src/plugins/cpptools/editordocumenthandle.h
+++ b/src/plugins/cpptools/editordocumenthandle.h
@@ -36,11 +36,11 @@
namespace CppTools {
-class CPPTOOLS_EXPORT EditorDocumentHandle
+class CPPTOOLS_EXPORT CppEditorDocumentHandle
{
public:
- EditorDocumentHandle();
- virtual ~EditorDocumentHandle();
+ CppEditorDocumentHandle();
+ virtual ~CppEditorDocumentHandle();
bool needsRefresh() const;
void setNeedsRefresh(bool needsRefresh);
diff --git a/src/plugins/cpptools/includeutils.cpp b/src/plugins/cpptools/includeutils.cpp
index ef7743c133b..a50fb450714 100644
--- a/src/plugins/cpptools/includeutils.cpp
+++ b/src/plugins/cpptools/includeutils.cpp
@@ -131,7 +131,11 @@ LineForNewIncludeDirective::LineForNewIncludeDirective(const QTextDocument *text
, m_cppDocument(cppDocument)
, m_includeStyle(includeStyle)
{
- const QList<Document::Include> includes = cppDocument->resolvedIncludes();
+ QList<Document::Include> includes
+ = cppDocument->resolvedIncludes() + cppDocument->unresolvedIncludes();
+ Utils::sort(includes, [](const Include &left, const Include &right) {
+ return left.line() < right.line();
+ });
// Ignore *.moc includes if requested
if (mocIncludeMode == IgnoreMocIncludes) {
@@ -143,13 +147,6 @@ LineForNewIncludeDirective::LineForNewIncludeDirective(const QTextDocument *text
m_includes = includes;
}
- // TODO: Remove this filter loop once FastPreprocessor::sourceNeeded does not add
- // extra includes anymore.
- for (int i = m_includes.count() - 1; i >= 0; --i) {
- if (!QFileInfo(m_includes.at(i).resolvedFileName()).isAbsolute())
- m_includes.removeAt(i);
- }
-
// Detect include style
if (m_includeStyle == AutoDetect) {
unsigned timesIncludeStyleChanged = 0;
@@ -220,7 +217,7 @@ int LineForNewIncludeDirective::operator()(const QString &newIncludeFileName,
*newLinesToAppend = false;
const QString pureIncludeFileName = newIncludeFileName.mid(1, newIncludeFileName.length() - 2);
- const CPlusPlus::Client::IncludeType newIncludeType =
+ const Client::IncludeType newIncludeType =
newIncludeFileName.startsWith(QLatin1Char('"')) ? Client::IncludeLocal
: Client::IncludeGlobal;
@@ -328,11 +325,6 @@ QList<IncludeGroup> LineForNewIncludeDirective::getGroupsByIncludeType(
/// includes will be modified!
QList<IncludeGroup> IncludeGroup::detectIncludeGroupsByNewLines(QList<Document::Include> &includes)
{
- // Sort by line
- Utils::sort(includes, [](const Include &left, const Include &right) {
- return left.line() < right.line();
- });
-
// Create groups
QList<IncludeGroup> result;
unsigned lastLine = 0;
@@ -399,11 +391,11 @@ QList<IncludeGroup> IncludeGroup::detectIncludeGroupsByIncludeType(const QList<I
{
// Create sub groups
QList<IncludeGroup> result;
- CPlusPlus::Client::IncludeType lastIncludeType;
+ Client::IncludeType lastIncludeType;
QList<Include> currentIncludes;
bool isFirst = true;
foreach (const Include &include, includes) {
- const CPlusPlus::Client::IncludeType currentIncludeType = include.type();
+ const Client::IncludeType currentIncludeType = include.type();
// First include...
if (isFirst) {
@@ -544,14 +536,8 @@ bool IncludeGroup::hasCommonIncludeDir() const
using namespace Tests;
using CppTools::Internal::CppToolsPlugin;
-static QList<Include> includesForSource(const QByteArray &source)
+static QList<Include> includesForSource(const QString &filePath)
{
- const QString fileName = TestIncludePaths::testFilePath();
-
- FileWriterAndRemover scopedFile(fileName, source);
- if (!scopedFile.writtenSuccessfully())
- return QList<Include>();
-
using namespace CppTools::Internal;
CppModelManager *cmm = CppModelManager::instance();
cmm->GC();
@@ -560,44 +546,18 @@ static QList<Include> includesForSource(const QByteArray &source)
<< ProjectPart::HeaderPath(
TestIncludePaths::globalIncludePath(),
ProjectPart::HeaderPath::IncludePath));
- sourceProcessor->run(fileName);
+ sourceProcessor->run(filePath);
- Document::Ptr document = cmm->document(fileName);
+ Document::Ptr document = cmm->document(filePath);
return document->resolvedIncludes();
}
void CppToolsPlugin::test_includeGroups_detectIncludeGroupsByNewLines()
{
- // Source referencing those files
- QByteArray source =
- "#include \"header.h\"\n"
- "\n"
- "#include \"file.h\"\n"
- "#include \"fileother.h\"\n"
- "\n"
- "#include <lib/fileother.h>\n"
- "#include <lib/file.h>\n"
- "\n"
- "#include \"otherlib/file.h\"\n"
- "#include \"otherlib/fileother.h\"\n"
- "\n"
- "#include \"utils/utils.h\"\n"
- "\n"
- "#include <QDebug>\n"
- "#include <QDir>\n"
- "#include <QString>\n"
- "\n"
- "#include <iostream>\n"
- "#include <string>\n"
- "#include <except>\n"
- "\n"
- "#include <iostream>\n"
- "#include \"stuff\"\n"
- "#include <except>\n"
- "\n"
- ;
-
- QList<Include> includes = includesForSource(source);
+ const QString testFilePath = TestIncludePaths::testFilePath(
+ QLatin1String("test_main_detectIncludeGroupsByNewLines.cpp"));
+
+ QList<Include> includes = includesForSource(testFilePath);
QCOMPARE(includes.size(), 17);
QList<IncludeGroup> includeGroups
= IncludeGroup::detectIncludeGroupsByNewLines(includes);
@@ -636,20 +596,10 @@ void CppToolsPlugin::test_includeGroups_detectIncludeGroupsByNewLines()
void CppToolsPlugin::test_includeGroups_detectIncludeGroupsByIncludeDir()
{
- QByteArray source =
- "#include \"file.h\"\n"
- "#include \"fileother.h\"\n"
- "#include <lib/file.h>\n"
- "#include <lib/fileother.h>\n"
- "#include \"otherlib/file.h\"\n"
- "#include \"otherlib/fileother.h\"\n"
- "#include <iostream>\n"
- "#include <string>\n"
- "#include <except>\n"
- "\n"
- ;
-
- QList<Include> includes = includesForSource(source);
+ const QString testFilePath = TestIncludePaths::testFilePath(
+ QLatin1String("test_main_detectIncludeGroupsByIncludeDir.cpp"));
+
+ QList<Include> includes = includesForSource(testFilePath);
QCOMPARE(includes.size(), 9);
QList<IncludeGroup> includeGroups
= IncludeGroup::detectIncludeGroupsByIncludeDir(includes);
@@ -670,20 +620,10 @@ void CppToolsPlugin::test_includeGroups_detectIncludeGroupsByIncludeDir()
void CppToolsPlugin::test_includeGroups_detectIncludeGroupsByIncludeType()
{
- QByteArray source =
- "#include \"file.h\"\n"
- "#include \"fileother.h\"\n"
- "#include <lib/file.h>\n"
- "#include <lib/fileother.h>\n"
- "#include \"otherlib/file.h\"\n"
- "#include \"otherlib/fileother.h\"\n"
- "#include <iostream>\n"
- "#include <string>\n"
- "#include <except>\n"
- "\n"
- ;
-
- QList<Include> includes = includesForSource(source);
+ const QString testFilePath = TestIncludePaths::testFilePath(
+ QLatin1String("test_main_detectIncludeGroupsByIncludeType.cpp"));
+
+ QList<Include> includes = includesForSource(testFilePath);
QCOMPARE(includes.size(), 9);
QList<IncludeGroup> includeGroups
= IncludeGroup::detectIncludeGroupsByIncludeDir(includes);
diff --git a/src/plugins/cpptools/insertionpointlocator.cpp b/src/plugins/cpptools/insertionpointlocator.cpp
index d8e27626161..9359bb7a553 100644
--- a/src/plugins/cpptools/insertionpointlocator.cpp
+++ b/src/plugins/cpptools/insertionpointlocator.cpp
@@ -135,7 +135,7 @@ protected:
if (needsLeadingEmptyLine)
prefix += QLatin1String("\n");
if (needsPrefix)
- prefix += InsertionPointLocator::accessSpecToString(_xsSpec);
+ prefix += InsertionPointLocator::accessSpecToString(_xsSpec) + QLatin1String(":\n");
QString suffix;
if (needsSuffix)
@@ -278,25 +278,25 @@ QString InsertionPointLocator::accessSpecToString(InsertionPointLocator::AccessS
switch (xsSpec) {
default:
case InsertionPointLocator::Public:
- return QLatin1String("public:\n");
+ return QLatin1String("public");
case InsertionPointLocator::Protected:
- return QLatin1String("protected:\n");
+ return QLatin1String("protected");
case InsertionPointLocator::Private:
- return QLatin1String("private:\n");
+ return QLatin1String("private");
case InsertionPointLocator::PublicSlot:
- return QLatin1String("public slots:\n");
+ return QLatin1String("public slots");
case InsertionPointLocator::ProtectedSlot:
- return QLatin1String("protected slots:\n");
+ return QLatin1String("protected slots");
case InsertionPointLocator::PrivateSlot:
- return QLatin1String("private slots:\n");
+ return QLatin1String("private slots");
case InsertionPointLocator::Signals:
- return QLatin1String("signals:\n");
+ return QLatin1String("signals");
}
}
@@ -497,7 +497,7 @@ static InsertionLocation nextToSurroundingDefinitions(Symbol *declaration,
return noResult;
// scan preceding declarations for a function declaration (and see if it is defined)
- CppTools::SymbolFinder symbolFinder;
+ SymbolFinder symbolFinder;
Function *definitionFunction = 0;
QString prefix, suffix;
Declaration *surroundingFunctionDecl = 0;
@@ -572,7 +572,7 @@ QList<InsertionLocation> InsertionPointLocator::methodDefinition(Symbol *declara
return result;
if (useSymbolFinder) {
- CppTools::SymbolFinder symbolFinder;
+ SymbolFinder symbolFinder;
if (symbolFinder.findMatchingDefinition(declaration, m_refactoringChanges.snapshot(), true))
return result;
}
diff --git a/src/plugins/cpptools/modelmanagertesthelper.cpp b/src/plugins/cpptools/modelmanagertesthelper.cpp
index 76591cd8bee..10480482e11 100644
--- a/src/plugins/cpptools/modelmanagertesthelper.cpp
+++ b/src/plugins/cpptools/modelmanagertesthelper.cpp
@@ -30,6 +30,7 @@
#include "modelmanagertesthelper.h"
+#include "cpptoolstestcase.h"
#include "cppworkingcopy.h"
#include <QtTest>
@@ -59,22 +60,23 @@ ModelManagerTestHelper::ModelManagerTestHelper(QObject *parent) :
CppModelManager *mm = CppModelManager::instance();
assert(mm);
- connect(this, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)),
- mm, SLOT(onAboutToRemoveProject(ProjectExplorer::Project*)));
- connect(this, SIGNAL(projectAdded(ProjectExplorer::Project*)),
- mm, SLOT(onProjectAdded(ProjectExplorer::Project*)));
- connect(mm, SIGNAL(sourceFilesRefreshed(QSet<QString>)),
- this, SLOT(sourceFilesRefreshed(QSet<QString>)));
- connect(mm, SIGNAL(gcFinished()), this, SLOT(gcFinished()));
+ connect(this, &ModelManagerTestHelper::aboutToRemoveProject,
+ mm, &CppModelManager::onAboutToRemoveProject);
+ connect(this, &ModelManagerTestHelper::projectAdded,
+ mm, &CppModelManager::onProjectAdded);
+ connect(mm, &CppModelManager::sourceFilesRefreshed,
+ this, &ModelManagerTestHelper::sourceFilesRefreshed);
+ connect(mm, &CppModelManager::gcFinished,
+ this, &ModelManagerTestHelper::gcFinished);
cleanup();
- verifyClean();
+ QVERIFY(Tests::VerifyCleanCppModelManager::isClean());
}
ModelManagerTestHelper::~ModelManagerTestHelper()
{
cleanup();
- verifyClean();
+ QVERIFY(Tests::VerifyCleanCppModelManager::isClean());
}
void ModelManagerTestHelper::cleanup()
@@ -90,20 +92,6 @@ void ModelManagerTestHelper::cleanup()
waitForFinishedGc();
}
-void ModelManagerTestHelper::verifyClean()
-{
- CppModelManager *mm = CppModelManager::instance();
- assert(mm);
-
- QVERIFY(mm->projectInfos().isEmpty());
- QVERIFY(mm->headerPaths().isEmpty());
- QVERIFY(mm->definedMacros().isEmpty());
- QVERIFY(mm->projectFiles().isEmpty());
- QVERIFY(mm->snapshot().isEmpty());
- QCOMPARE(mm->workingCopy().size(), 1);
- QVERIFY(mm->workingCopy().contains(mm->configurationFileName()));
-}
-
ModelManagerTestHelper::Project *ModelManagerTestHelper::createProject(const QString &name)
{
TestProject *tp = new TestProject(name, this);
diff --git a/src/plugins/cpptools/modelmanagertesthelper.h b/src/plugins/cpptools/modelmanagertesthelper.h
index f2c25edc7b9..6da987a581f 100644
--- a/src/plugins/cpptools/modelmanagertesthelper.h
+++ b/src/plugins/cpptools/modelmanagertesthelper.h
@@ -76,7 +76,6 @@ public:
~ModelManagerTestHelper();
void cleanup();
- static void verifyClean();
Project *createProject(const QString &name);
diff --git a/src/plugins/cpptools/searchsymbols.cpp b/src/plugins/cpptools/searchsymbols.cpp
index 0f4a1d5aecf..cc7746247c3 100644
--- a/src/plugins/cpptools/searchsymbols.cpp
+++ b/src/plugins/cpptools/searchsymbols.cpp
@@ -37,7 +37,8 @@
#include <QDebug>
using namespace CPlusPlus;
-using namespace CppTools;
+
+namespace CppTools {
typedef Utils::ScopedSwap<IndexItem::Ptr> ScopedIndexItemPtr;
typedef Utils::ScopedSwap<QString> ScopedScope;
@@ -48,7 +49,7 @@ SearchSymbols::SymbolTypes SearchSymbols::AllTypes =
| SymbolSearcher::Enums
| SymbolSearcher::Declarations;
-SearchSymbols::SearchSymbols(CppTools::Internal::StringTable &stringTable)
+SearchSymbols::SearchSymbols(Internal::StringTable &stringTable)
: strings(stringTable)
, symbolsToSearchFor(SymbolSearcher::Classes | SymbolSearcher::Functions | SymbolSearcher::Enums)
{
@@ -157,92 +158,92 @@ bool SearchSymbols::visit(Class *symbol)
return false;
}
-bool SearchSymbols::visit(CPlusPlus::UsingNamespaceDirective *)
+bool SearchSymbols::visit(UsingNamespaceDirective *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::UsingDeclaration *)
+bool SearchSymbols::visit(UsingDeclaration *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::NamespaceAlias *)
+bool SearchSymbols::visit(NamespaceAlias *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::Argument *)
+bool SearchSymbols::visit(Argument *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::TypenameArgument *)
+bool SearchSymbols::visit(TypenameArgument *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::BaseClass *)
+bool SearchSymbols::visit(BaseClass *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::Template *)
+bool SearchSymbols::visit(Template *)
{
return true;
}
-bool SearchSymbols::visit(CPlusPlus::Block *)
+bool SearchSymbols::visit(Block *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ForwardClassDeclaration *)
+bool SearchSymbols::visit(ForwardClassDeclaration *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCBaseClass *)
+bool SearchSymbols::visit(ObjCBaseClass *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCBaseProtocol *)
+bool SearchSymbols::visit(ObjCBaseProtocol *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCClass *symbol)
+bool SearchSymbols::visit(ObjCClass *symbol)
{
processClass(symbol);
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCForwardClassDeclaration *)
+bool SearchSymbols::visit(ObjCForwardClassDeclaration *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCProtocol *symbol)
+bool SearchSymbols::visit(ObjCProtocol *symbol)
{
processClass(symbol);
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCForwardProtocolDeclaration *)
+bool SearchSymbols::visit(ObjCForwardProtocolDeclaration *)
{
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCMethod *symbol)
+bool SearchSymbols::visit(ObjCMethod *symbol)
{
processFunction(symbol);
return false;
}
-bool SearchSymbols::visit(CPlusPlus::ObjCPropertyDeclaration *symbol)
+bool SearchSymbols::visit(ObjCPropertyDeclaration *symbol)
{
processFunction(symbol);
return false;
@@ -336,3 +337,5 @@ void SearchSymbols::processFunction(T *func)
QString type = overview.prettyType(func->type());
addChildItem(name, type, _scope, IndexItem::Function, func);
}
+
+} // namespace CppTools
diff --git a/src/plugins/cpptools/stringtable.cpp b/src/plugins/cpptools/stringtable.cpp
index 9d23bb4ba0e..5430604c735 100644
--- a/src/plugins/cpptools/stringtable.cpp
+++ b/src/plugins/cpptools/stringtable.cpp
@@ -53,8 +53,7 @@ StringTable::StringTable()
m_gcCountDown.setObjectName(QLatin1String("StringTable::m_gcCountDown"));
m_gcCountDown.setSingleShot(true);
m_gcCountDown.setInterval(GCTimeOut);
- connect(&m_gcCountDown, SIGNAL(timeout()),
- this, SLOT(startGC()));
+ connect(&m_gcCountDown, &QTimer::timeout, this, &StringTable::startGC);
}
QString StringTable::insert(const QString &string)
diff --git a/src/plugins/cpptools/symbolsearcher_test.cpp b/src/plugins/cpptools/symbolsearcher_test.cpp
index 6471436ad88..6fcc0c08f4f 100644
--- a/src/plugins/cpptools/symbolsearcher_test.cpp
+++ b/src/plugins/cpptools/symbolsearcher_test.cpp
@@ -88,7 +88,7 @@ public:
typedef ResultData::ResultDataList ResultDataList;
-class SymbolSearcherTestCase : public CppTools::Tests::TestCase
+class SymbolSearcherTestCase : public Tests::TestCase
{
public:
/// Takes no ownership of indexingSupportToUse
diff --git a/src/plugins/cpptools/symbolsfindfilter.cpp b/src/plugins/cpptools/symbolsfindfilter.cpp
index 3733fc4fb99..ecb77142c29 100644
--- a/src/plugins/cpptools/symbolsfindfilter.cpp
+++ b/src/plugins/cpptools/symbolsfindfilter.cpp
@@ -85,32 +85,32 @@ bool SymbolsFindFilter::isEnabled() const
void SymbolsFindFilter::cancel()
{
- Core::SearchResult *search = qobject_cast<Core::SearchResult *>(sender());
+ SearchResult *search = qobject_cast<SearchResult *>(sender());
QTC_ASSERT(search, return);
- QFutureWatcher<Core::SearchResultItem> *watcher = m_watchers.key(search);
+ QFutureWatcher<SearchResultItem> *watcher = m_watchers.key(search);
QTC_ASSERT(watcher, return);
watcher->cancel();
}
void SymbolsFindFilter::setPaused(bool paused)
{
- Core::SearchResult *search = qobject_cast<Core::SearchResult *>(sender());
+ SearchResult *search = qobject_cast<SearchResult *>(sender());
QTC_ASSERT(search, return);
- QFutureWatcher<Core::SearchResultItem> *watcher = m_watchers.key(search);
+ QFutureWatcher<SearchResultItem> *watcher = m_watchers.key(search);
QTC_ASSERT(watcher, return);
if (!paused || watcher->isRunning()) // guard against pausing when the search is finished
watcher->setPaused(paused);
}
-Core::FindFlags SymbolsFindFilter::supportedFindFlags() const
+FindFlags SymbolsFindFilter::supportedFindFlags() const
{
- return Core::FindCaseSensitively | Core::FindRegularExpression | Core::FindWholeWords;
+ return FindCaseSensitively | FindRegularExpression | FindWholeWords;
}
-void SymbolsFindFilter::findAll(const QString &txt, Core::FindFlags findFlags)
+void SymbolsFindFilter::findAll(const QString &txt, FindFlags findFlags)
{
- Core::SearchResultWindow *window = Core::SearchResultWindow::instance();
- Core::SearchResult *search = window->startNewSearch(label(), toolTip(findFlags), txt);
+ SearchResultWindow *window = SearchResultWindow::instance();
+ SearchResult *search = window->startNewSearch(label(), toolTip(findFlags), txt);
search->setSearchAgainSupported(true);
connect(search, SIGNAL(activated(Core::SearchResultItem)),
this, SLOT(openEditor(Core::SearchResultItem)));
@@ -129,7 +129,7 @@ void SymbolsFindFilter::findAll(const QString &txt, Core::FindFlags findFlags)
startSearch(search);
}
-void SymbolsFindFilter::startSearch(Core::SearchResult *search)
+void SymbolsFindFilter::startSearch(SearchResult *search)
{
SymbolSearcher::Parameters parameters = search->userData().value<SymbolSearcher::Parameters>();
QSet<QString> projectFileNames;
@@ -138,7 +138,7 @@ void SymbolsFindFilter::startSearch(Core::SearchResult *search)
projectFileNames += project->files(ProjectExplorer::Project::AllFiles).toSet();
}
- QFutureWatcher<Core::SearchResultItem> *watcher = new QFutureWatcher<Core::SearchResultItem>();
+ QFutureWatcher<SearchResultItem> *watcher = new QFutureWatcher<SearchResultItem>();
m_watchers.insert(watcher, search);
connect(watcher, SIGNAL(finished()),
this, SLOT(finish()));
@@ -155,32 +155,32 @@ void SymbolsFindFilter::startSearch(Core::SearchResult *search)
void SymbolsFindFilter::addResults(int begin, int end)
{
- QFutureWatcher<Core::SearchResultItem> *watcher =
- static_cast<QFutureWatcher<Core::SearchResultItem> *>(sender());
- Core::SearchResult *search = m_watchers.value(watcher);
+ QFutureWatcher<SearchResultItem> *watcher =
+ static_cast<QFutureWatcher<SearchResultItem> *>(sender());
+ SearchResult *search = m_watchers.value(watcher);
if (!search) {
// search was removed from search history while the search is running
watcher->cancel();
return;
}
- QList<Core::SearchResultItem> items;
+ QList<SearchResultItem> items;
for (int i = begin; i < end; ++i)
items << watcher->resultAt(i);
- search->addResults(items, Core::SearchResult::AddSorted);
+ search->addResults(items, SearchResult::AddSorted);
}
void SymbolsFindFilter::finish()
{
- QFutureWatcher<Core::SearchResultItem> *watcher =
- static_cast<QFutureWatcher<Core::SearchResultItem> *>(sender());
- Core::SearchResult *search = m_watchers.value(watcher);
+ QFutureWatcher<SearchResultItem> *watcher =
+ static_cast<QFutureWatcher<SearchResultItem> *>(sender());
+ SearchResult *search = m_watchers.value(watcher);
if (search)
search->finishSearch(watcher->isCanceled());
m_watchers.remove(watcher);
watcher->deleteLater();
}
-void SymbolsFindFilter::openEditor(const Core::SearchResultItem &item)
+void SymbolsFindFilter::openEditor(const SearchResultItem &item)
{
if (!item.userData.canConvert<IndexItem::Ptr>())
return;
@@ -220,7 +220,7 @@ void SymbolsFindFilter::onTaskStarted(Id type)
}
}
-void SymbolsFindFilter::onAllTasksFinished(Core::Id type)
+void SymbolsFindFilter::onAllTasksFinished(Id type)
{
if (type == CppTools::Constants::TASK_INDEX) {
m_enabled = true;
@@ -230,7 +230,7 @@ void SymbolsFindFilter::onAllTasksFinished(Core::Id type)
void SymbolsFindFilter::searchAgain()
{
- Core::SearchResult *search = qobject_cast<Core::SearchResult *>(sender());
+ SearchResult *search = qobject_cast<SearchResult *>(sender());
QTC_ASSERT(search, return);
search->restart();
startSearch(search);
@@ -241,7 +241,7 @@ QString SymbolsFindFilter::label() const
return tr("C++ Symbols:");
}
-QString SymbolsFindFilter::toolTip(Core::FindFlags findFlags) const
+QString SymbolsFindFilter::toolTip(FindFlags findFlags) const
{
QStringList types;
if (m_symbolsToSearch & SymbolSearcher::Classes)
@@ -255,7 +255,7 @@ QString SymbolsFindFilter::toolTip(Core::FindFlags findFlags) const
return tr("Scope: %1\nTypes: %2\nFlags: %3")
.arg(searchScope() == SymbolSearcher::SearchGlobal ? tr("All") : tr("Projects"))
.arg(types.join(tr(", ")))
- .arg(Core::IFindFilter::descriptionForFindFlags(findFlags));
+ .arg(IFindFilter::descriptionForFindFlags(findFlags));
}
// #pragma mark -- SymbolsFindFilterConfigWidget
diff --git a/src/plugins/cpptools/typehierarchybuilder.cpp b/src/plugins/cpptools/typehierarchybuilder.cpp
index 57b8c156d52..1f017dcb533 100644
--- a/src/plugins/cpptools/typehierarchybuilder.cpp
+++ b/src/plugins/cpptools/typehierarchybuilder.cpp
@@ -195,9 +195,13 @@ void TypeHierarchyBuilder::buildDerived(TypeHierarchy *typeHierarchy,
QStringList TypeHierarchyBuilder::filesDependingOn(CPlusPlus::Symbol *symbol) const
{
+ QStringList deps;
if (!symbol)
- return QStringList();
+ return deps;
- const QString file = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());
- return QStringList() << file << _snapshot.filesDependingOn(file);
+ Utils::FileName file = Utils::FileName::fromUtf8(symbol->fileName(), symbol->fileNameLength());
+ deps << file.toString();
+ foreach (const Utils::FileName &fileName, _snapshot.filesDependingOn(file))
+ deps.append(fileName.toString());
+ return deps;
}
diff --git a/src/plugins/cpptools/typehierarchybuilder_test.cpp b/src/plugins/cpptools/typehierarchybuilder_test.cpp
index 54148ca1e78..c4204f11be2 100644
--- a/src/plugins/cpptools/typehierarchybuilder_test.cpp
+++ b/src/plugins/cpptools/typehierarchybuilder_test.cpp
@@ -95,7 +95,7 @@ private:
Class *m_clazz;
};
-class TypeHierarchyBuilderTestCase : public CppTools::Tests::TestCase
+class TypeHierarchyBuilderTestCase : public Tests::TestCase
{
public:
TypeHierarchyBuilderTestCase(const QList<Tests::TestDocument> &documents,
@@ -103,11 +103,17 @@ public:
{
QVERIFY(succeededSoFar());
+ Tests::TemporaryDir temporaryDir;
+ QVERIFY(temporaryDir.isValid());
+
+ QList<Tests::TestDocument> documents_ = documents;
+
// Write files
QSet<QString> filePaths;
- foreach (const Tests::TestDocument &document, documents) {
- QVERIFY(document.writeToDisk());
- filePaths << document.filePath();
+ for (int i = 0, size = documents_.size(); i < size; ++i) {
+ documents_[i].setBaseDirectory(temporaryDir.path());
+ QVERIFY(documents_[i].writeToDisk());
+ filePaths << documents_[i].filePath();
}
// Parse files
@@ -115,7 +121,7 @@ public:
const Snapshot snapshot = globalSnapshot();
// Get class for which to generate the hierarchy
- const Document::Ptr firstDocument = snapshot.document(documents.first().filePath());
+ const Document::Ptr firstDocument = snapshot.document(documents_.first().filePath());
QVERIFY(firstDocument);
QVERIFY(firstDocument->diagnosticMessages().isEmpty());
Class *clazz = FindFirstClassInDocument()(firstDocument);
diff --git a/src/plugins/cvs/checkoutwizard.cpp b/src/plugins/cvs/checkoutwizard.cpp
index 116aaeea920..65573926bb9 100644
--- a/src/plugins/cvs/checkoutwizard.cpp
+++ b/src/plugins/cvs/checkoutwizard.cpp
@@ -35,7 +35,7 @@
#include <coreplugin/iversioncontrol.h>
#include <vcsbase/vcscommand.h>
#include <vcsbase/vcsbaseconstants.h>
-#include <vcsbase/vcsconfigurationpage.h>
+#include <vcsbase/wizard/vcsconfigurationpage.h>
#include <utils/qtcassert.h>
using namespace VcsBase;
@@ -51,9 +51,12 @@ CheckoutWizard::CheckoutWizard(const Utils::FileName &path, QWidget *parent) :
BaseCheckoutWizard(path, parent)
{
const Core::IVersionControl *vc = CvsPlugin::instance()->versionControl();
- if (!vc->isConfigured())
- addPage(new VcsConfigurationPage(vc));
- CheckoutWizardPage *cwp = new CheckoutWizardPage;
+ if (!vc->isConfigured()) {
+ auto configPage = new VcsConfigurationPage;
+ configPage->setVersionControl(vc);
+ addPage(configPage);
+ }
+ auto cwp = new CheckoutWizardPage;
cwp->setPath(path.toString());
addPage(cwp);
}
@@ -78,8 +81,8 @@ VcsCommand *CheckoutWizard::createCommand(Utils::FileName *checkoutDir)
const QString workingDirectory = cwp->path();
*checkoutDir = Utils::FileName::fromString(workingDirectory + QLatin1Char('/') + repository);
- VcsCommand *command = new VcsCommand(binary, workingDirectory,
- QProcessEnvironment::systemEnvironment());
+ auto command = new VcsCommand(binary, workingDirectory,
+ QProcessEnvironment::systemEnvironment());
command->addJob(settings.addOptions(args), -1);
return command;
}
diff --git a/src/plugins/cvs/cvsclient.cpp b/src/plugins/cvs/cvsclient.cpp
index 90984e5cbd8..d41c7c4467a 100644
--- a/src/plugins/cvs/cvsclient.cpp
+++ b/src/plugins/cvs/cvsclient.cpp
@@ -65,59 +65,40 @@ SynchronousProcessResponse::Result CvsDiffExitCodeInterpreter::interpretExitCode
return SynchronousProcessResponse::Finished;
}
-// 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 CvsDiffParameters
-{
- QString workingDir;
- QStringList extraOptions;
- QStringList files;
-};
-
// Parameter widget controlling whitespace diff mode, associated with a parameter
class CvsDiffParameterWidget : public VcsBaseEditorParameterWidget
{
Q_OBJECT
public:
- explicit CvsDiffParameterWidget(CvsClient *client,
- const CvsDiffParameters &p,
- QWidget *parent = 0);
+ explicit CvsDiffParameterWidget(CvsSettings *settings, QWidget *parent = 0);
QStringList arguments() const;
- void executeCommand();
private:
-
- CvsClient *m_client;
- const CvsDiffParameters m_params;
+ const CvsSettings *m_settings;
};
-CvsDiffParameterWidget::CvsDiffParameterWidget(CvsClient *client,
- const CvsDiffParameters &p,
- QWidget *parent)
- : VcsBaseEditorParameterWidget(parent), m_client(client), m_params(p)
+CvsDiffParameterWidget::CvsDiffParameterWidget(CvsSettings *settings, QWidget *parent)
+ : VcsBaseEditorParameterWidget(parent),
+ m_settings(settings)
{
mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace")),
- client->settings()->boolPointer(CvsSettings::diffIgnoreWhiteSpaceKey));
+ settings->boolPointer(CvsSettings::diffIgnoreWhiteSpaceKey));
mapSetting(addToggleButton(QLatin1String("-B"), tr("Ignore Blank Lines")),
- client->settings()->boolPointer(CvsSettings::diffIgnoreBlankLinesKey));
+ settings->boolPointer(CvsSettings::diffIgnoreBlankLinesKey));
}
QStringList CvsDiffParameterWidget::arguments() const
{
QStringList args;
- args = m_client->settings()->stringValue(CvsSettings::diffOptionsKey).split(QLatin1Char(' '), QString::SkipEmptyParts);
+ args = m_settings->stringValue(CvsSettings::diffOptionsKey).split(QLatin1Char(' '), QString::SkipEmptyParts);
args += VcsBaseEditorParameterWidget::arguments();
return args;
}
-void CvsDiffParameterWidget::executeCommand()
-{
- m_client->diff(m_params.workingDir, m_params.files, m_params.extraOptions);
-}
-
CvsClient::CvsClient(CvsSettings *settings) :
VcsBaseClient(settings)
{
+ setDiffParameterWidgetCreator([=] { return new CvsDiffParameterWidget(settings); });
}
CvsSettings *CvsClient::settings() const
@@ -169,17 +150,6 @@ VcsBaseClient::StatusItem CvsClient::parseStatusLine(const QString &line) const
return VcsBaseClient::StatusItem();
}
-VcsBaseEditorParameterWidget *CvsClient::createDiffEditor(
- const QString &workingDir, const QStringList &files, const QStringList &extraOptions)
-{
- Q_UNUSED(extraOptions)
- CvsDiffParameters p;
- p.workingDir = workingDir;
- p.files = files;
- p.extraOptions = extraOptions;
- return new CvsDiffParameterWidget(this, p);
-}
-
} // namespace Internal
} // namespace Cvs
diff --git a/src/plugins/cvs/cvsclient.h b/src/plugins/cvs/cvsclient.h
index 8e3134a6abb..1b3058e95a9 100644
--- a/src/plugins/cvs/cvsclient.h
+++ b/src/plugins/cvs/cvsclient.h
@@ -53,14 +53,9 @@ public:
QStringList revisionSpec(const QString &revision) const;
StatusItem parseStatusLine(const QString &line) const;
-
protected:
Utils::ExitCodeInterpreter *exitCodeInterpreter(VcsCommandTag cmd, QObject *parent) const;
Core::Id vcsEditorKind(VcsCommandTag cmd) const;
- VcsBase::VcsBaseEditorParameterWidget *createDiffEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions);
-private:
};
} // namespace Internal
diff --git a/src/plugins/cvs/cvscontrol.cpp b/src/plugins/cvs/cvscontrol.cpp
index bb494770973..2aa38aeaea2 100644
--- a/src/plugins/cvs/cvscontrol.cpp
+++ b/src/plugins/cvs/cvscontrol.cpp
@@ -74,8 +74,6 @@ bool CvsControl::supportsOperation(Operation operation) const
case MoveOperation:
case CreateRepositoryOperation:
case SnapshotOperations:
- case CheckoutOperation:
- case GetRepositoryRootOperation:
rc = false;
break;
}
@@ -118,16 +116,6 @@ bool CvsControl::vcsCreateRepository(const QString &)
return false;
}
-QString CvsControl::vcsGetRepositoryURL(const QString &)
-{
- return QString();
-}
-
-bool CvsControl::vcsCheckout(const QString &, const QByteArray &)
-{
- return false;
-}
-
bool CvsControl::vcsAnnotate(const QString &file, int line)
{
const QFileInfo fi(file);
diff --git a/src/plugins/cvs/cvscontrol.h b/src/plugins/cvs/cvscontrol.h
index b4ec77be317..c1bedee0f35 100644
--- a/src/plugins/cvs/cvscontrol.h
+++ b/src/plugins/cvs/cvscontrol.h
@@ -59,8 +59,6 @@ public:
bool vcsDelete(const QString &filename);
bool vcsMove(const QString &from, const QString &to);
bool vcsCreateRepository(const QString &directory);
- bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
bool vcsAnnotate(const QString &file, int line);
QString vcsOpenText() const;
diff --git a/src/plugins/cvs/cvsplugin.cpp b/src/plugins/cvs/cvsplugin.cpp
index 380edbfc8a3..94fd10fc8bc 100644
--- a/src/plugins/cvs/cvsplugin.cpp
+++ b/src/plugins/cvs/cvsplugin.cpp
@@ -111,6 +111,8 @@ const char CMD_ID_COMMIT_CURRENT[] = "CVS.CommitCurrent";
const char CMD_ID_FILELOG_CURRENT[] = "CVS.FilelogCurrent";
const char CMD_ID_ANNOTATE_CURRENT[] = "CVS.AnnotateCurrent";
const char CMD_ID_STATUS[] = "CVS.Status";
+const char CMD_ID_UPDATE_DIRECTORY[] = "CVS.UpdateDirectory";
+const char CMD_ID_COMMIT_DIRECTORY[] = "CVS.CommitDirectory";
const char CMD_ID_UPDATE[] = "CVS.Update";
const char CMD_ID_PROJECTLOG[] = "CVS.ProjectLog";
const char CMD_ID_PROJECTCOMMIT[] = "CVS.ProjectCommit";
@@ -185,6 +187,8 @@ CvsPlugin::CvsPlugin() :
m_statusProjectAction(0),
m_updateProjectAction(0),
m_commitProjectAction(0),
+ m_updateDirectoryAction(0),
+ m_commitDirectoryAction(0),
m_diffRepositoryAction(0),
m_updateRepositoryAction(0),
m_statusRepositoryAction(0),
@@ -402,6 +406,23 @@ bool CvsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
cvsMenu->addSeparator(context);
+ m_updateDirectoryAction = new ParameterAction(tr("Update Directory"), tr("Update Directory \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
+ command = ActionManager::registerAction(m_updateDirectoryAction, CMD_ID_UPDATE_DIRECTORY, context);
+ command->setAttribute(Command::CA_UpdateText);
+ connect(m_updateDirectoryAction, SIGNAL(triggered()), this, SLOT(updateDirectory()));
+ cvsMenu->addAction(command);
+ m_commandLocator->appendCommand(command);
+
+ m_commitDirectoryAction = new ParameterAction(tr("Commit Directory"), tr("Commit Directory \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
+ command = ActionManager::registerAction(m_commitDirectoryAction,
+ CMD_ID_COMMIT_DIRECTORY, context);
+ command->setAttribute(Command::CA_UpdateText);
+ connect(m_commitDirectoryAction, SIGNAL(triggered()), this, SLOT(startCommitDirectory()));
+ cvsMenu->addAction(command);
+ m_commandLocator->appendCommand(command);
+
+ cvsMenu->addSeparator(context);
+
m_diffRepositoryAction = new QAction(tr("Diff Repository"), this);
command = ActionManager::registerAction(m_diffRepositoryAction, CMD_ID_REPOSITORYDIFF, context);
connect(m_diffRepositoryAction, SIGNAL(triggered()), this, SLOT(diffRepository()));
@@ -471,7 +492,7 @@ bool CvsPlugin::submitEditorAboutToClose()
// Submit editor closing. Make it write out the commit message
// and retrieve files
- const QFileInfo editorFile(editorDocument->filePath());
+ const QFileInfo editorFile = editorDocument->filePath().toFileInfo();
const QFileInfo changeFile(m_commitMessageFileName);
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
return true; // Oops?!
@@ -559,6 +580,13 @@ void CvsPlugin::updateActions(VcsBasePlugin::ActionState as)
m_logProjectAction->setParameter(currentProjectName);
m_commitProjectAction->setParameter(currentProjectName);
+ // TODO: Find a more elegant way to shorten the path
+ QString currentDirectoryName = QDir::toNativeSeparators(currentState().currentFileDirectory());
+ if (currentDirectoryName.size() > 15)
+ currentDirectoryName.replace(0, currentDirectoryName.size() - 15, QLatin1String("..."));
+ m_updateDirectoryAction->setParameter(currentDirectoryName);
+ m_commitDirectoryAction->setParameter(currentDirectoryName);
+
m_diffRepositoryAction->setEnabled(hasTopLevel);
m_statusRepositoryAction->setEnabled(hasTopLevel);
m_updateRepositoryAction->setEnabled(hasTopLevel);
@@ -648,7 +676,17 @@ void CvsPlugin::startCommitCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- startCommit(state.currentFileTopLevel(), state.relativeCurrentFile());
+ /* The following has the same effect as
+ startCommit(state.currentFileTopLevel(), state.relativeCurrentFile()),
+ but is faster when the project has multiple directory levels */
+ startCommit(state.currentFileDirectory(), state.currentFileName());
+}
+
+void CvsPlugin::startCommitDirectory()
+{
+ const VcsBasePluginState state = currentState();
+ QTC_ASSERT(state.hasFile(), return);
+ startCommit(state.currentFileDirectory());
}
void CvsPlugin::startCommitAll()
@@ -780,6 +818,13 @@ void CvsPlugin::filelog(const QString &workingDir,
}
}
+void CvsPlugin::updateDirectory()
+{
+ const VcsBasePluginState state = currentState();
+ QTC_ASSERT(state.hasFile(), return);
+ update(state.currentFileDirectory(), QString());
+}
+
void CvsPlugin::updateProject()
{
const VcsBasePluginState state = currentState();
diff --git a/src/plugins/cvs/cvsplugin.h b/src/plugins/cvs/cvsplugin.h
index 2e61ebbba54..2e9f61fb08c 100644
--- a/src/plugins/cvs/cvsplugin.h
+++ b/src/plugins/cvs/cvsplugin.h
@@ -106,11 +106,13 @@ private slots:
void diffCurrentFile();
void revertAll();
void startCommitAll();
+ void startCommitDirectory();
void startCommitCurrentFile();
void filelogCurrentFile();
void annotateCurrentFile();
void projectStatus();
void slotDescribe(const QString &source, const QString &changeNr);
+ void updateDirectory();
void updateProject();
void submitCurrentLog();
void diffCommitFiles(const QStringList &);
@@ -190,6 +192,8 @@ private:
Utils::ParameterAction *m_statusProjectAction;
Utils::ParameterAction *m_updateProjectAction;
Utils::ParameterAction *m_commitProjectAction;
+ Utils::ParameterAction *m_updateDirectoryAction;
+ Utils::ParameterAction *m_commitDirectoryAction;
QAction *m_diffRepositoryAction;
QAction *m_updateRepositoryAction;
QAction *m_statusRepositoryAction;
diff --git a/src/plugins/cvs/cvssubmiteditor.cpp b/src/plugins/cvs/cvssubmiteditor.cpp
index 975d52e5b76..91edd3939f8 100644
--- a/src/plugins/cvs/cvssubmiteditor.cpp
+++ b/src/plugins/cvs/cvssubmiteditor.cpp
@@ -38,7 +38,7 @@ using namespace Cvs::Internal;
using namespace VcsBase;
CvsSubmitEditor::CvsSubmitEditor(const VcsBaseSubmitEditorParameters *parameters) :
- VcsBaseSubmitEditor(parameters, new VcsBase::SubmitEditorWidget),
+ VcsBaseSubmitEditor(parameters, new SubmitEditorWidget),
m_msgAdded(tr("Added")),
m_msgRemoved(tr("Removed")),
m_msgModified(tr("Modified"))
@@ -61,7 +61,7 @@ QString CvsSubmitEditor::stateName(State st) const
void CvsSubmitEditor::setStateList(const StateFilePairs &statusOutput)
{
typedef StateFilePairs::const_iterator ConstIterator;
- SubmitFileModel *model = new SubmitFileModel(this);
+ auto model = new SubmitFileModel(this);
const ConstIterator cend = statusOutput.constEnd();
for (ConstIterator it = statusOutput.constBegin(); it != cend; ++it)
diff --git a/src/plugins/debugger/breakhandler.cpp b/src/plugins/debugger/breakhandler.cpp
index 75534a428a9..a13f54326c0 100644
--- a/src/plugins/debugger/breakhandler.cpp
+++ b/src/plugins/debugger/breakhandler.cpp
@@ -29,7 +29,6 @@
****************************************************************************/
#include "breakhandler.h"
-#include "breakpointmarker.h"
#include "debuggeractions.h"
#include "debuggercore.h"
@@ -38,6 +37,7 @@
#include "simplifytype.h"
#include <extensionsystem/invoker.h>
+#include <texteditor/textmark.h>
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
@@ -49,17 +49,125 @@
#include <QDir>
#include <QDebug>
-#define BREAK_ASSERT(cond, action) if (cond) {} else { action; }
-//#define BREAK_ASSERT(cond, action) QTC_ASSERT(cond, action)
+using namespace Utils;
+
+namespace Debugger {
+namespace Internal {
+
+struct LocationItem : public TreeItem
+{
+ QVariant data(int column, int role) const
+ {
+ if (role == Qt::DisplayRole) {
+ switch (column) {
+ case 0:
+ return params.id.toString();
+ case 1:
+ return params.functionName;
+ case 4:
+ if (params.address)
+ return QString::fromLatin1("0x%1").arg(params.address, 0, 16);
+ }
+ }
+ return QVariant();
+ }
+
+ BreakpointResponse params;
+};
+
+class BreakpointMarker;
+
+class BreakpointItem : public QObject, public TreeItem
+{
+ Q_DECLARE_TR_FUNCTIONS(Debugger::Internal::BreakHandler)
+
+public:
+ ~BreakpointItem();
+
+ QVariant data(int column, int role) const;
+
+ QIcon icon() const;
+
+ void removeBreakpoint();
+ void updateLineNumberFromMarker(int lineNumber);
+ void updateFileNameFromMarker(const QString &fileName);
+ void changeLineNumberFromMarker(int lineNumber);
+ bool isLocatedAt(const QString &fileName, int lineNumber, bool useMarkerPosition) const;
+
+ bool needsChildren() const;
+
+ void setMarkerFileAndLine(const QString &fileName, int lineNumber);
+
+ void insertSubBreakpoint(const BreakpointResponse &params);
+ QString markerFileName() const;
+ int markerLineNumber() const;
+
+ bool needsChange() const;
+private:
+ friend class BreakHandler;
+ friend class Breakpoint;
+ BreakpointItem(BreakHandler *handler);
+
+ void destroyMarker();
+ void updateMarker();
+ void updateMarkerIcon();
+ void scheduleSynchronization();
+
+ QString toToolTip() const;
+ void setState(BreakpointState state);
+ void deleteThis();
+ bool isEngineRunning() const;
+
+ BreakHandler * const m_handler;
+ const BreakpointModelId m_id;
+ BreakpointParameters m_params;
+ BreakpointState m_state; // Current state of breakpoint.
+ DebuggerEngine *m_engine; // Engine currently handling the breakpoint.
+ BreakpointResponse m_response;
+ BreakpointMarker *m_marker;
+};
-//////////////////////////////////////////////////////////////////
//
-// BreakHandler
+// BreakpointMarker
//
-//////////////////////////////////////////////////////////////////
-namespace Debugger {
-namespace Internal {
+// The red blob on the left side in the cpp editor.
+class BreakpointMarker : public TextEditor::TextMark
+{
+public:
+ BreakpointMarker(BreakpointItem *b, const QString &fileName, int lineNumber)
+ : TextMark(fileName, lineNumber), m_bp(b)
+ {
+ setIcon(b->icon());
+ setPriority(TextEditor::TextMark::NormalPriority);
+ }
+
+ void removedFromEditor()
+ {
+ if (m_bp)
+ m_bp->removeBreakpoint();
+ }
+
+ void updateLineNumber(int lineNumber)
+ {
+ TextMark::updateLineNumber(lineNumber);
+ m_bp->updateLineNumberFromMarker(lineNumber);
+ }
+
+ void updateFileName(const QString &fileName)
+ {
+ TextMark::updateFileName(fileName);
+ m_bp->updateFileNameFromMarker(fileName);
+ }
+
+ bool isDraggable() const { return true; }
+ void dragToLine(int line) { m_bp->changeLineNumberFromMarker(line); }
+ bool isClickable() const { return true; }
+ void clicked() { m_bp->removeBreakpoint(); }
+
+public:
+ BreakpointItem *m_bp;
+};
static QString stateToString(BreakpointState state)
{
@@ -135,14 +243,16 @@ static QString typeToString(BreakpointType type)
BreakHandler::BreakHandler()
: m_syncTimerId(-1)
{
+ qRegisterMetaType<BreakpointModelId>();
+
#if USE_BREAK_MODEL_TEST
new ModelTest(this, 0);
#endif
+ setHeader(QStringList()
+ << tr("Number") << tr("Function") << tr("File") << tr("Line")
+ << tr("Address") << tr("Condition") << tr("Ignore") << tr("Threads"));
}
-BreakHandler::~BreakHandler()
-{}
-
QIcon BreakHandler::breakpointIcon()
{
static QIcon icon(_(":/debugger/images/breakpoint_16.png"));
@@ -183,276 +293,260 @@ QIcon BreakHandler::emptyIcon()
static inline bool fileNameMatch(const QString &f1, const QString &f2)
{
- if (Utils::HostOsInfo::fileNameCaseSensitivity() == Qt::CaseInsensitive)
+ if (HostOsInfo::fileNameCaseSensitivity() == Qt::CaseInsensitive)
return f1.compare(f2, Qt::CaseInsensitive) == 0;
return f1 == f2;
}
-static bool isSimilarTo(const BreakpointParameters &data, const BreakpointResponse &needle)
+static bool isSimilarTo(const BreakpointParameters &params, const BreakpointResponse &needle)
{
// Clear miss.
- if (needle.type != UnknownBreakpointType && data.type != UnknownBreakpointType
- && data.type != needle.type)
+ if (needle.type != UnknownBreakpointType && params.type != UnknownBreakpointType
+ && params.type != needle.type)
return false;
// Clear hit.
- if (data.address && data.address == needle.address)
+ if (params.address && params.address == needle.address)
return true;
// Clear hit.
- if (data == needle)
+ if (params == needle)
return true;
// At least at a position we were looking for.
// FIXME: breaks multiple breakpoints at the same location
- if (!data.fileName.isEmpty()
- && fileNameMatch(data.fileName, needle.fileName)
- && data.lineNumber == needle.lineNumber)
+ if (!params.fileName.isEmpty()
+ && fileNameMatch(params.fileName, needle.fileName)
+ && params.lineNumber == needle.lineNumber)
return true;
// At least at a position we were looking for.
// FIXME: breaks multiple breakpoints at the same location
- if (!data.fileName.isEmpty()
- && fileNameMatch(data.fileName, needle.fileName)
- && data.lineNumber == needle.lineNumber)
+ if (!params.fileName.isEmpty()
+ && fileNameMatch(params.fileName, needle.fileName)
+ && params.lineNumber == needle.lineNumber)
return true;
return false;
}
-BreakpointModelId BreakHandler::findSimilarBreakpoint(const BreakpointResponse &needle) const
+Breakpoint BreakHandler::findSimilarBreakpoint(const BreakpointResponse &needle) const
{
// Search a breakpoint we might refer to.
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it) {
- const BreakpointModelId id = it.key();
- const BreakpointParameters &data = it->data;
- const BreakpointResponse &response = it->response;
- //qDebug() << "COMPARING " << data.toString() << " WITH " << needle.toString();
- if (response.id.isValid() && response.id.majorPart() == needle.id.majorPart())
- return id;
-
- if (isSimilarTo(data, needle))
- return id;
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ //qDebug() << "COMPARING " << params.toString() << " WITH " << needle.toString();
+ if (b->m_response.id.isValid() && b->m_response.id.majorPart() == needle.id.majorPart())
+ return Breakpoint(b);
+
+ if (isSimilarTo(b->m_params, needle))
+ return Breakpoint(b);
}
- return BreakpointModelId();
+ return Breakpoint();
}
-BreakpointModelId BreakHandler::findBreakpointByResponseId(const BreakpointResponseId &id) const
+Breakpoint BreakHandler::findBreakpointByResponseId(const BreakpointResponseId &id) const
{
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it)
- if (it->response.id.majorPart() == id.majorPart())
- return it.key();
- return BreakpointModelId();
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->m_response.id.majorPart() == id.majorPart())
+ return Breakpoint(b);
+ }
+ return Breakpoint();
}
-BreakpointModelId BreakHandler::findBreakpointByFunction(const QString &functionName) const
+Breakpoint BreakHandler::findBreakpointByFunction(const QString &functionName) const
{
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it)
- if (it->data.functionName == functionName)
- return it.key();
- return BreakpointModelId();
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->m_params.functionName == functionName)
+ return Breakpoint(b);
+ }
+ return Breakpoint();
}
-BreakpointModelId BreakHandler::findBreakpointByAddress(quint64 address) const
+Breakpoint BreakHandler::findBreakpointByAddress(quint64 address) const
{
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it)
- if (it->data.address == address || it->response.address == address)
- return it.key();
- return BreakpointModelId();
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->m_params.address == address || b->m_params.address == address)
+ return Breakpoint(b);
+ }
+ return Breakpoint();
}
-BreakpointModelId BreakHandler::findBreakpointByFileAndLine(const QString &fileName,
+Breakpoint BreakHandler::findBreakpointByFileAndLine(const QString &fileName,
int lineNumber, bool useMarkerPosition)
{
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it)
- if (it->isLocatedAt(fileName, lineNumber, useMarkerPosition))
- return it.key();
- return BreakpointModelId();
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->isLocatedAt(fileName, lineNumber, useMarkerPosition))
+ return Breakpoint(b);
+ }
+ return Breakpoint();
}
-const BreakpointParameters &BreakHandler::breakpointData(BreakpointModelId id) const
+Breakpoint BreakHandler::breakpointById(BreakpointModelId id) const
{
- static BreakpointParameters dummy;
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return dummy);
- return it->data;
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->m_id == id)
+ return Breakpoint(b);
+ }
+ return Breakpoint();
}
-BreakpointModelId BreakHandler::findWatchpoint(const BreakpointParameters &data) const
+void BreakHandler::deletionHelper(BreakpointModelId id)
{
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it)
- if (it->data.isWatchpoint()
- && it->data.address == data.address
- && it->data.size == data.size
- && it->data.expression == data.expression
- && it->data.bitpos == data.bitpos)
- return it.key();
- return BreakpointModelId();
+ Breakpoint b = breakpointById(id);
+ QTC_ASSERT(b, return);
+ removeItem(b.b);
+ delete b.b;
+}
+
+Breakpoint BreakHandler::findWatchpoint(const BreakpointParameters &params) const
+{
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->m_params.isWatchpoint()
+ && b->m_params.address == params.address
+ && b->m_params.size == params.size
+ && b->m_params.expression == params.expression
+ && b->m_params.bitpos == params.bitpos)
+ return Breakpoint(b);
+ }
+ return Breakpoint();
}
void BreakHandler::saveBreakpoints()
{
const QString one = _("1");
- //qDebug() << "SAVING BREAKPOINTS...";
QList<QVariant> list;
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it) {
- const BreakpointParameters &data = it->data;
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ const BreakpointParameters &params = b->m_params;
QMap<QString, QVariant> map;
- if (data.type != BreakpointByFileAndLine)
- map.insert(_("type"), data.type);
- if (!data.fileName.isEmpty())
- map.insert(_("filename"), data.fileName);
- if (data.lineNumber)
- map.insert(_("linenumber"), data.lineNumber);
- if (!data.functionName.isEmpty())
- map.insert(_("funcname"), data.functionName);
- if (data.address)
- map.insert(_("address"), data.address);
- if (!data.condition.isEmpty())
- map.insert(_("condition"), data.condition);
- if (data.ignoreCount)
- map.insert(_("ignorecount"), data.ignoreCount);
- if (data.threadSpec >= 0)
- map.insert(_("threadspec"), data.threadSpec);
- if (!data.enabled)
+ if (params.type != BreakpointByFileAndLine)
+ map.insert(_("type"), params.type);
+ if (!params.fileName.isEmpty())
+ map.insert(_("filename"), params.fileName);
+ if (params.lineNumber)
+ map.insert(_("linenumber"), params.lineNumber);
+ if (!params.functionName.isEmpty())
+ map.insert(_("funcname"), params.functionName);
+ if (params.address)
+ map.insert(_("address"), params.address);
+ if (!params.condition.isEmpty())
+ map.insert(_("condition"), params.condition);
+ if (params.ignoreCount)
+ map.insert(_("ignorecount"), params.ignoreCount);
+ if (params.threadSpec >= 0)
+ map.insert(_("threadspec"), params.threadSpec);
+ if (!params.enabled)
map.insert(_("disabled"), one);
- if (data.oneShot)
+ if (params.oneShot)
map.insert(_("oneshot"), one);
- if (data.pathUsage != BreakpointPathUsageEngineDefault)
- map.insert(_("usefullpath"), QString::number(data.pathUsage));
- if (data.tracepoint)
+ if (params.pathUsage != BreakpointPathUsageEngineDefault)
+ map.insert(_("usefullpath"), QString::number(params.pathUsage));
+ if (params.tracepoint)
map.insert(_("tracepoint"), one);
- if (!data.module.isEmpty())
- map.insert(_("module"), data.module);
- if (!data.command.isEmpty())
- map.insert(_("command"), data.command);
- if (!data.expression.isEmpty())
- map.insert(_("expression"), data.expression);
- if (!data.message.isEmpty())
- map.insert(_("message"), data.message);
+ if (!params.module.isEmpty())
+ map.insert(_("module"), params.module);
+ if (!params.command.isEmpty())
+ map.insert(_("command"), params.command);
+ if (!params.expression.isEmpty())
+ map.insert(_("expression"), params.expression);
+ if (!params.message.isEmpty())
+ map.insert(_("message"), params.message);
list.append(map);
}
setSessionValue("Breakpoints", list);
- //qDebug() << "SAVED BREAKPOINTS" << this << list.size();
}
void BreakHandler::loadBreakpoints()
{
- //qDebug() << "LOADING BREAKPOINTS...";
QVariant value = sessionValue("Breakpoints");
QList<QVariant> list = value.toList();
- //clear();
foreach (const QVariant &var, list) {
const QMap<QString, QVariant> map = var.toMap();
- BreakpointParameters data(BreakpointByFileAndLine);
+ BreakpointParameters params(BreakpointByFileAndLine);
QVariant v = map.value(_("filename"));
if (v.isValid())
- data.fileName = v.toString();
+ params.fileName = v.toString();
v = map.value(_("linenumber"));
if (v.isValid())
- data.lineNumber = v.toString().toInt();
+ params.lineNumber = v.toString().toInt();
v = map.value(_("condition"));
if (v.isValid())
- data.condition = v.toString().toLatin1();
+ params.condition = v.toString().toLatin1();
v = map.value(_("address"));
if (v.isValid())
- data.address = v.toString().toULongLong();
+ params.address = v.toString().toULongLong();
v = map.value(_("ignorecount"));
if (v.isValid())
- data.ignoreCount = v.toString().toInt();
+ params.ignoreCount = v.toString().toInt();
v = map.value(_("threadspec"));
if (v.isValid())
- data.threadSpec = v.toString().toInt();
+ params.threadSpec = v.toString().toInt();
v = map.value(_("funcname"));
if (v.isValid())
- data.functionName = v.toString();
+ params.functionName = v.toString();
v = map.value(_("disabled"));
if (v.isValid())
- data.enabled = !v.toInt();
+ params.enabled = !v.toInt();
v = map.value(_("oneshot"));
if (v.isValid())
- data.oneShot = v.toInt();
+ params.oneShot = v.toInt();
v = map.value(_("usefullpath"));
if (v.isValid())
- data.pathUsage = static_cast<BreakpointPathUsage>(v.toInt());
+ params.pathUsage = static_cast<BreakpointPathUsage>(v.toInt());
v = map.value(_("tracepoint"));
if (v.isValid())
- data.tracepoint = bool(v.toInt());
+ params.tracepoint = bool(v.toInt());
v = map.value(_("type"));
if (v.isValid() && v.toInt() != UnknownBreakpointType)
- data.type = BreakpointType(v.toInt());
+ params.type = BreakpointType(v.toInt());
v = map.value(_("module"));
if (v.isValid())
- data.module = v.toString();
+ params.module = v.toString();
v = map.value(_("command"));
if (v.isValid())
- data.command = v.toString();
+ params.command = v.toString();
v = map.value(_("expression"));
if (v.isValid())
- data.expression = v.toString();
+ params.expression = v.toString();
v = map.value(_("message"));
if (v.isValid())
- data.message = v.toString();
- if (data.isValid())
- appendBreakpoint(data);
+ params.message = v.toString();
+ if (params.isValid())
+ appendBreakpointInternal(params);
else
- qWarning("Not restoring invalid breakpoint: %s", qPrintable(data.toString()));
+ qWarning("Not restoring invalid breakpoint: %s", qPrintable(params.toString()));
}
- //qDebug() << "LOADED BREAKPOINTS" << this << list.size();
}
void BreakHandler::updateMarkers()
{
- Iterator it = m_storage.begin(), et = m_storage.end();
- for ( ; it != et; ++it)
- it->updateMarker(it.key());
-}
-
-QVariant BreakHandler::headerData(int section,
- Qt::Orientation orientation, int role) const
-{
- if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
- static QString headers[] = {
- tr("Number"), tr("Function"), tr("File"), tr("Line"),
- tr("Address"), tr("Condition"), tr("Ignore"), tr("Threads")
- };
- return headers[section];
- }
- return QVariant();
+ foreach (TreeItem *n, rootItem()->children())
+ static_cast<BreakpointItem *>(n)->updateMarker();
}
-BreakpointModelId BreakHandler::findBreakpointByIndex(const QModelIndex &index) const
+Breakpoint BreakHandler::findBreakpointByIndex(const QModelIndex &index) const
{
- //qDebug() << "FIND: " << index <<
- // BreakpointId::fromInternalId(index.internalId());
- return BreakpointModelId::fromInternalId(index.internalId());
+ TreeItem *item = itemFromIndex(index);
+ return Breakpoint(item && item->parent() == rootItem() ? static_cast<BreakpointItem *>(item) : 0);
}
-BreakpointModelIds BreakHandler::findBreakpointsByIndex(const QList<QModelIndex> &list) const
+Breakpoints BreakHandler::findBreakpointsByIndex(const QList<QModelIndex> &list) const
{
- QSet<BreakpointModelId> ids;
- foreach (const QModelIndex &index, list)
- ids.insert(findBreakpointByIndex(index));
+ QSet<Breakpoint> ids;
+ foreach (const QModelIndex &index, list) {
+ if (Breakpoint b = findBreakpointByIndex(index))
+ ids.insert(Breakpoint(b));
+ }
return ids.toList();
}
-Qt::ItemFlags BreakHandler::flags(const QModelIndex &index) const
-{
-// switch (index.column()) {
-// //case 0:
-// // return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
-// default:
- return QAbstractItemModel::flags(index);
-// }
-}
-
QString BreakHandler::displayFromThreadSpec(int spec)
{
return spec == -1 ? BreakHandler::tr("(all)") : QString::number(spec);
@@ -465,95 +559,12 @@ int BreakHandler::threadSpecFromDisplay(const QString &str)
return ok ? result : -1;
}
-QModelIndex BreakHandler::createIndex(int row, int column, quint32 id) const
-{
- return QAbstractItemModel::createIndex(row, column, id);
-}
-
-QModelIndex BreakHandler::createIndex(int row, int column, void *ptr) const
-{
- QTC_CHECK(false); // This function is not used.
- return QAbstractItemModel::createIndex(row, column, ptr);
-}
+const QString empty(QLatin1Char('-'));
-int BreakHandler::columnCount(const QModelIndex &idx) const
+QVariant BreakpointItem::data(int column, int role) const
{
- if (idx.column() > 0)
- return 0;
- const BreakpointModelId id = findBreakpointByIndex(idx);
- return id.isMinor() ? 0 : 8;
-}
-
-int BreakHandler::rowCount(const QModelIndex &idx) const
-{
- if (idx.column() > 0)
- return 0;
- if (!idx.isValid())
- return m_storage.size();
- const BreakpointModelId id = findBreakpointByIndex(idx);
- if (id.isMajor())
- return m_storage.value(id).subItems.size();
- return 0;
-}
-
-QModelIndex BreakHandler::index(int row, int col, const QModelIndex &parent) const
-{
- if (row < 0 || col < 0)
- return QModelIndex();
- if (parent.column() > 0)
- return QModelIndex();
- BreakpointModelId id = findBreakpointByIndex(parent);
- if (id.isMajor()) {
- ConstIterator it = m_storage.find(id);
- if (row >= it->subItems.size())
- return QModelIndex();
- BreakpointModelId sub = id.child(row);
- return createIndex(row, col, sub.toInternalId());
- }
- if (id.isMinor())
- return QModelIndex();
- QTC_ASSERT(!id.isValid(), return QModelIndex());
- if (row >= m_storage.size())
- return QModelIndex();
- id = at(row);
- return createIndex(row, col, id.toInternalId());
-}
-
-QModelIndex BreakHandler::parent(const QModelIndex &idx) const
-{
- if (!idx.isValid())
- return QModelIndex();
- BreakpointModelId id = findBreakpointByIndex(idx);
- if (id.isMajor())
- return QModelIndex();
- if (id.isMinor()) {
- BreakpointModelId pid = id.parent();
- int row = indexOf(pid);
- return createIndex(row, 0, pid.toInternalId());
- }
- return QModelIndex();
-}
-
-QVariant BreakHandler::data(const QModelIndex &mi, int role) const
-{
- static const QString empty = QString(QLatin1Char('-'));
-
- if (!mi.isValid())
- return QVariant();
-
- BreakpointModelId id = findBreakpointByIndex(mi);
-
- BreakpointModelId pid = id;
- if (id.isMinor())
- pid = id.parent();
-
- ConstIterator it = m_storage.find(pid);
- QTC_ASSERT(it != m_storage.end(), return QVariant());
- const BreakpointParameters &data = it->data;
- const BreakpointResponse &response = it->response;
-
bool orig = false;
- switch (it->state) {
+ switch (m_state) {
case BreakpointInsertRequested:
case BreakpointInsertProceeding:
case BreakpointChangeRequested:
@@ -568,53 +579,52 @@ QVariant BreakHandler::data(const QModelIndex &mi, int role) const
break;
};
- if (id.isMinor()) {
- QTC_ASSERT(id.minorPart() <= it->subItems.size(), return QVariant());
- const BreakpointResponse &res = it->subItems.at(id.minorPart() - 1);
- switch (mi.column()) {
- case 0:
- if (role == Qt::DisplayRole)
- return id.toString();
- case 1:
- if (role == Qt::DisplayRole)
- return res.functionName;
- case 4:
- if (role == Qt::DisplayRole)
- if (res.address)
- return QString::fromLatin1("0x%1").arg(res.address, 0, 16);
- }
- return QVariant();
+ if (role == Qt::ForegroundRole) {
+ static const QVariant gray(QColor(140, 140, 140));
+ switch (m_state) {
+ case BreakpointInsertRequested:
+ case BreakpointInsertProceeding:
+ case BreakpointChangeRequested:
+ case BreakpointChangeProceeding:
+ case BreakpointRemoveRequested:
+ case BreakpointRemoveProceeding:
+ return gray;
+ case BreakpointInserted:
+ case BreakpointNew:
+ case BreakpointDead:
+ break;
+ };
}
- switch (mi.column()) {
+ switch (column) {
case 0:
if (role == Qt::DisplayRole)
- return id.toString();
+ return m_id.toString();
if (role == Qt::DecorationRole)
- return it->icon();
+ return icon();
break;
case 1:
if (role == Qt::DisplayRole) {
- if (!response.functionName.isEmpty())
- return simplifyType(response.functionName);
- if (!data.functionName.isEmpty())
- return data.functionName;
- if (data.type == BreakpointAtMain
- || data.type == BreakpointAtThrow
- || data.type == BreakpointAtCatch
- || data.type == BreakpointAtFork
- || data.type == BreakpointAtExec
- //|| data.type == BreakpointAtVFork
- || data.type == BreakpointAtSysCall)
- return typeToString(data.type);
- if (data.type == WatchpointAtAddress) {
- quint64 address = response.address ? response.address : data.address;
- return tr("Data at 0x%1").arg(address, 0, 16);
+ if (!m_response.functionName.isEmpty())
+ return simplifyType(m_response.functionName);
+ if (!m_params.functionName.isEmpty())
+ return m_params.functionName;
+ if (m_params.type == BreakpointAtMain
+ || m_params.type == BreakpointAtThrow
+ || m_params.type == BreakpointAtCatch
+ || m_params.type == BreakpointAtFork
+ || m_params.type == BreakpointAtExec
+ //|| m_params.type == BreakpointAtVFork
+ || m_params.type == BreakpointAtSysCall)
+ return typeToString(m_params.type);
+ if (m_params.type == WatchpointAtAddress) {
+ quint64 address = m_response.address ? m_response.address : m_params.address;
+ return BreakHandler::tr("Data at 0x%1").arg(address, 0, 16);
}
- if (data.type == WatchpointAtExpression) {
- QString expression = !response.expression.isEmpty()
- ? response.expression : data.expression;
- return tr("Data at %1").arg(expression);
+ if (m_params.type == WatchpointAtExpression) {
+ QString expression = !m_response.expression.isEmpty()
+ ? m_response.expression : m_params.expression;
+ return BreakHandler::tr("Data at %1").arg(expression);
}
return empty;
}
@@ -622,17 +632,17 @@ QVariant BreakHandler::data(const QModelIndex &mi, int role) const
case 2:
if (role == Qt::DisplayRole) {
QString str;
- if (!response.fileName.isEmpty())
- str = response.fileName;
- if (str.isEmpty() && !data.fileName.isEmpty())
- str = data.fileName;
+ if (!m_response.fileName.isEmpty())
+ str = m_response.fileName;
+ if (str.isEmpty() && !m_params.fileName.isEmpty())
+ str = m_params.fileName;
if (str.isEmpty()) {
- QString s = QFileInfo(str).fileName();
+ QString s = FileName::fromString(str).fileName();
if (!s.isEmpty())
str = s;
}
// FIXME: better?
- //if (data.multiple && str.isEmpty() && !response.fileName.isEmpty())
+ //if (params.multiple && str.isEmpty() && !response.fileName.isEmpty())
// str = response.fileName;
if (!str.isEmpty())
return QDir::toNativeSeparators(str);
@@ -641,18 +651,18 @@ QVariant BreakHandler::data(const QModelIndex &mi, int role) const
break;
case 3:
if (role == Qt::DisplayRole) {
- if (response.lineNumber > 0)
- return response.lineNumber;
- if (data.lineNumber > 0)
- return data.lineNumber;
+ if (m_response.lineNumber > 0)
+ return m_response.lineNumber;
+ if (m_params.lineNumber > 0)
+ return m_params.lineNumber;
return empty;
}
if (role == Qt::UserRole + 1)
- return data.lineNumber;
+ return m_params.lineNumber;
break;
case 4:
if (role == Qt::DisplayRole) {
- const quint64 address = orig ? data.address : response.address;
+ const quint64 address = orig ? m_params.address : m_response.address;
if (address)
return QString::fromLatin1("0x%1").arg(address, 0, 16);
return QVariant();
@@ -660,196 +670,204 @@ QVariant BreakHandler::data(const QModelIndex &mi, int role) const
break;
case 5:
if (role == Qt::DisplayRole)
- return orig ? data.condition : response.condition;
+ return orig ? m_params.condition : m_response.condition;
if (role == Qt::ToolTipRole)
- return tr("Breakpoint will only be hit if this condition is met.");
+ return BreakHandler::tr("Breakpoint will only be hit if this condition is met.");
if (role == Qt::UserRole + 1)
- return data.condition;
+ return m_params.condition;
break;
case 6:
if (role == Qt::DisplayRole) {
const int ignoreCount =
- orig ? data.ignoreCount : response.ignoreCount;
+ orig ? m_params.ignoreCount : m_response.ignoreCount;
return ignoreCount ? QVariant(ignoreCount) : QVariant(QString());
}
if (role == Qt::ToolTipRole)
- return tr("Breakpoint will only be hit after being ignored so many times.");
+ return BreakHandler::tr("Breakpoint will only be hit after being ignored so many times.");
if (role == Qt::UserRole + 1)
- return data.ignoreCount;
+ return m_params.ignoreCount;
break;
case 7:
if (role == Qt::DisplayRole)
- return displayFromThreadSpec(orig ? data.threadSpec : response.threadSpec);
+ return BreakHandler::displayFromThreadSpec(orig ? m_params.threadSpec : m_response.threadSpec);
if (role == Qt::ToolTipRole)
- return tr("Breakpoint will only be hit in the specified thread(s).");
+ return BreakHandler::tr("Breakpoint will only be hit in the specified thread(s).");
if (role == Qt::UserRole + 1)
- return displayFromThreadSpec(data.threadSpec);
+ return BreakHandler::displayFromThreadSpec(m_params.threadSpec);
break;
}
- switch (role) {
- case Qt::ToolTipRole:
- if (boolSetting(UseToolTipsInBreakpointsView))
- return QVariant(it->toToolTip());
- break;
- }
+
+ if (role == Qt::ToolTipRole && boolSetting(UseToolTipsInBreakpointsView))
+ return toToolTip();
+
return QVariant();
}
-#define GETTER(type, getter) \
-type BreakHandler::getter(BreakpointModelId id) const \
+#define PROPERTY(type, getter, setter) \
+\
+type Breakpoint::getter() const \
{ \
- ConstIterator it = m_storage.find(id); \
- BREAK_ASSERT(it != m_storage.end(), \
- qDebug() << "ID" << id << "NOT KNOWN"; \
- return type()); \
- return it->data.getter; \
-}
-
-#define SETTER(type, getter, setter) \
-void BreakHandler::setter(BreakpointModelId id, const type &value) \
+ return parameters().getter; \
+} \
+\
+void Breakpoint::setter(const type &value) \
{ \
- Iterator it = m_storage.find(id); \
- BREAK_ASSERT(it != m_storage.end(), \
- qDebug() << "ID" << id << "NOT KNOWN"; return); \
- if (it->data.getter == value) \
+ QTC_ASSERT(b, return); \
+ if (b->m_params.getter == value) \
return; \
- it->data.getter = value; \
- if (it->state != BreakpointNew) { \
- it->state = BreakpointChangeRequested; \
- scheduleSynchronization(); \
+ b->m_params.getter = value; \
+ if (b->m_state != BreakpointNew) { \
+ b->m_state = BreakpointChangeRequested; \
+ b->scheduleSynchronization(); \
} \
}
-#define PROPERTY(type, getter, setter) \
- GETTER(type, getter) \
- SETTER(type, getter, setter)
-
-
PROPERTY(BreakpointPathUsage, pathUsage, setPathUsage)
PROPERTY(QString, fileName, setFileName)
PROPERTY(QString, functionName, setFunctionName)
PROPERTY(BreakpointType, type, setType)
PROPERTY(int, threadSpec, setThreadSpec)
PROPERTY(QByteArray, condition, setCondition)
-GETTER(int, lineNumber)
PROPERTY(quint64, address, setAddress)
PROPERTY(QString, expression, setExpression)
PROPERTY(QString, message, setMessage)
PROPERTY(int, ignoreCount, setIgnoreCount)
-bool BreakHandler::isEnabled(BreakpointModelId id) const
+void BreakpointItem::scheduleSynchronization()
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return false);
- return it->data.enabled;
+ m_handler->scheduleSynchronization();
}
-void BreakHandler::setEnabled(BreakpointModelId id, bool on)
+const BreakpointParameters &Breakpoint::parameters() const
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- //qDebug() << "SET ENABLED: " << id << it->data.isEnabled() << on;
- if (it->data.enabled == on)
- return;
- it->data.enabled = on;
- it->updateMarkerIcon();
- if (it->engine) {
- it->state = BreakpointChangeRequested;
- scheduleSynchronization();
- }
+ static BreakpointParameters p;
+ QTC_ASSERT(b, return p);
+ return b->m_params;
+}
+
+void Breakpoint::addToCommand(DebuggerCommand *cmd) const
+{
+ cmd->arg("modelid", id().toByteArray());
+ cmd->arg("type", type());
+ cmd->arg("ignorecount", ignoreCount());
+ cmd->arg("condition", condition().toHex());
+ cmd->arg("function", functionName().toUtf8());
+ cmd->arg("oneshot", isOneShot());
+ cmd->arg("enabled", isEnabled());
+ cmd->arg("fileName", fileName().toUtf8());
+ cmd->arg("lineNumber", lineNumber());
+ cmd->arg("address", address());
+ cmd->arg("expression", expression());
+}
+
+BreakpointState Breakpoint::state() const
+{
+ QTC_ASSERT(b, return BreakpointState());
+ return b->m_state;
}
-bool BreakHandler::isWatchpoint(BreakpointModelId id) const
+int Breakpoint::lineNumber() const { return parameters().lineNumber; }
+
+bool Breakpoint::isEnabled() const { return parameters().enabled; }
+
+bool Breakpoint::isWatchpoint() const { return parameters().isWatchpoint(); }
+
+bool Breakpoint::isTracepoint() const { return parameters().isTracepoint(); }
+
+QIcon Breakpoint::icon() const { return b ? b->icon() : QIcon(); }
+
+DebuggerEngine *Breakpoint::engine() const
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return false);
- return it->data.isWatchpoint();
+ return b ? b->m_engine : 0;
}
-bool BreakHandler::isTracepoint(BreakpointModelId id) const
+const BreakpointResponse &Breakpoint::response() const
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return false);
- return it->data.tracepoint;
+ static BreakpointResponse r;
+ return b ? b->m_response : r;
}
-bool BreakHandler::isOneShot(BreakpointModelId id) const
+bool Breakpoint::isOneShot() const { return parameters().oneShot; }
+
+void Breakpoint::removeAlienBreakpoint()
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return false);
- return it->data.oneShot;
+ b->deleteThis();
}
-bool BreakHandler::needsChildren(BreakpointModelId id) const
+void Breakpoint::removeBreakpoint() const
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return false);
- return it->response.multiple && it->subItems.isEmpty();
+ b->removeBreakpoint();
}
-void BreakHandler::setTracepoint(BreakpointModelId id, bool on)
+Breakpoint::Breakpoint(BreakpointItem *b)
+ : b(b)
+{}
+
+void Breakpoint::setEnabled(bool on) const
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- if (it->data.tracepoint == on)
+ QTC_ASSERT(b, return);
+ if (b->m_params.enabled == on)
return;
- it->data.tracepoint = on;
- it->updateMarkerIcon();
-
- if (it->engine) {
- it->state = BreakpointChangeRequested;
- scheduleSynchronization();
+ b->m_params.enabled = on;
+ b->updateMarkerIcon();
+ if (b->m_engine) {
+ b->m_state = BreakpointChangeRequested;
+ b->scheduleSynchronization();
}
}
-void BreakHandler::setMarkerFileAndLine(BreakpointModelId id,
- const QString &fileName, int lineNumber)
+void Breakpoint::setMarkerFileAndLine(const QString &fileName, int lineNumber)
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(),
- qDebug() << "MARKER_FILE_AND_LINE: " << id; return);
- if (it->response.fileName == fileName && it->response.lineNumber == lineNumber)
- return;
- it->response.fileName = fileName;
- it->response.lineNumber = lineNumber;
- it->destroyMarker();
- it->updateMarker(id);
- emit layoutChanged();
+ if (b)
+ b->setMarkerFileAndLine(fileName, lineNumber);
}
-BreakpointState BreakHandler::state(BreakpointModelId id) const
+bool BreakpointItem::needsChildren() const
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(),
- qDebug() << "STATE: " << id; return BreakpointDead);
- return it->state;
+ return m_response.multiple && rowCount() == 0;
}
-DebuggerEngine *BreakHandler::engine(BreakpointModelId id) const
+void Breakpoint::setTracepoint(bool on)
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), qDebug() << id; return 0);
- return it->engine;
+ if (b->m_params.tracepoint == on)
+ return;
+ b->m_params.tracepoint = on;
+ b->updateMarkerIcon();
+
+ if (b->m_engine) {
+ b->m_state = BreakpointChangeRequested;
+ b->scheduleSynchronization();
+ }
}
-void BreakHandler::setEngine(BreakpointModelId id, DebuggerEngine *value)
+void BreakpointItem::setMarkerFileAndLine(const QString &fileName, int lineNumber)
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), qDebug() << "SET ENGINE" << id; return);
- QTC_ASSERT(it->state == BreakpointNew, qDebug() << "STATE: " << it->state <<id);
- QTC_ASSERT(!it->engine, qDebug() << "NO ENGINE" << id; return);
- it->engine = value;
- it->state = BreakpointInsertRequested;
- it->response = BreakpointResponse();
- it->updateMarker(id);
- scheduleSynchronization();
+ if (m_response.fileName == fileName && m_response.lineNumber == lineNumber)
+ return;
+ m_response.fileName = fileName;
+ m_response.lineNumber = lineNumber;
+ destroyMarker();
+ updateMarker();
+ update();
+}
+
+void Breakpoint::setEngine(DebuggerEngine *value)
+{
+ QTC_ASSERT(b->m_state == BreakpointNew, qDebug() << "STATE: " << b->m_state << b->m_id);
+ QTC_ASSERT(!b->m_engine, qDebug() << "NO ENGINE" << b->m_id; return);
+ b->m_engine = value;
+ b->m_state = BreakpointInsertRequested;
+ b->m_response = BreakpointResponse();
+ b->updateMarker();
+ //b->scheduleSynchronization();
}
static bool isAllowedTransition(BreakpointState from, BreakpointState to)
{
switch (from) {
case BreakpointNew:
- return to == BreakpointInsertRequested;
+ return to == BreakpointInsertRequested
+ || to == BreakpointDead;
case BreakpointInsertRequested:
return to == BreakpointInsertProceeding;
case BreakpointInsertProceeding:
@@ -876,287 +894,234 @@ static bool isAllowedTransition(BreakpointState from, BreakpointState to)
return false;
}
-bool BreakHandler::isEngineRunning(BreakpointModelId id) const
+bool BreakpointItem::isEngineRunning() const
{
- if (const DebuggerEngine *e = engine(id)) {
- const DebuggerState state = e->state();
- return state != DebuggerFinished && state != DebuggerNotReady;
- }
- return false;
+ if (!m_engine)
+ return false;
+ const DebuggerState state = m_engine->state();
+ return state != DebuggerFinished && state != DebuggerNotReady;
}
-void BreakHandler::setState(BreakpointModelId id, BreakpointState state)
+void BreakpointItem::setState(BreakpointState state)
{
- Iterator it = m_storage.find(id);
- //qDebug() << "BREAKPOINT STATE TRANSITION, ID: " << id
- // << " FROM: " << it->state << " TO: " << state;
- BREAK_ASSERT(it != m_storage.end(), qDebug() << id; return);
- QTC_ASSERT(isAllowedTransition(it->state, state),
- qDebug() << "UNEXPECTED BREAKPOINT STATE TRANSITION"
- << it->state << state);
+ //qDebug() << "BREAKPOINT STATE TRANSITION, ID: " << m_id
+ // << " FROM: " << state << " TO: " << state;
+ if (!isAllowedTransition(m_state, state)) {
+ qDebug() << "UNEXPECTED BREAKPOINT STATE TRANSITION" << m_state << state;
+ QTC_CHECK(false);
+ }
- if (it->state == state) {
- qDebug() << "STATE UNCHANGED: " << id << state;
+ if (m_state == state) {
+ qDebug() << "STATE UNCHANGED: " << m_id << m_state;
return;
}
- it->state = state;
+ m_state = state;
// FIXME: updateMarker() should recognize the need for icon changes.
if (state == BreakpointInserted) {
- it->destroyMarker();
- it->updateMarker(id);
+ destroyMarker();
+ updateMarker();
}
- layoutChanged();
+ update();
+}
+
+void BreakpointItem::deleteThis()
+{
+ setState(BreakpointDead);
+ destroyMarker();
+
+ // This is called from b directly. So delay deletion of b.
+ ExtensionSystem::InvokerBase invoker;
+ invoker.addArgument(m_id);
+ invoker.setConnectionType(Qt::QueuedConnection);
+ invoker.invoke(m_handler, "deletionHelper");
+ QTC_CHECK(invoker.wasSuccessful());
}
-void BreakHandler::notifyBreakpointChangeAfterInsertNeeded(BreakpointModelId id)
+void Breakpoint::gotoState(BreakpointState target, BreakpointState assumedCurrent)
{
- QTC_ASSERT(state(id) == BreakpointInsertProceeding, qDebug() << state(id));
- setState(id, BreakpointChangeRequested);
+ QTC_ASSERT(b, return);
+ QTC_ASSERT(b->m_state == assumedCurrent, qDebug() << b->m_state);
+ b->setState(target);
}
-void BreakHandler::notifyBreakpointInsertProceeding(BreakpointModelId id)
+void Breakpoint::notifyBreakpointChangeAfterInsertNeeded()
{
- QTC_ASSERT(state(id) == BreakpointInsertRequested, qDebug() << state(id));
- setState(id, BreakpointInsertProceeding);
+ gotoState(BreakpointChangeRequested, BreakpointInsertProceeding);
}
-void BreakHandler::notifyBreakpointInsertOk(BreakpointModelId id)
+void Breakpoint::notifyBreakpointInsertProceeding()
{
- QTC_ASSERT(state(id) == BreakpointInsertProceeding, qDebug() << state(id));
- setState(id, BreakpointInserted);
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
+ gotoState(BreakpointInsertProceeding, BreakpointInsertRequested);
}
-void BreakHandler::notifyBreakpointInsertFailed(BreakpointModelId id)
+void Breakpoint::notifyBreakpointInsertOk()
{
- QTC_ASSERT(state(id) == BreakpointInsertProceeding, qDebug() << state(id));
- setState(id, BreakpointDead);
+ gotoState(BreakpointInserted, BreakpointInsertProceeding);
}
-void BreakHandler::notifyBreakpointRemoveProceeding(BreakpointModelId id)
+void Breakpoint::notifyBreakpointInsertFailed()
{
- QTC_ASSERT(state(id) == BreakpointRemoveRequested, qDebug() << state(id));
- setState(id, BreakpointRemoveProceeding);
+ gotoState(BreakpointDead, BreakpointInsertProceeding);
}
-void BreakHandler::notifyBreakpointRemoveOk(BreakpointModelId id)
+void Breakpoint::notifyBreakpointRemoveProceeding()
{
- QTC_ASSERT(state(id) == BreakpointRemoveProceeding, qDebug() << state(id));
- setState(id, BreakpointDead);
- cleanupBreakpoint(id);
+ gotoState(BreakpointRemoveProceeding, BreakpointRemoveRequested);
}
-void BreakHandler::notifyBreakpointRemoveFailed(BreakpointModelId id)
+void Breakpoint::notifyBreakpointRemoveOk()
{
- QTC_ASSERT(state(id) == BreakpointRemoveProceeding, qDebug() << state(id));
- setState(id, BreakpointDead);
- cleanupBreakpoint(id);
+ QTC_ASSERT(b, return);
+ QTC_ASSERT(b->m_state == BreakpointRemoveProceeding, qDebug() << b->m_state);
+ b->deleteThis();
}
-void BreakHandler::notifyBreakpointChangeProceeding(BreakpointModelId id)
+void Breakpoint::notifyBreakpointRemoveFailed()
{
- QTC_ASSERT(state(id) == BreakpointChangeRequested, qDebug() << state(id));
- setState(id, BreakpointChangeProceeding);
+ QTC_ASSERT(b, return);
+ QTC_ASSERT(b->m_state == BreakpointRemoveProceeding, qDebug() << b->m_state);
+ b->deleteThis();
}
-void BreakHandler::notifyBreakpointChangeOk(BreakpointModelId id)
+void Breakpoint::notifyBreakpointChangeProceeding()
{
- QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
- setState(id, BreakpointInserted);
+ gotoState(BreakpointChangeProceeding, BreakpointChangeRequested);
}
-void BreakHandler::notifyBreakpointChangeFailed(BreakpointModelId id)
+void Breakpoint::notifyBreakpointChangeOk()
{
- QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
- setState(id, BreakpointDead);
+ gotoState(BreakpointInserted, BreakpointChangeProceeding);
}
-void BreakHandler::notifyBreakpointReleased(BreakpointModelId id)
+void Breakpoint::notifyBreakpointChangeFailed()
{
- //QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- it->state = BreakpointNew;
- it->engine = 0;
- it->response = BreakpointResponse();
- it->subItems.clear();
- it->destroyMarker();
- it->updateMarker(id);
- if (it->data.type == WatchpointAtAddress
- || it->data.type == WatchpointAtExpression
- || it->data.type == BreakpointByAddress)
- it->data.enabled = false;
- else
- it->data.address = 0;
- layoutChanged();
+ gotoState(BreakpointDead, BreakpointChangeProceeding);
}
-void BreakHandler::notifyBreakpointAdjusted(BreakpointModelId id,
- const BreakpointParameters &data)
+void Breakpoint::notifyBreakpointReleased()
{
- QTC_ASSERT(state(id) == BreakpointInserted, qDebug() << state(id));
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- it->data = data;
- //if (it->needsChange())
- // setState(id, BreakpointChangeRequested);
+ QTC_ASSERT(b, return);
+ b->removeChildren();
+ //QTC_ASSERT(b->m_state == BreakpointChangeProceeding, qDebug() << b->m_state);
+ b->m_state = BreakpointNew;
+ b->m_engine = 0;
+ b->m_response = BreakpointResponse();
+ b->destroyMarker();
+ b->updateMarker();
+ if (b->m_params.type == WatchpointAtAddress
+ || b->m_params.type == WatchpointAtExpression
+ || b->m_params.type == BreakpointByAddress)
+ b->m_params.enabled = false;
+ else
+ b->m_params.address = 0;
+ b->update();
}
-void BreakHandler::notifyBreakpointNeedsReinsertion(BreakpointModelId id)
+void Breakpoint::notifyBreakpointAdjusted(const BreakpointParameters &params)
{
- QTC_ASSERT(state(id) == BreakpointChangeProceeding, qDebug() << state(id));
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- it->state = BreakpointInsertRequested;
+ QTC_ASSERT(b, return);
+ QTC_ASSERT(b->m_state == BreakpointInserted, qDebug() << b->m_state);
+ b->m_params = params;
+ //if (b->needsChange())
+ // b->setState(BreakpointChangeRequested);
}
-void BreakHandler::removeAlienBreakpoint(BreakpointModelId id)
+void Breakpoint::notifyBreakpointNeedsReinsertion()
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- it->state = BreakpointDead;
- cleanupBreakpoint(id);
+ QTC_ASSERT(b, return);
+ QTC_ASSERT(b->m_state == BreakpointChangeProceeding, qDebug() << b->m_state);
+ b->m_state = BreakpointInsertRequested;
}
-void BreakHandler::removeBreakpoint(BreakpointModelId id)
+void BreakpointItem::removeBreakpoint()
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- switch (it->state) {
+ switch (m_state) {
case BreakpointRemoveRequested:
break;
case BreakpointInserted:
case BreakpointInsertProceeding:
- setState(id, BreakpointRemoveRequested);
+ setState(BreakpointRemoveRequested);
scheduleSynchronization();
break;
case BreakpointNew:
- it->state = BreakpointDead;
- cleanupBreakpoint(id);
+ deleteThis();
break;
default:
qWarning("Warning: Cannot remove breakpoint %s in state '%s'.",
- qPrintable(id.toString()), qPrintable(stateToString(it->state)));
- it->state = BreakpointRemoveRequested;
+ qPrintable(m_id.toString()), qPrintable(stateToString(m_state)));
+ m_state = BreakpointRemoveRequested;
break;
}
}
-// Ok to be not thread-safe. The order does not matter and only the gui
-// produces authoritative ids.
-static int currentId = 0;
+void BreakHandler::appendBreakpoint(const BreakpointParameters &params)
+{
+ appendBreakpointInternal(params);
+ scheduleSynchronization();
+}
-void BreakHandler::appendBreakpoint(const BreakpointParameters &data)
+void BreakHandler::appendBreakpointInternal(const BreakpointParameters &params)
{
- if (!data.isValid()) {
- qWarning("Not adding invalid breakpoint: %s", qPrintable(data.toString()));
+ if (!params.isValid()) {
+ qWarning("Not adding invalid breakpoint: %s", qPrintable(params.toString()));
return;
}
- BreakpointModelId id(++currentId);
- const int row = m_storage.size();
- beginInsertRows(QModelIndex(), row, row);
- Iterator it = m_storage.insert(id, BreakpointItem());
- endInsertRows();
-
- // Create marker after copy is inserted into hash.
- it->data = data;
- it->updateMarker(id);
-
- scheduleSynchronization();
+ BreakpointItem *b = new BreakpointItem(this);
+ b->m_params = params;
+ b->updateMarker();
+ rootItem()->appendChild(b);
}
void BreakHandler::handleAlienBreakpoint(const BreakpointResponse &response, DebuggerEngine *engine)
{
- BreakpointModelId id = findSimilarBreakpoint(response);
- if (id.isValid()) {
+ Breakpoint b = findSimilarBreakpoint(response);
+ if (b) {
if (response.id.isMinor())
- insertSubBreakpoint(id, response);
+ b.insertSubBreakpoint(response);
else
- setResponse(id, response);
+ b.setResponse(response);
} else {
- id = BreakpointModelId(++currentId);
- const int row = m_storage.size();
-
- beginInsertRows(QModelIndex(), row, row);
- Iterator it = m_storage.insert(id, BreakpointItem());
- endInsertRows();
-
- it->data = response;
- it->response = response;
- it->state = BreakpointInserted;
- it->engine = engine;
- it->updateMarker(id);
-
- layoutChanged();
- scheduleSynchronization();
+ auto b = new BreakpointItem(this);
+ b->m_params = response;
+ b->m_response = response;
+ b->m_state = BreakpointInserted;
+ b->m_engine = engine;
+ b->updateMarker();
+ rootItem()->appendChild(b);
}
}
-BreakpointModelId BreakHandler::at(int n) const
+void Breakpoint::insertSubBreakpoint(const BreakpointResponse &params)
{
- if (n < 0 || n >= m_storage.size())
- return BreakpointModelId();
- ConstIterator it = m_storage.constBegin();
- for ( ; --n >= 0; ++it)
- ;
- return it.key();
+ QTC_ASSERT(b, return);
+ b->insertSubBreakpoint(params);
}
-int BreakHandler::indexOf(BreakpointModelId id) const
+void BreakpointItem::insertSubBreakpoint(const BreakpointResponse &params)
{
- int row = 0;
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it, ++row)
- if (it.key() == id)
- return row;
- return -1;
-}
+ QTC_ASSERT(params.id.isMinor(), return);
-void BreakHandler::insertSubBreakpoint(BreakpointModelId id,
- const BreakpointResponse &data)
-{
- QTC_ASSERT(data.id.isMinor(), return);
- QTC_ASSERT(id.isMajor(), return);
- Iterator it = m_storage.find(id);
+ int minorPart = params.id.minorPart();
- if (it == m_storage.end()) {
- qDebug() << "FAILED: " << id.toString();
- for (ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- it != et; ++it) {
- qDebug() << " ID: " << it->response.id.toString();
- qDebug() << " DATA: " << it->data.toString();
- qDebug() << " RESP: " << it->response.toString();
+ const QVector<TreeItem *> &children = TreeItem::children();
+ foreach (TreeItem *n, children) {
+ LocationItem *l = static_cast<LocationItem *>(n);
+ if (l->params.id.minorPart() == minorPart) {
+ // This modifies an existing sub-breakpoint.
+ l->params = params;
+ l->update();
+ return;
}
}
- QTC_ASSERT(it != m_storage.end(), return);
- int minorPart = data.id.minorPart();
- int pos = -1;
- for (int i = 0; i != it->subItems.size(); ++i) {
- if (it->subItems.at(i).id.minorPart() == minorPart) {
- pos = i;
- break;
- }
- }
- if (pos == -1) {
- // This is a new sub-breakpoint.
- //qDebug() << "NEW ID" << id;
- int row = indexOf(id);
- QTC_ASSERT(row != -1, return);
- QModelIndex idx = createIndex(row, 0, id.toInternalId());
- beginInsertRows(idx, it->subItems.size(), it->subItems.size());
- it->subItems.append(data);
- endInsertRows();
- } else {
- // This modifies an existing sub-breakpoint.
- //qDebug() << "EXISTING ID" << id;
- it->subItems[pos] = data;
- layoutChanged();
- }
+ // This is a new sub-breakpoint.
+ LocationItem *l = new LocationItem;
+ l->params = params;
+ appendChild(l);
+ expand();
}
void BreakHandler::saveSessionData()
@@ -1166,12 +1131,7 @@ void BreakHandler::saveSessionData()
void BreakHandler::loadSessionData()
{
- beginResetModel();
- Iterator it = m_storage.begin(), et = m_storage.end();
- for ( ; it != et; ++it)
- it->destroyMarker();
- m_storage.clear();
- endResetModel();
+ removeItems();
loadBreakpoints();
}
@@ -1179,25 +1139,17 @@ void BreakHandler::breakByFunction(const QString &functionName)
{
// One breakpoint per function is enough for now. This does not handle
// combinations of multiple conditions and ignore counts, though.
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it) {
- const BreakpointParameters &data = it->data;
- if (data.functionName == functionName
- && data.condition.isEmpty()
- && data.ignoreCount == 0)
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ const BreakpointParameters &params = b->m_params;
+ if (params.functionName == functionName
+ && params.condition.isEmpty()
+ && params.ignoreCount == 0)
return;
}
- BreakpointParameters data(BreakpointByFunction);
- data.functionName = functionName;
- appendBreakpoint(data);
-}
-
-QIcon BreakHandler::icon(BreakpointModelId id) const
-{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), qDebug() << "NO ICON FOR ID" << id;
- return pendingBreakpointIcon());
- return it->icon();
+ BreakpointParameters params(BreakpointByFunction);
+ params.functionName = functionName;
+ appendBreakpoint(params);
}
void BreakHandler::scheduleSynchronization()
@@ -1215,158 +1167,127 @@ void BreakHandler::timerEvent(QTimerEvent *event)
Internal::synchronizeBreakpoints();
}
-void BreakHandler::gotoLocation(BreakpointModelId id) const
+void Breakpoint::gotoLocation() const
{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- DebuggerEngine *engine = currentEngine();
- if (it->data.type == BreakpointByAddress) {
- if (engine)
- engine->gotoLocation(it->data.address);
- } else {
- if (engine)
- engine->gotoLocation(
- Location(it->markerFileName(), it->markerLineNumber(), false));
+ if (DebuggerEngine *engine = currentEngine()) {
+ if (b->m_params.type == BreakpointByAddress)
+ engine->gotoLocation(b->m_params.address);
+ else
+ engine->gotoLocation(Location(b->markerFileName(), b->markerLineNumber(), false));
}
}
-void BreakHandler::updateFileNameFromMarker(BreakpointModelId id, const QString &fileName)
+void BreakpointItem::updateFileNameFromMarker(const QString &fileName)
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- it->data.fileName = fileName;
- emit layoutChanged();
+ m_params.fileName = fileName;
+ update();
}
-void BreakHandler::updateLineNumberFromMarker(BreakpointModelId id, int lineNumber)
+void BreakpointItem::updateLineNumberFromMarker(int lineNumber)
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
// Ignore updates to the "real" line number while the debugger is
// running, as this can be triggered by moving the breakpoint to
// the next line that generated code.
- if (it->data.lineNumber == lineNumber)
+ if (m_params.lineNumber == lineNumber)
; // Nothing
- else if (isEngineRunning(id))
- it->data.lineNumber += lineNumber - it->response.lineNumber;
+ else if (isEngineRunning())
+ m_params.lineNumber += lineNumber - m_response.lineNumber;
else
- it->data.lineNumber = lineNumber;
- it->updateMarker(id);
- emit layoutChanged();
+ m_params.lineNumber = lineNumber;
+ updateMarker();
+ update();
}
-void BreakHandler::changeLineNumberFromMarker(BreakpointModelId id, int lineNumber)
+void BreakpointItem::changeLineNumberFromMarker(int lineNumber)
{
+ m_params.lineNumber = lineNumber;
+
// We need to delay this as it is called from a marker which will be destroyed.
ExtensionSystem::InvokerBase invoker;
- invoker.addArgument(id);
- invoker.addArgument(lineNumber);
+ invoker.addArgument(m_id);
invoker.setConnectionType(Qt::QueuedConnection);
- invoker.invoke(this, "changeLineNumberFromMarkerHelper");
+ invoker.invoke(m_handler, "changeLineNumberFromMarkerHelper");
QTC_CHECK(invoker.wasSuccessful());
}
-void BreakHandler::changeLineNumberFromMarkerHelper(BreakpointModelId id, int lineNumber)
+void BreakHandler::changeLineNumberFromMarkerHelper(BreakpointModelId id)
{
- BreakpointParameters data = breakpointData(id);
- data.lineNumber = lineNumber;
- removeBreakpoint(id);
- appendBreakpoint(data);
+ Breakpoint b = breakpointById(id);
+ QTC_ASSERT(b, return);
+ BreakpointParameters params = b.parameters();
+ removeItem(b.b);
+ delete b.b;
+ appendBreakpoint(params);
}
-BreakpointModelIds BreakHandler::allBreakpointIds() const
+Breakpoints BreakHandler::allBreakpoints() const
{
- BreakpointModelIds ids;
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it)
- ids.append(it.key());
- return ids;
+ Breakpoints items;
+ foreach (TreeItem *n, rootItem()->children())
+ items.append(Breakpoint(static_cast<BreakpointItem *>(n)));
+ return items;
}
-BreakpointModelIds BreakHandler::unclaimedBreakpointIds() const
+Breakpoints BreakHandler::unclaimedBreakpoints() const
{
- return engineBreakpointIds(0);
+ return engineBreakpoints(0);
}
-BreakpointModelIds BreakHandler::engineBreakpointIds(DebuggerEngine *engine) const
+Breakpoints BreakHandler::engineBreakpoints(DebuggerEngine *engine) const
{
- BreakpointModelIds ids;
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it)
- if (it->engine == engine)
- ids.append(it.key());
- return ids;
+ Breakpoints items;
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->m_engine == engine)
+ items.append(Breakpoint(b));
+ }
+ return items;
}
QStringList BreakHandler::engineBreakpointPaths(DebuggerEngine *engine) const
{
QSet<QString> set;
- ConstIterator it = m_storage.constBegin(), et = m_storage.constEnd();
- for ( ; it != et; ++it) {
- if (it->engine == engine) {
- if (it->data.type == BreakpointByFileAndLine)
- set.insert(QFileInfo(it->data.fileName).dir().path());
+ foreach (TreeItem *n, rootItem()->children()) {
+ BreakpointItem *b = static_cast<BreakpointItem *>(n);
+ if (b->m_engine == engine) {
+ if (b->m_params.type == BreakpointByFileAndLine)
+ set.insert(QFileInfo(b->m_params.fileName).dir().path());
}
}
return set.toList();
}
-void BreakHandler::cleanupBreakpoint(BreakpointModelId id)
+void Breakpoint::setResponse(const BreakpointResponse &response)
{
- QTC_ASSERT(state(id) == BreakpointDead, qDebug() << state(id));
- BreakpointItem item = m_storage.take(id);
- item.destroyMarker();
- layoutChanged();
-}
-
-const BreakpointResponse &BreakHandler::response(BreakpointModelId id) const
-{
- static BreakpointResponse dummy;
- ConstIterator it = m_storage.find(id);
- if (it == m_storage.end()) {
- qDebug() << "NO RESPONSE FOR " << id;
- return dummy;
- }
- return it->response;
-}
-
-bool BreakHandler::needsChange(BreakpointModelId id) const
-{
- ConstIterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return false);
- return it->needsChange();
+ QTC_ASSERT(b, return);
+ b->m_response = response;
+ b->destroyMarker();
+ b->updateMarker();
+ // Take over corrected values from response.
+ if ((b->m_params.type == BreakpointByFileAndLine
+ || b->m_params.type == BreakpointByFunction)
+ && !response.module.isEmpty())
+ b->m_params.module = response.module;
}
-void BreakHandler::setResponse(BreakpointModelId id,
- const BreakpointResponse &response)
+bool Internal::Breakpoint::needsChange() const
{
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- it->response = response;
- it->destroyMarker();
- it->updateMarker(id);
- // Take over corrected values from response.
- if ((it->data.type == BreakpointByFileAndLine
- || it->data.type == BreakpointByFunction)
- && !response.module.isEmpty())
- it->data.module = response.module;
+ return b && b->needsChange();
}
-void BreakHandler::changeBreakpointData(BreakpointModelId id,
- const BreakpointParameters &data, BreakpointParts parts)
+void Breakpoint::changeBreakpointData(const BreakpointParameters &params)
{
- Q_UNUSED(parts);
- Iterator it = m_storage.find(id);
- BREAK_ASSERT(it != m_storage.end(), return);
- if (data == it->data)
+ if (!b)
return;
- it->data = data;
- it->destroyMarker();
- it->updateMarker(id);
- layoutChanged();
- if (it->needsChange() && it->engine && it->state != BreakpointNew) {
- setState(id, BreakpointChangeRequested);
- scheduleSynchronization();
+ if (params == b->m_params)
+ return;
+ b->m_params = params;
+ b->destroyMarker();
+ b->updateMarker();
+ b->update();
+ if (b->needsChange() && b->m_engine && b->m_state != BreakpointNew) {
+ b->setState(BreakpointChangeRequested);
+ b->m_handler->scheduleSynchronization();
}
}
@@ -1376,42 +1297,52 @@ void BreakHandler::changeBreakpointData(BreakpointModelId id,
//
//////////////////////////////////////////////////////////////////
-BreakHandler::BreakpointItem::BreakpointItem()
- : state(BreakpointNew), engine(0), marker(0)
+// Ok to be not thread-safe. The order does not matter and only the gui
+// produces authoritative ids.
+static int currentId = 0;
+
+BreakpointItem::BreakpointItem(BreakHandler *handler)
+ : m_handler(handler), m_id(++currentId), m_state(BreakpointNew), m_engine(0), m_marker(0)
{}
-void BreakHandler::BreakpointItem::destroyMarker()
+BreakpointItem::~BreakpointItem()
+{
+ delete m_marker;
+}
+
+void BreakpointItem::destroyMarker()
{
- BreakpointMarker *m = marker;
- marker = 0;
+ BreakpointMarker *m = m_marker;
+ QTC_ASSERT(m, return);
+ m->m_bp = 0;
+ m_marker = 0;
delete m;
}
-QString BreakHandler::BreakpointItem::markerFileName() const
+QString BreakpointItem::markerFileName() const
{
// Some heuristics to find a "good" file name.
- if (!data.fileName.isEmpty()) {
- QFileInfo fi(data.fileName);
+ if (!m_params.fileName.isEmpty()) {
+ QFileInfo fi(m_params.fileName);
if (fi.exists())
return fi.absoluteFilePath();
}
- if (!response.fileName.isEmpty()) {
- QFileInfo fi(response.fileName);
+ if (!m_response.fileName.isEmpty()) {
+ QFileInfo fi(m_response.fileName);
if (fi.exists())
return fi.absoluteFilePath();
}
- if (response.fileName.endsWith(data.fileName))
- return response.fileName;
- if (data.fileName.endsWith(response.fileName))
- return data.fileName;
- return response.fileName.size() > data.fileName.size()
- ? response.fileName : data.fileName;
+ if (m_response.fileName.endsWith(m_params.fileName))
+ return m_response.fileName;
+ if (m_params.fileName.endsWith(m_response.fileName))
+ return m_params.fileName;
+ return m_response.fileName.size() > m_params.fileName.size()
+ ? m_response.fileName : m_params.fileName;
}
-
-int BreakHandler::BreakpointItem::markerLineNumber() const
+int BreakpointItem::markerLineNumber() const
{
- return response.lineNumber ? response.lineNumber : data.lineNumber;
+ return m_response.lineNumber ? m_response.lineNumber : m_params.lineNumber;
}
static void formatAddress(QTextStream &str, quint64 address)
@@ -1424,94 +1355,94 @@ static void formatAddress(QTextStream &str, quint64 address)
}
}
-bool BreakHandler::BreakpointItem::needsChange() const
+bool BreakpointItem::needsChange() const
{
- if (!data.conditionsMatch(response.condition))
+ if (!m_params.conditionsMatch(m_response.condition))
return true;
- if (data.ignoreCount != response.ignoreCount)
+ if (m_params.ignoreCount != m_response.ignoreCount)
return true;
- if (data.enabled != response.enabled)
+ if (m_params.enabled != m_response.enabled)
return true;
- if (data.threadSpec != response.threadSpec)
+ if (m_params.threadSpec != m_response.threadSpec)
return true;
- if (data.command != response.command)
+ if (m_params.command != m_response.command)
return true;
- if (data.type == BreakpointByFileAndLine && data.lineNumber != response.lineNumber)
+ if (m_params.type == BreakpointByFileAndLine && m_params.lineNumber != m_response.lineNumber)
return true;
// FIXME: Too strict, functions may have parameter lists, or not.
- // if (data.type == BreakpointByFunction && data.functionName != response.functionName)
+ // if (m_params.type == BreakpointByFunction && m_params.functionName != m_response.functionName)
// return true;
- // if (data.type == BreakpointByAddress && data.address != response.address)
+ // if (m_params.type == BreakpointByAddress && m_params.address != m_response.address)
// return true;
return false;
}
-bool BreakHandler::BreakpointItem::isLocatedAt
+bool BreakpointItem::isLocatedAt
(const QString &fileName, int lineNumber, bool useMarkerPosition) const
{
- int line = useMarkerPosition ? response.lineNumber : data.lineNumber;
+ int line = useMarkerPosition ? m_response.lineNumber : m_params.lineNumber;
return lineNumber == line
- && (fileNameMatch(fileName, response.fileName)
+ && (fileNameMatch(fileName, m_response.fileName)
|| fileNameMatch(fileName, markerFileName()));
}
-void BreakHandler::BreakpointItem::updateMarkerIcon()
+void BreakpointItem::updateMarkerIcon()
{
- if (marker) {
- marker->setIcon(icon());
- marker->updateMarker();
+ if (m_marker) {
+ m_marker->setIcon(icon());
+ m_marker->updateMarker();
}
}
-void BreakHandler::BreakpointItem::updateMarker(BreakpointModelId id)
+void BreakpointItem::updateMarker()
{
QString file = markerFileName();
int line = markerLineNumber();
- if (marker && (file != marker->fileName() || line != marker->lineNumber()))
+ if (m_marker && (file != m_marker->fileName() || line != m_marker->lineNumber()))
destroyMarker();
- if (!marker && !file.isEmpty() && line > 0)
- marker = new BreakpointMarker(id, file, line);
+ if (!m_marker && !file.isEmpty() && line > 0)
+ m_marker = new BreakpointMarker(this, file, line);
}
-QIcon BreakHandler::BreakpointItem::icon() const
+QIcon BreakpointItem::icon() const
{
// FIXME: This seems to be called on each cursor blink as soon as the
// cursor is near a line with a breakpoint marker (+/- 2 lines or so).
- if (data.isTracepoint())
+ if (m_params.isTracepoint())
return BreakHandler::tracepointIcon();
- if (data.type == WatchpointAtAddress)
+ if (m_params.type == WatchpointAtAddress)
return BreakHandler::watchpointIcon();
- if (data.type == WatchpointAtExpression)
+ if (m_params.type == WatchpointAtExpression)
return BreakHandler::watchpointIcon();
- if (!data.enabled)
+ if (!m_params.enabled)
return BreakHandler::disabledBreakpointIcon();
- if (state == BreakpointInserted)
+ if (m_state == BreakpointInserted)
return BreakHandler::breakpointIcon();
return BreakHandler::pendingBreakpointIcon();
}
-QString BreakHandler::BreakpointItem::toToolTip() const
+QString BreakpointItem::toToolTip() const
{
QString rc;
QTextStream str(&rc);
str << "<html><body><table>"
//<< "<tr><td>" << tr("ID:") << "</td><td>" << m_id << "</td></tr>"
<< "<tr><td>" << tr("State:")
- << "</td><td>" << (data.enabled ? tr("Enabled") : tr("Disabled"));
- if (response.pending)
+ << "</td><td>" << (m_params.enabled ? tr("Enabled") : tr("Disabled"));
+ if (m_response.pending)
str << tr(", pending");
- str << ", " << state << " (" << stateToString(state) << ")</td></tr>";
- if (engine) {
+ str << ", " << m_state << " (" << stateToString(m_state) << ")</td></tr>";
+ if (m_engine) {
str << "<tr><td>" << tr("Engine:")
- << "</td><td>" << engine->objectName() << "</td></tr>";
+ << "</td><td>" << m_engine->objectName() << "</td></tr>";
}
- if (!response.pending) {
+ if (!m_response.pending) {
str << "<tr><td>" << tr("Breakpoint Number:")
- << "</td><td>" << response.id.toString() << "</td></tr>";
+ << "</td><td>" << m_response.id.toString() << "</td></tr>";
}
str << "<tr><td>" << tr("Breakpoint Type:")
- << "</td><td>" << typeToString(data.type) << "</td></tr>"
+ << "</td><td>" << typeToString(m_params.type) << "</td></tr>"
<< "<tr><td>" << tr("Marker File:")
<< "</td><td>" << QDir::toNativeSeparators(markerFileName()) << "</td></tr>"
<< "<tr><td>" << tr("Marker Line:")
@@ -1521,77 +1452,77 @@ QString BreakHandler::BreakpointItem::toToolTip() const
<< "</th><th>" << tr("Requested")
<< "</th><th>" << tr("Obtained") << "</th></tr>"
<< "<tr><td>" << tr("Internal Number:")
- << "</td><td>&mdash;</td><td>" << response.id.toString() << "</td></tr>";
- if (data.type == BreakpointByFunction) {
+ << "</td><td>&mdash;</td><td>" << m_response.id.toString() << "</td></tr>";
+ if (m_params.type == BreakpointByFunction) {
str << "<tr><td>" << tr("Function Name:")
- << "</td><td>" << data.functionName
- << "</td><td>" << response.functionName
+ << "</td><td>" << m_params.functionName
+ << "</td><td>" << m_response.functionName
<< "</td></tr>";
}
- if (data.type == BreakpointByFileAndLine) {
+ if (m_params.type == BreakpointByFileAndLine) {
str << "<tr><td>" << tr("File Name:")
- << "</td><td>" << QDir::toNativeSeparators(data.fileName)
- << "</td><td>" << QDir::toNativeSeparators(response.fileName)
+ << "</td><td>" << QDir::toNativeSeparators(m_params.fileName)
+ << "</td><td>" << QDir::toNativeSeparators(m_response.fileName)
<< "</td></tr>"
<< "<tr><td>" << tr("Line Number:")
- << "</td><td>" << data.lineNumber
- << "</td><td>" << response.lineNumber << "</td></tr>"
+ << "</td><td>" << m_params.lineNumber
+ << "</td><td>" << m_response.lineNumber << "</td></tr>"
<< "<tr><td>" << tr("Corrected Line Number:")
<< "</td><td>-"
- << "</td><td>" << response.correctedLineNumber << "</td></tr>";
+ << "</td><td>" << m_response.correctedLineNumber << "</td></tr>";
}
- if (data.type == BreakpointByFunction || data.type == BreakpointByFileAndLine) {
+ if (m_params.type == BreakpointByFunction || m_params.type == BreakpointByFileAndLine) {
str << "<tr><td>" << tr("Module:")
- << "</td><td>" << data.module
- << "</td><td>" << response.module
+ << "</td><td>" << m_params.module
+ << "</td><td>" << m_response.module
<< "</td></tr>";
}
str << "<tr><td>" << tr("Breakpoint Address:")
<< "</td><td>";
- formatAddress(str, data.address);
+ formatAddress(str, m_params.address);
str << "</td><td>";
- formatAddress(str, response.address);
+ formatAddress(str, m_response.address);
str << "</td></tr>";
- if (response.multiple) {
+ if (m_response.multiple) {
str << "<tr><td>" << tr("Multiple Addresses:")
<< "</td><td>"
<< "</td></tr>";
}
- if (!data.command.isEmpty() || !response.command.isEmpty()) {
+ if (!m_params.command.isEmpty() || !m_response.command.isEmpty()) {
str << "<tr><td>" << tr("Command:")
- << "</td><td>" << data.command
- << "</td><td>" << response.command
+ << "</td><td>" << m_params.command
+ << "</td><td>" << m_response.command
<< "</td></tr>";
}
- if (!data.message.isEmpty() || !response.message.isEmpty()) {
+ if (!m_params.message.isEmpty() || !m_response.message.isEmpty()) {
str << "<tr><td>" << tr("Message:")
- << "</td><td>" << data.message
- << "</td><td>" << response.message
+ << "</td><td>" << m_params.message
+ << "</td><td>" << m_response.message
<< "</td></tr>";
}
- if (!data.condition.isEmpty() || !response.condition.isEmpty()) {
+ if (!m_params.condition.isEmpty() || !m_response.condition.isEmpty()) {
str << "<tr><td>" << tr("Condition:")
- << "</td><td>" << data.condition
- << "</td><td>" << response.condition
+ << "</td><td>" << m_params.condition
+ << "</td><td>" << m_response.condition
<< "</td></tr>";
}
- if (data.ignoreCount || response.ignoreCount) {
+ if (m_params.ignoreCount || m_response.ignoreCount) {
str << "<tr><td>" << tr("Ignore Count:") << "</td><td>";
- if (data.ignoreCount)
- str << data.ignoreCount;
+ if (m_params.ignoreCount)
+ str << m_params.ignoreCount;
str << "</td><td>";
- if (response.ignoreCount)
- str << response.ignoreCount;
+ if (m_response.ignoreCount)
+ str << m_response.ignoreCount;
str << "</td></tr>";
}
- if (data.threadSpec >= 0 || response.threadSpec >= 0) {
+ if (m_params.threadSpec >= 0 || m_response.threadSpec >= 0) {
str << "<tr><td>" << tr("Thread Specification:")
<< "</td><td>";
- if (data.threadSpec >= 0)
- str << data.threadSpec;
+ if (m_params.threadSpec >= 0)
+ str << m_params.threadSpec;
str << "</td><td>";
- if (response.threadSpec >= 0)
- str << response.threadSpec;
+ if (m_response.threadSpec >= 0)
+ str << m_response.threadSpec;
str << "</td></tr>";
}
str << "</table></body></html>";
@@ -1600,29 +1531,89 @@ QString BreakHandler::BreakpointItem::toToolTip() const
void BreakHandler::setWatchpointAtAddress(quint64 address, unsigned size)
{
- BreakpointParameters data(WatchpointAtAddress);
- data.address = address;
- data.size = size;
- BreakpointModelId id = findWatchpoint(data);
- if (id) {
+ BreakpointParameters params(WatchpointAtAddress);
+ params.address = address;
+ params.size = size;
+ if (findWatchpoint(params)) {
qDebug() << "WATCHPOINT EXISTS";
// removeBreakpoint(index);
return;
}
- appendBreakpoint(data);
+ appendBreakpoint(params);
}
void BreakHandler::setWatchpointAtExpression(const QString &exp)
{
- BreakpointParameters data(WatchpointAtExpression);
- data.expression = exp;
- BreakpointModelId id = findWatchpoint(data);
- if (id) {
+ BreakpointParameters params(WatchpointAtExpression);
+ params.expression = exp;
+ if (findWatchpoint(params)) {
qDebug() << "WATCHPOINT EXISTS";
// removeBreakpoint(index);
return;
}
- appendBreakpoint(data);
+ appendBreakpoint(params);
+}
+
+bool Breakpoint::isValid() const
+{
+ return b && b->m_id.isValid();
+}
+
+uint Breakpoint::hash() const
+{
+ return b ? 0 : qHash(b->m_id);
+}
+
+BreakpointModelId Breakpoint::id() const
+{
+ return b ? b->m_id : BreakpointModelId();
+}
+
+QString Breakpoint::msgWatchpointByExpressionTriggered(const int number, const QString &expr) const
+{
+ return id()
+ ? tr("Data breakpoint %1 (%2) at %3 triggered.")
+ .arg(id().toString()).arg(number).arg(expr)
+ : tr("Internal data breakpoint %1 at %2 triggered.")
+ .arg(number).arg(expr);
+}
+
+QString Breakpoint::msgWatchpointByExpressionTriggered(const int number, const QString &expr,
+ const QString &threadId) const
+{
+ return id()
+ ? tr("Data breakpoint %1 (%2) at %3 in thread %4 triggered.")
+ .arg(id().toString()).arg(number).arg(expr).arg(threadId)
+ : tr("Internal data breakpoint %1 at %2 in thread %3 triggered.")
+ .arg(number).arg(expr).arg(threadId);
+}
+
+QString Breakpoint::msgWatchpointByAddressTriggered(const int number, quint64 address) const
+{
+ return id()
+ ? tr("Data breakpoint %1 (%2) at 0x%3 triggered.")
+ .arg(id().toString()).arg(number).arg(address, 0, 16)
+ : tr("Internal data breakpoint %1 at 0x%2 triggered.")
+ .arg(number).arg(address, 0, 16);
+}
+
+QString Breakpoint::msgWatchpointByAddressTriggered(
+ const int number, quint64 address, const QString &threadId) const
+{
+ return id()
+ ? tr("Data breakpoint %1 (%2) at 0x%3 in thread %4 triggered.")
+ .arg(id().toString()).arg(number).arg(address, 0, 16).arg(threadId)
+ : tr("Internal data breakpoint %1 at 0x%2 in thread %3 triggered.")
+ .arg(id().toString()).arg(number).arg(address, 0, 16).arg(threadId);
+}
+
+QString Breakpoint::msgBreakpointTriggered(const int number, const QString &threadId) const
+{
+ return id()
+ ? tr("Stopped at breakpoint %1 (%2) in thread %3.")
+ .arg(id().toString()).arg(number).arg(threadId)
+ : tr("Stopped at internal breakpoint %1 in thread %2.")
+ .arg(number).arg(threadId);
}
} // namespace Internal
diff --git a/src/plugins/debugger/breakhandler.h b/src/plugins/debugger/breakhandler.h
index 7281d88faa5..430f93c698a 100644
--- a/src/plugins/debugger/breakhandler.h
+++ b/src/plugins/debugger/breakhandler.h
@@ -33,7 +33,10 @@
#include "breakpoint.h"
-#include <QAbstractTableModel>
+#include <utils/treemodel.h>
+
+#include <QCoreApplication>
+#include <QPointer>
//////////////////////////////////////////////////////////////////
//
@@ -42,20 +45,132 @@
//////////////////////////////////////////////////////////////////
namespace Debugger {
+namespace Internal {
+class BreakpointItem;
+class BreakHandler;
+class DebuggerCommand;
class DebuggerEngine;
-namespace Internal {
+// Non-owning "deletion-safe" wrapper around a BreakpointItem *
+class Breakpoint
+{
+ Q_DECLARE_TR_FUNCTIONS(Debugger::Internal::BreakHandler)
+
+public:
+ Breakpoint() {}
+
+ bool isValid() const;
+ operator const void *() const { return isValid() ? this : 0; }
+ bool operator!() const { return !isValid(); }
+
+ uint hash() const;
+
+ const BreakpointParameters &parameters() const;
+ void addToCommand(DebuggerCommand *cmd) const;
-class BreakpointMarker;
+ BreakpointModelId id() const;
+ bool isLocatedAt(const QString &fileName, int lineNumber,
+ bool useMarkerPosition) const;
+
+ QIcon icon() const;
+ BreakpointState state() const;
+ void setEngine(DebuggerEngine *engine);
+
+ // State transitions.
+ void notifyBreakpointChangeAfterInsertNeeded();
+ void notifyBreakpointInsertProceeding();
+ void notifyBreakpointInsertOk();
+ void notifyBreakpointInsertFailed();
+ void notifyBreakpointChangeOk();
+ void notifyBreakpointChangeProceeding();
+ void notifyBreakpointChangeFailed();
+ void notifyBreakpointPending();
+ void notifyBreakpointRemoveProceeding();
+ void notifyBreakpointRemoveOk();
+ void notifyBreakpointRemoveFailed();
+ void notifyBreakpointReleased();
+ void notifyBreakpointNeedsReinsertion();
+ void notifyBreakpointAdjusted(const BreakpointParameters &params);
+
+ void update();
+
+ void gotoLocation() const;
+
+ // Getter retrieves property value.
+ // Setter sets property value and triggers update if changed.
+ // Only use setters when it is safe to assume that the breakpoint still
+ // exist. That's not the case if the event loop could run after you
+ // obtained the BreakpointItem pointer.
+ BreakpointPathUsage pathUsage() const;
+ void setPathUsage(const BreakpointPathUsage &u);
+ QByteArray condition() const;
+ void setCondition(const QByteArray &condition);
+ int ignoreCount() const;
+ void setIgnoreCount(const int &count);
+ int threadSpec() const;
+ void setThreadSpec(const int &spec);
+ QString fileName() const;
+ void setFileName(const QString &fileName);
+ QString functionName() const;
+ void setFunctionName(const QString &functionName);
+ QString expression() const;
+ void setExpression(const QString &expression);
+ QString message() const;
+ void setMessage(const QString &m);
+ BreakpointType type() const;
+ void setType(const BreakpointType &type);
+ quint64 address() const;
+ void setAddress(const quint64 &address);
+ int lineNumber() const;
+ void changeBreakpointData(const BreakpointParameters &data);
+ bool isEnabled() const;
+ void setEnabled(bool on) const;
+ void updateFileNameFromMarker(const QString &fileName);
+ void updateLineNumberFromMarker(int lineNumber);
+ void changeLineNumberFromMarker(int lineNumber);
+ void setMarkerFileAndLine(const QString &fileName, int lineNumber);
+ bool isWatchpoint() const;
+ bool isTracepoint() const;
+ void setTracepoint(bool on);
+ DebuggerEngine *engine() const;
+ const BreakpointResponse &response() const;
+ void setResponse(const BreakpointResponse &data);
+ bool needsChange() const;
+ bool needsChildren() const;
+
+ bool isOneShot() const;
+ void insertSubBreakpoint(const BreakpointResponse &data);
+ void removeAlienBreakpoint();
+ void removeBreakpoint() const;
+
+ QString msgWatchpointByAddressTriggered(int number, quint64 address) const;
+ QString msgWatchpointByAddressTriggered(
+ int number, quint64 address, const QString &threadId) const;
+ QString msgWatchpointByExpressionTriggered(int number, const QString &expr) const;
+ QString msgWatchpointByExpressionTriggered(
+ int number, const QString &expr, const QString &threadId) const;
+ QString msgBreakpointTriggered(int number, const QString &threadId) const;
+
+private:
+ void gotoState(BreakpointState target, BreakpointState assumedCurrent);
-class BreakHandler : public QAbstractItemModel
+ friend class BreakHandler;
+ explicit Breakpoint(BreakpointItem *b);
+
+ QPointer<BreakpointItem> b;
+};
+
+inline uint qHash(const Debugger::Internal::Breakpoint &b) { return b.hash(); }
+
+typedef QList<Breakpoint> Breakpoints;
+
+class BreakHandler : public Utils::TreeModel
{
Q_OBJECT
public:
BreakHandler();
- ~BreakHandler();
void loadSessionData();
void saveSessionData();
@@ -65,22 +180,19 @@ public:
// The only way to add a new breakpoint.
void appendBreakpoint(const BreakpointParameters &data);
void handleAlienBreakpoint(const BreakpointResponse &response, DebuggerEngine *engine);
- void insertSubBreakpoint(BreakpointModelId id, const BreakpointResponse &data);
- void removeAlienBreakpoint(BreakpointModelId id);
- BreakpointModelIds allBreakpointIds() const;
- BreakpointModelIds engineBreakpointIds(DebuggerEngine *engine) const;
- BreakpointModelIds unclaimedBreakpointIds() const;
- int size() const { return m_storage.size(); }
+ Breakpoints allBreakpoints() const;
+ Breakpoints engineBreakpoints(DebuggerEngine *engine) const;
+ Breakpoints unclaimedBreakpoints() const;
QStringList engineBreakpointPaths(DebuggerEngine *engine) const;
// Find a breakpoint matching approximately the data in needle.
- BreakpointModelId findSimilarBreakpoint(const BreakpointResponse &needle) const;
- BreakpointModelId findBreakpointByResponseId(const BreakpointResponseId &resultId) const;
- BreakpointModelId findWatchpoint(const BreakpointParameters &data) const;
- BreakpointModelId findBreakpointByFunction(const QString &functionName) const;
- BreakpointModelId findBreakpointByIndex(const QModelIndex &index) const;
- BreakpointModelIds findBreakpointsByIndex(const QList<QModelIndex> &list) const;
+ Breakpoint findSimilarBreakpoint(const BreakpointResponse &needle) const;
+ Breakpoint findBreakpointByResponseId(const BreakpointResponseId &resultId) const;
+ Breakpoint findWatchpoint(const BreakpointParameters &data) const;
+ Breakpoint findBreakpointByFunction(const QString &functionName) const;
+ Breakpoint findBreakpointByIndex(const QModelIndex &index) const;
+ Breakpoints findBreakpointsByIndex(const QList<QModelIndex> &list) const;
void updateMarkers();
static QIcon breakpointIcon();
@@ -90,77 +202,11 @@ public:
static QIcon watchpointIcon();
static QIcon tracepointIcon();
- BreakpointModelId findBreakpointByFileAndLine(const QString &fileName,
+ Breakpoint findBreakpointByFileAndLine(const QString &fileName,
int lineNumber, bool useMarkerPosition = true);
- BreakpointModelId findBreakpointByAddress(quint64 address) const;
+ Breakpoint findBreakpointByAddress(quint64 address) const;
void breakByFunction(const QString &functionName);
- void removeBreakpoint(BreakpointModelId id);
- QIcon icon(BreakpointModelId id) const;
- void gotoLocation(BreakpointModelId id) const;
-
- // Getter retrieves property value.
- // Setter sets property value and triggers update if changed.
- BreakpointPathUsage pathUsage(BreakpointModelId id) const;
- void setPathUsage(BreakpointModelId, const BreakpointPathUsage &u);
- QByteArray condition(BreakpointModelId id) const;
- void setCondition(BreakpointModelId, const QByteArray &condition);
- int ignoreCount(BreakpointModelId id) const;
- void setIgnoreCount(BreakpointModelId, const int &count);
- int threadSpec(BreakpointModelId id) const;
- void setThreadSpec(BreakpointModelId, const int &spec);
- QString fileName(BreakpointModelId id) const;
- void setFileName(BreakpointModelId, const QString &fileName);
- QString functionName(BreakpointModelId id) const;
- void setFunctionName(BreakpointModelId, const QString &functionName);
- QString expression(BreakpointModelId id) const;
- void setExpression(BreakpointModelId, const QString &expression);
- QString message(BreakpointModelId id) const;
- void setMessage(BreakpointModelId, const QString &m);
- BreakpointType type(BreakpointModelId id) const;
- void setType(BreakpointModelId id, const BreakpointType &type);
- quint64 address(BreakpointModelId id) const;
- void setAddress(BreakpointModelId id, const quint64 &address);
- int lineNumber(BreakpointModelId id) const;
- void changeBreakpointData(BreakpointModelId id, const BreakpointParameters &data,
- BreakpointParts parts);
- const BreakpointParameters &breakpointData(BreakpointModelId id) const;
- BreakpointState state(BreakpointModelId id) const;
- bool isEnabled(BreakpointModelId id) const;
- void setEnabled(BreakpointModelId id, bool on);
- void updateFileNameFromMarker(BreakpointModelId id, const QString &fileName);
- void updateLineNumberFromMarker(BreakpointModelId id, int lineNumber);
- void changeLineNumberFromMarker(BreakpointModelId id, int lineNumber);
- void setMarkerFileAndLine(BreakpointModelId id,
- const QString &fileName, int lineNumber);
- bool isOneShot(BreakpointModelId id) const;
- bool isWatchpoint(BreakpointModelId id) const;
- bool isTracepoint(BreakpointModelId id) const;
- void setTracepoint(BreakpointModelId, bool on);
- DebuggerEngine *engine(BreakpointModelId id) const;
- void setEngine(BreakpointModelId id, DebuggerEngine *engine);
- const BreakpointResponse &response(BreakpointModelId id) const;
- void setResponse(BreakpointModelId id, const BreakpointResponse &data);
- bool needsChange(BreakpointModelId id) const;
- bool needsChildren(BreakpointModelId id) const;
-
- // State transitions.
- void notifyBreakpointChangeAfterInsertNeeded(BreakpointModelId id);
- void notifyBreakpointInsertProceeding(BreakpointModelId id);
- void notifyBreakpointInsertOk(BreakpointModelId id);
- void notifyBreakpointInsertFailed(BreakpointModelId id);
- void notifyBreakpointChangeOk(BreakpointModelId id);
- void notifyBreakpointChangeProceeding(BreakpointModelId id);
- void notifyBreakpointChangeFailed(BreakpointModelId id);
- void notifyBreakpointPending(BreakpointModelId id);
- void notifyBreakpointRemoveProceeding(BreakpointModelId id);
- void notifyBreakpointRemoveOk(BreakpointModelId id);
- void notifyBreakpointRemoveFailed(BreakpointModelId id);
- void notifyBreakpointReleased(BreakpointModelId id);
- void notifyBreakpointNeedsReinsertion(BreakpointModelId id);
- void notifyBreakpointAdjusted(BreakpointModelId id,
- const BreakpointParameters &data);
-
static QString displayFromThreadSpec(int spec);
static int threadSpecFromDisplay(const QString &str);
@@ -168,53 +214,19 @@ public:
void setWatchpointAtAddress(quint64 address, unsigned size);
void setWatchpointAtExpression(const QString &exp);
+ Breakpoint breakpointById(BreakpointModelId id) const;
+
private:
- // QAbstractItemModel implementation.
- int columnCount(const QModelIndex &parent) const;
- int rowCount(const QModelIndex &parent) const;
- QVariant data(const QModelIndex &index, int role) const;
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
- QModelIndex index(int row, int col, const QModelIndex &parent) const;
- QModelIndex parent(const QModelIndex &parent) const;
- QModelIndex createIndex(int row, int column, quint32 id) const;
- QModelIndex createIndex(int row, int column, void *ptr) const;
-
- int indexOf(BreakpointModelId id) const;
- BreakpointModelId at(int index) const;
- bool isEngineRunning(BreakpointModelId id) const;
- void setState(BreakpointModelId id, BreakpointState state);
+ friend class BreakpointItem;
+ friend class Breakpoint;
+
void loadBreakpoints();
void saveBreakpoints();
- void cleanupBreakpoint(BreakpointModelId id);
- Q_SLOT void changeLineNumberFromMarkerHelper(Debugger::Internal::BreakpointModelId id, int lineNumber);
-
- struct BreakpointItem
- {
- BreakpointItem();
-
- void destroyMarker();
- bool needsChange() const;
- bool isLocatedAt(const QString &fileName, int lineNumber,
- bool useMarkerPosition) const;
- void updateMarker(BreakpointModelId id);
- void updateMarkerIcon();
- QString toToolTip() const;
- QString markerFileName() const;
- int markerLineNumber() const;
- QIcon icon() const;
-
- BreakpointParameters data;
- BreakpointState state; // Current state of breakpoint.
- DebuggerEngine *engine; // Engine currently handling the breakpoint.
- BreakpointResponse response;
- BreakpointMarker *marker;
- QList<BreakpointResponse> subItems;
- };
- typedef QHash<BreakpointModelId, BreakpointItem> BreakpointStorage;
- typedef BreakpointStorage::ConstIterator ConstIterator;
- typedef BreakpointStorage::Iterator Iterator;
- BreakpointStorage m_storage;
+
+ void appendBreakpointInternal(const BreakpointParameters &data);
+
+ Q_SLOT void changeLineNumberFromMarkerHelper(Debugger::Internal::BreakpointModelId id);
+ Q_SLOT void deletionHelper(Debugger::Internal::BreakpointModelId id);
void scheduleSynchronization();
void timerEvent(QTimerEvent *event);
@@ -224,4 +236,6 @@ private:
} // namespace Internal
} // namespace Debugger
+Q_DECLARE_METATYPE(Debugger::Internal::Breakpoint)
+
#endif // DEBUGGER_BREAKHANDLER_H
diff --git a/src/plugins/debugger/breakpoint.cpp b/src/plugins/debugger/breakpoint.cpp
index 859ed4956e8..76a722c66b6 100644
--- a/src/plugins/debugger/breakpoint.cpp
+++ b/src/plugins/debugger/breakpoint.cpp
@@ -94,18 +94,6 @@ QString BreakpointModelId::toString() const
return QString::number(m_majorPart);
}
-BreakpointModelId BreakpointModelId::parent() const
-{
- QTC_ASSERT(isMinor(), return BreakpointModelId());
- return BreakpointModelId(m_majorPart, 0);
-}
-
-BreakpointModelId BreakpointModelId::child(int row) const
-{
- QTC_ASSERT(isMajor(), return BreakpointModelId());
- return BreakpointModelId(m_majorPart, row + 1);
-}
-
//////////////////////////////////////////////////////////////////
//
diff --git a/src/plugins/debugger/breakpoint.h b/src/plugins/debugger/breakpoint.h
index d53a2929705..989c3528c89 100644
--- a/src/plugins/debugger/breakpoint.h
+++ b/src/plugins/debugger/breakpoint.h
@@ -63,8 +63,6 @@ public:
{ return m_majorPart == id.m_majorPart && m_minorPart == id.m_minorPart; }
quint16 majorPart() const { return m_majorPart; }
quint16 minorPart() const { return m_minorPart; }
- BreakpointModelId parent() const;
- BreakpointModelId child(int row) const;
static BreakpointModelId fromInternalId(quint32 id)
{ return BreakpointModelId(id & 0xff, id >> 16); }
@@ -199,7 +197,6 @@ inline void operator|=(BreakpointParts &p, BreakpointParts r)
p = BreakpointParts(int(p) | int(r));
}
-
class BreakpointParameters
{
public:
@@ -257,8 +254,6 @@ public:
int correctedLineNumber; //!< Line number as seen by gdb.
};
-typedef QList<BreakpointModelId> BreakpointModelIds;
-
inline uint qHash(const Debugger::Internal::BreakpointModelId &id)
{
return id.toInternalId();
diff --git a/src/plugins/debugger/breakpointmarker.cpp b/src/plugins/debugger/breakpointmarker.cpp
deleted file mode 100644
index 5867d64bf9c..00000000000
--- a/src/plugins/debugger/breakpointmarker.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "breakpointmarker.h"
-#include "breakhandler.h"
-#include "debuggercore.h"
-
-//////////////////////////////////////////////////////////////////
-//
-// BreakpointMarker
-//
-//////////////////////////////////////////////////////////////////
-
-
-namespace Debugger {
-namespace Internal {
-
-BreakpointMarker::BreakpointMarker(BreakpointModelId id,
- const QString &fileName, int lineNumber)
- : TextMark(fileName, lineNumber), m_id(id)
-{
- setIcon(breakHandler()->icon(m_id));
- setPriority(TextEditor::TextMark::NormalPriority);
- //qDebug() << "CREATE MARKER " << fileName << lineNumber;
-}
-
-BreakpointMarker::~BreakpointMarker()
-{
- //qDebug() << "REMOVE MARKER ";
-}
-
-void BreakpointMarker::removedFromEditor()
-{
- breakHandler()->removeBreakpoint(m_id);
-}
-
-void BreakpointMarker::updateLineNumber(int lineNumber)
-{
- TextMark::updateLineNumber(lineNumber);
- breakHandler()->updateLineNumberFromMarker(m_id, lineNumber);
-}
-
-void BreakpointMarker::dragToLine(int lineNumber)
-{
- breakHandler()->changeLineNumberFromMarker(m_id, lineNumber);
-}
-
-void BreakpointMarker::clicked()
-{
- breakHandler()->removeBreakpoint(m_id);
-}
-
-void BreakpointMarker::updateFileName(const QString &fileName)
-{
- TextMark::updateFileName(fileName);
- breakHandler()->updateFileNameFromMarker(m_id, fileName);
-}
-
-} // namespace Internal
-} // namespace Debugger
-
diff --git a/src/plugins/debugger/breakwindow.cpp b/src/plugins/debugger/breakwindow.cpp
index fdc23649926..ff5434e2984 100644
--- a/src/plugins/debugger/breakwindow.cpp
+++ b/src/plugins/debugger/breakwindow.cpp
@@ -49,7 +49,6 @@
#include <QKeyEvent>
#include <QLabel>
#include <QLineEdit>
-#include <QMessageBox>
#include <QMenu>
#include <QSpinBox>
#include <QTextEdit>
@@ -81,7 +80,7 @@ class BreakpointDialog : public QDialog
{
Q_OBJECT
public:
- explicit BreakpointDialog(BreakpointModelId id, QWidget *parent = 0);
+ explicit BreakpointDialog(Breakpoint b, QWidget *parent = 0);
bool showDialog(BreakpointParameters *data, BreakpointParts *parts);
void setParameters(const BreakpointParameters &data);
@@ -139,13 +138,13 @@ private:
QDialogButtonBox *m_buttonBox;
};
-BreakpointDialog::BreakpointDialog(BreakpointModelId id, QWidget *parent)
+BreakpointDialog::BreakpointDialog(Breakpoint b, QWidget *parent)
: QDialog(parent), m_enabledParts(~0), m_previousType(UnknownBreakpointType),
m_firstTypeChange(true)
{
setWindowTitle(tr("Edit Breakpoint Properties"));
- QGroupBox *groupBoxBasic = new QGroupBox(tr("Basic"), this);
+ auto groupBoxBasic = new QGroupBox(tr("Basic"), this);
// Match BreakpointType (omitting unknown type).
QStringList types;
@@ -196,7 +195,7 @@ BreakpointDialog::BreakpointDialog(BreakpointModelId id, QWidget *parent)
m_labelFunction = new QLabel(tr("Fun&ction:"), groupBoxBasic);
m_labelFunction->setBuddy(m_lineEditFunction);
- QGroupBox *groupBoxAdvanced = new QGroupBox(tr("Advanced"), this);
+ auto groupBoxAdvanced = new QGroupBox(tr("Advanced"), this);
m_checkBoxTracepoint = new QCheckBox(groupBoxAdvanced);
m_labelTracepoint = new QLabel(tr("T&racepoint only:"), groupBoxAdvanced);
@@ -269,8 +268,8 @@ BreakpointDialog::BreakpointDialog(BreakpointModelId id, QWidget *parent)
m_buttonBox = new QDialogButtonBox(this);
m_buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
- if (id.isValid()) {
- if (DebuggerEngine *engine = breakHandler()->engine(id)) {
+ if (b) {
+ if (DebuggerEngine *engine = b.engine()) {
if (!engine->hasCapability(BreakConditionCapability))
m_enabledParts &= ~ConditionPart;
if (!engine->hasCapability(BreakModuleCapability))
@@ -280,7 +279,7 @@ BreakpointDialog::BreakpointDialog(BreakpointModelId id, QWidget *parent)
}
}
- QFormLayout *basicLayout = new QFormLayout(groupBoxBasic);
+ auto basicLayout = new QFormLayout(groupBoxBasic);
basicLayout->addRow(m_labelType, m_comboBoxType);
basicLayout->addRow(m_labelFileName, m_pathChooserFileName);
basicLayout->addRow(m_labelLineNumber, m_lineEditLineNumber);
@@ -290,7 +289,7 @@ BreakpointDialog::BreakpointDialog(BreakpointModelId id, QWidget *parent)
basicLayout->addRow(m_labelFunction, m_lineEditFunction);
basicLayout->addRow(m_labelOneShot, m_checkBoxOneShot);
- QFormLayout *advancedLeftLayout = new QFormLayout();
+ auto advancedLeftLayout = new QFormLayout();
advancedLeftLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
advancedLeftLayout->addRow(m_labelCondition, m_lineEditCondition);
advancedLeftLayout->addRow(m_labelIgnoreCount, m_spinBoxIgnoreCount);
@@ -298,18 +297,18 @@ BreakpointDialog::BreakpointDialog(BreakpointModelId id, QWidget *parent)
advancedLeftLayout->addRow(m_labelUseFullPath, m_comboBoxPathUsage);
advancedLeftLayout->addRow(m_labelModule, m_lineEditModule);
- QFormLayout *advancedRightLayout = new QFormLayout();
+ auto advancedRightLayout = new QFormLayout();
advancedRightLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
advancedRightLayout->addRow(m_labelCommands, m_textEditCommands);
advancedRightLayout->addRow(m_labelTracepoint, m_checkBoxTracepoint);
advancedRightLayout->addRow(m_labelMessage, m_lineEditMessage);
- QHBoxLayout *horizontalLayout = new QHBoxLayout(groupBoxAdvanced);
+ auto horizontalLayout = new QHBoxLayout(groupBoxAdvanced);
horizontalLayout->addLayout(advancedLeftLayout);
horizontalLayout->addSpacing(15);
horizontalLayout->addLayout(advancedRightLayout);
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
+ auto verticalLayout = new QVBoxLayout(this);
verticalLayout->addWidget(groupBoxBasic);
verticalLayout->addSpacing(10);
verticalLayout->addWidget(groupBoxAdvanced);
@@ -317,9 +316,10 @@ BreakpointDialog::BreakpointDialog(BreakpointModelId id, QWidget *parent)
verticalLayout->addWidget(m_buttonBox);
verticalLayout->setStretchFactor(groupBoxAdvanced, 10);
- connect(m_comboBoxType, SIGNAL(activated(int)), SLOT(typeChanged(int)));
- connect(m_buttonBox, SIGNAL(accepted()), SLOT(accept()));
- connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));
+ connect(m_comboBoxType, static_cast<void(QComboBox::*)(int)>(&QComboBox::activated),
+ this, &BreakpointDialog::typeChanged);
+ connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
void BreakpointDialog::setType(BreakpointType type)
@@ -655,18 +655,18 @@ MultiBreakPointsDialog::MultiBreakPointsDialog(QWidget *parent) :
m_buttonBox = new QDialogButtonBox(this);
m_buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
- QFormLayout *formLayout = new QFormLayout;
+ auto formLayout = new QFormLayout;
if (currentEngine()->hasCapability(BreakConditionCapability))
formLayout->addRow(tr("&Condition:"), m_lineEditCondition);
formLayout->addRow(tr("&Ignore count:"), m_spinBoxIgnoreCount);
formLayout->addRow(tr("&Thread specification:"), m_lineEditThreadSpec);
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
+ auto verticalLayout = new QVBoxLayout(this);
verticalLayout->addLayout(formLayout);
verticalLayout->addWidget(m_buttonBox);
- QObject::connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
- QObject::connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
+ connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
///////////////////////////////////////////////////////////////////////
@@ -679,8 +679,8 @@ BreakTreeView::BreakTreeView()
{
setWindowIcon(QIcon(QLatin1String(":/debugger/images/debugger_breakpoints.png")));
setSelectionMode(QAbstractItemView::ExtendedSelection);
- connect(action(UseAddressInBreakpointsView),
- SIGNAL(toggled(bool)), SLOT(showAddressColumn(bool)));
+ connect(action(UseAddressInBreakpointsView), &QAction::toggled,
+ this, &BreakTreeView::showAddressColumn);
}
void BreakTreeView::showAddressColumn(bool on)
@@ -693,22 +693,21 @@ void BreakTreeView::keyPressEvent(QKeyEvent *ev)
if (ev->key() == Qt::Key_Delete) {
QItemSelectionModel *sm = selectionModel();
QTC_ASSERT(sm, return);
- QModelIndexList si = sm->selectedIndexes();
+ QModelIndexList si = sm->selectedRows();
if (si.isEmpty())
si.append(currentIndex());
- const BreakpointModelIds ids = breakHandler()->findBreakpointsByIndex(si);
+ const Breakpoints ids = breakHandler()->findBreakpointsByIndex(si);
int row = qMin(model()->rowCount() - ids.size() - 1, currentIndex().row());
deleteBreakpoints(ids);
- setCurrentIndex(si.at(0).sibling(row, 0));
+ setCurrentIndex(model()->index(row, 0));
} else if (ev->key() == Qt::Key_Space) {
QItemSelectionModel *sm = selectionModel();
QTC_ASSERT(sm, return);
- const QModelIndexList selectedIds = sm->selectedIndexes();
+ const QModelIndexList selectedIds = sm->selectedRows();
if (!selectedIds.isEmpty()) {
- BreakHandler *handler = breakHandler();
- const BreakpointModelIds validIds = handler->findBreakpointsByIndex(selectedIds);
- const bool isEnabled = validIds.isEmpty() || handler->isEnabled(validIds.at(0));
- setBreakpointsEnabled(validIds, !isEnabled);
+ const Breakpoints items = breakHandler()->findBreakpointsByIndex(selectedIds);
+ const bool isEnabled = items.isEmpty() || items.at(0).isEnabled();
+ setBreakpointsEnabled(items, !isEnabled);
foreach (const QModelIndex &id, selectedIds)
update(id);
}
@@ -721,8 +720,9 @@ void BreakTreeView::mouseDoubleClickEvent(QMouseEvent *ev)
QModelIndex indexUnderMouse = indexAt(ev->pos());
if (indexUnderMouse.isValid()) {
if (indexUnderMouse.column() >= 4) {
- BreakpointModelId id = breakHandler()->findBreakpointByIndex(indexUnderMouse);
- editBreakpoints(BreakpointModelIds() << id);
+ Breakpoint b = breakHandler()->findBreakpointByIndex(indexUnderMouse);
+ QTC_ASSERT(b, return);
+ editBreakpoints(Breakpoints() << b);
}
} else {
addBreakpoint();
@@ -735,27 +735,24 @@ void BreakTreeView::contextMenuEvent(QContextMenuEvent *ev)
QMenu menu;
QItemSelectionModel *sm = selectionModel();
QTC_ASSERT(sm, return);
- QModelIndexList selectedIndices = sm->selectedIndexes();
+ QModelIndexList selectedIndices = sm->selectedRows();
QModelIndex indexUnderMouse = indexAt(ev->pos());
if (selectedIndices.isEmpty() && indexUnderMouse.isValid())
selectedIndices.append(indexUnderMouse);
BreakHandler *handler = breakHandler();
- BreakpointModelIds selectedIds;
- foreach (BreakpointModelId id, handler->findBreakpointsByIndex(selectedIndices))
- if (id.isMajor())
- selectedIds.append(id);
+ Breakpoints selectedItems = handler->findBreakpointsByIndex(selectedIndices);
const int rowCount = model()->rowCount();
- QAction *deleteAction = new QAction(tr("Delete Breakpoint"), &menu);
- deleteAction->setEnabled(!selectedIds.empty());
+ auto deleteAction = new QAction(tr("Delete Selected Breakpoints"), &menu);
+ deleteAction->setEnabled(!selectedItems.empty());
- QAction *deleteAllAction = new QAction(tr("Delete All Breakpoints"), &menu);
+ auto deleteAllAction = new QAction(tr("Delete All Breakpoints"), &menu);
deleteAllAction->setEnabled(model()->rowCount() > 0);
// Delete by file: Find indices of breakpoints of the same file.
QAction *deleteByFileAction = 0;
- BreakpointModelIds breakpointsInFile;
+ Breakpoints breakpointsInFile;
if (indexUnderMouse.isValid()) {
const QModelIndex index = indexUnderMouse.sibling(indexUnderMouse.row(), 2);
const QString file = index.data().toString();
@@ -775,36 +772,33 @@ void BreakTreeView::contextMenuEvent(QContextMenuEvent *ev)
deleteByFileAction->setEnabled(false);
}
- QAction *editBreakpointAction =
- new QAction(tr("Edit Breakpoint..."), &menu);
- editBreakpointAction->setEnabled(!selectedIds.isEmpty());
+ auto editBreakpointAction = new QAction(tr("Edit Breakpoint..."), &menu);
+ editBreakpointAction->setEnabled(!selectedItems.isEmpty());
int threadId = 0;
// FIXME BP: m_engine->threadsHandler()->currentThreadId();
QString associateTitle = threadId == -1
? tr("Associate Breakpoint With All Threads")
: tr("Associate Breakpoint With Thread %1").arg(threadId);
- QAction *associateBreakpointAction = new QAction(associateTitle, &menu);
- associateBreakpointAction->setEnabled(!selectedIds.isEmpty());
+ auto associateBreakpointAction = new QAction(associateTitle, &menu);
+ associateBreakpointAction->setEnabled(!selectedItems.isEmpty());
- QAction *synchronizeAction =
- new QAction(tr("Synchronize Breakpoints"), &menu);
+ auto synchronizeAction = new QAction(tr("Synchronize Breakpoints"), &menu);
synchronizeAction->setEnabled(Internal::hasSnapshots());
- bool enabled = selectedIds.isEmpty() || handler->isEnabled(selectedIds.at(0));
+ bool enabled = selectedItems.isEmpty() || selectedItems.at(0).isEnabled();
- const QString str5 = selectedIds.size() > 1
+ const QString str5 = selectedItems.size() > 1
? enabled
? tr("Disable Selected Breakpoints")
: tr("Enable Selected Breakpoints")
: enabled
? tr("Disable Breakpoint")
: tr("Enable Breakpoint");
- QAction *toggleEnabledAction = new QAction(str5, &menu);
- toggleEnabledAction->setEnabled(!selectedIds.isEmpty());
+ auto toggleEnabledAction = new QAction(str5, &menu);
+ toggleEnabledAction->setEnabled(!selectedItems.isEmpty());
- QAction *addBreakpointAction =
- new QAction(tr("Add Breakpoint..."), this);
+ auto addBreakpointAction = new QAction(tr("Add Breakpoint..."), this);
menu.addAction(addBreakpointAction);
menu.addAction(deleteAction);
@@ -826,28 +820,27 @@ void BreakTreeView::contextMenuEvent(QContextMenuEvent *ev)
QAction *act = menu.exec(ev->globalPos());
if (act == deleteAction)
- deleteBreakpoints(selectedIds);
+ deleteBreakpoints(selectedItems);
else if (act == deleteAllAction)
deleteAllBreakpoints();
else if (act == deleteByFileAction)
deleteBreakpoints(breakpointsInFile);
else if (act == editBreakpointAction)
- editBreakpoints(selectedIds);
+ editBreakpoints(selectedItems);
else if (act == associateBreakpointAction)
- associateBreakpoint(selectedIds, threadId);
+ associateBreakpoint(selectedItems, threadId);
else if (act == synchronizeAction)
; //synchronizeBreakpoints();
else if (act == toggleEnabledAction)
- setBreakpointsEnabled(selectedIds, !enabled);
+ setBreakpointsEnabled(selectedItems, !enabled);
else if (act == addBreakpointAction)
addBreakpoint();
}
-void BreakTreeView::setBreakpointsEnabled(const BreakpointModelIds &ids, bool enabled)
+void BreakTreeView::setBreakpointsEnabled(const Breakpoints &bps, bool enabled)
{
- BreakHandler *handler = breakHandler();
- foreach (const BreakpointModelId id, ids)
- handler->setEnabled(id, enabled);
+ foreach (Breakpoint b, bps)
+ b.setEnabled(enabled);
}
void BreakTreeView::deleteAllBreakpoints()
@@ -858,55 +851,56 @@ void BreakTreeView::deleteAllBreakpoints()
"from all files in the current session?"),
Core::ICore::settings(),
QLatin1String("RemoveAllBreakpoints")) == QDialogButtonBox::Yes)
- deleteBreakpoints(breakHandler()->allBreakpointIds());
+ deleteBreakpoints(breakHandler()->allBreakpoints());
}
-void BreakTreeView::deleteBreakpoints(const BreakpointModelIds &ids)
+void BreakTreeView::deleteBreakpoints(const Breakpoints &bps)
{
- BreakHandler *handler = breakHandler();
- foreach (const BreakpointModelId id, ids)
- handler->removeBreakpoint(id);
+ foreach (Breakpoint bp, bps)
+ bp.removeBreakpoint();
}
-void BreakTreeView::editBreakpoint(BreakpointModelId id, QWidget *parent)
+void BreakTreeView::editBreakpoint(Breakpoint bp, QWidget *parent)
{
- BreakpointParameters data = breakHandler()->breakpointData(id);
+ BreakpointParameters data = bp.parameters();
BreakpointParts parts = NoParts;
- BreakpointDialog dialog(id, parent);
- if (dialog.showDialog(&data, &parts))
- breakHandler()->changeBreakpointData(id, data, parts);
+
+ BreakpointDialog dialog(bp, parent);
+ if (!dialog.showDialog(&data, &parts))
+ return;
+
+ bp.changeBreakpointData(data);
}
void BreakTreeView::addBreakpoint()
{
BreakpointParameters data(BreakpointByFileAndLine);
BreakpointParts parts = NoParts;
- BreakpointDialog dialog(BreakpointModelId(), this);
+ BreakpointDialog dialog(Breakpoint(), this);
dialog.setWindowTitle(tr("Add Breakpoint"));
if (dialog.showDialog(&data, &parts))
breakHandler()->appendBreakpoint(data);
}
-void BreakTreeView::editBreakpoints(const BreakpointModelIds &ids)
+void BreakTreeView::editBreakpoints(const Breakpoints &bps)
{
- QTC_ASSERT(!ids.isEmpty(), return);
+ QTC_ASSERT(!bps.isEmpty(), return);
- const BreakpointModelId id = ids.at(0);
+ const Breakpoint bp = bps.at(0);
- if (ids.size() == 1) {
- editBreakpoint(id, this);
+ if (bps.size() == 1) {
+ editBreakpoint(bp, this);
return;
}
// This allows to change properties of multiple breakpoints at a time.
- BreakHandler *handler = breakHandler();
+ if (!bp)
+ return;
+
MultiBreakPointsDialog dialog;
- const QString oldCondition = QString::fromLatin1(handler->condition(id));
- dialog.setCondition(oldCondition);
- const int oldIgnoreCount = handler->ignoreCount(id);
- dialog.setIgnoreCount(oldIgnoreCount);
- const int oldThreadSpec = handler->threadSpec(id);
- dialog.setThreadSpec(oldThreadSpec);
+ dialog.setCondition(QString::fromLatin1(bp.condition()));
+ dialog.setIgnoreCount(bp.ignoreCount());
+ dialog.setThreadSpec(bp.threadSpec());
if (dialog.exec() == QDialog::Rejected)
return;
@@ -915,27 +909,27 @@ void BreakTreeView::editBreakpoints(const BreakpointModelIds &ids)
const int newIgnoreCount = dialog.ignoreCount();
const int newThreadSpec = dialog.threadSpec();
- if (newCondition == oldCondition && newIgnoreCount == oldIgnoreCount
- && newThreadSpec == oldThreadSpec)
- return;
-
- foreach (const BreakpointModelId id, ids) {
- handler->setCondition(id, newCondition.toLatin1());
- handler->setIgnoreCount(id, newIgnoreCount);
- handler->setThreadSpec(id, newThreadSpec);
+ foreach (Breakpoint bp, bps) {
+ if (bp) {
+ bp.setCondition(newCondition.toLatin1());
+ bp.setIgnoreCount(newIgnoreCount);
+ bp.setThreadSpec(newThreadSpec);
+ }
}
}
-void BreakTreeView::associateBreakpoint(const BreakpointModelIds &ids, int threadId)
+void BreakTreeView::associateBreakpoint(const Breakpoints &bps, int threadId)
{
- BreakHandler *handler = breakHandler();
- foreach (const BreakpointModelId id, ids)
- handler->setThreadSpec(id, threadId);
+ foreach (Breakpoint bp, bps) {
+ if (bp)
+ bp.setThreadSpec(threadId);
+ }
}
void BreakTreeView::rowActivated(const QModelIndex &index)
{
- breakHandler()->gotoLocation(breakHandler()->findBreakpointByIndex(index));
+ if (Breakpoint bp = breakHandler()->findBreakpointByIndex(index))
+ bp.gotoLocation();
}
} // namespace Internal
diff --git a/src/plugins/debugger/breakwindow.h b/src/plugins/debugger/breakwindow.h
index 5c9154859d8..f66d3e5eead 100644
--- a/src/plugins/debugger/breakwindow.h
+++ b/src/plugins/debugger/breakwindow.h
@@ -31,7 +31,7 @@
#ifndef DEBUGGER_BREAKWINDOW_H
#define DEBUGGER_BREAKWINDOW_H
-#include "breakpoint.h"
+#include "breakhandler.h"
#include <utils/basetreeview.h>
namespace Debugger {
@@ -44,7 +44,7 @@ class BreakTreeView : public Utils::BaseTreeView
public:
BreakTreeView();
- static void editBreakpoint(BreakpointModelId id, QWidget *parent);
+ static void editBreakpoint(Breakpoint bp, QWidget *parent);
private slots:
void showAddressColumn(bool on);
@@ -55,12 +55,12 @@ private:
void keyPressEvent(QKeyEvent *ev);
void mouseDoubleClickEvent(QMouseEvent *ev);
- void deleteBreakpoints(const BreakpointModelIds &ids);
+ void deleteBreakpoints(const Breakpoints &bps);
void deleteAllBreakpoints();
void addBreakpoint();
- void editBreakpoints(const BreakpointModelIds &ids);
- void associateBreakpoint(const BreakpointModelIds &ids, int thread);
- void setBreakpointsEnabled(const BreakpointModelIds &ids, bool enabled);
+ void editBreakpoints(const Breakpoints &bps);
+ void associateBreakpoint(const Breakpoints &bps, int thread);
+ void setBreakpointsEnabled(const Breakpoints &bps, bool enabled);
};
} // namespace Internal
diff --git a/src/plugins/debugger/cdb/cdbengine.cpp b/src/plugins/debugger/cdb/cdbengine.cpp
index cb210b8f8e6..a23fc804d72 100644
--- a/src/plugins/debugger/cdb/cdbengine.cpp
+++ b/src/plugins/debugger/cdb/cdbengine.cpp
@@ -55,6 +55,7 @@
#include <debugger/shared/hostutils.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <projectexplorer/taskhub.h>
#include <texteditor/texteditor.h>
@@ -72,7 +73,6 @@
#include <cpptools/cppworkingcopy.h>
#include <QDir>
-#include <QMessageBox>
#include <cctype>
@@ -340,17 +340,22 @@ CdbEngine::CdbEngine(const DebuggerStartParameters &sp) :
m_watchPointY(0),
m_ignoreCdbOutput(false)
{
- connect(action(OperateByInstruction), SIGNAL(triggered(bool)),
- this, SLOT(operateByInstructionTriggered(bool)));
- connect(action(VerboseLog), SIGNAL(triggered(bool)),
- this, SLOT(verboseLogTriggered(bool)));
- connect(action(CreateFullBacktrace), SIGNAL(triggered()),
- this, SLOT(createFullBacktrace()));
setObjectName(QLatin1String("CdbEngine"));
- connect(&m_process, SIGNAL(finished(int)), this, SLOT(processFinished()));
- connect(&m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(processError()));
- connect(&m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readyReadStandardOut()));
- connect(&m_process, SIGNAL(readyReadStandardError()), this, SLOT(readyReadStandardOut()));
+
+ connect(action(OperateByInstruction), &QAction::triggered,
+ this, &CdbEngine::operateByInstructionTriggered);
+ connect(action(VerboseLog), &QAction::triggered,
+ this, &CdbEngine::verboseLogTriggered);
+ connect(action(CreateFullBacktrace), &QAction::triggered,
+ this, &CdbEngine::createFullBacktrace);
+ connect(&m_process, static_cast<void(QProcess::*)(int)>(&QProcess::finished),
+ this, &CdbEngine::processFinished);
+ connect(&m_process, static_cast<void(QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
+ this, &CdbEngine::processError);
+ connect(&m_process, &QProcess::readyReadStandardOutput,
+ this, &CdbEngine::readyReadStandardOut);
+ connect(&m_process, &QProcess::readyReadStandardError,
+ this, &CdbEngine::readyReadStandardOut);
}
void CdbEngine::init()
@@ -534,7 +539,7 @@ void CdbEngine::consoleStubError(const QString &msg)
STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineIll")
notifyEngineIll();
}
- showMessageBox(QMessageBox::Critical, tr("Debugger Error"), msg);
+ Core::AsynchronousMessageBox::critical(tr("Debugger Error"), msg);
}
void CdbEngine::consoleStubProcessStarted()
@@ -552,7 +557,7 @@ void CdbEngine::consoleStubProcessStarted()
QString errorMessage;
if (!launchCDB(attachParameters, &errorMessage)) {
showMessage(errorMessage, LogError);
- showMessageBox(QMessageBox::Critical, tr("Failed to Start the Debugger"), errorMessage);
+ Core::AsynchronousMessageBox::critical(tr("Failed to Start the Debugger"), errorMessage);
STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSetupFailed")
notifyEngineSetupFailed();
}
@@ -599,7 +604,7 @@ void CdbEngine::setupEngine()
qDebug("<setupEngine ok=%d", ok);
if (!ok) {
showMessage(errorMessage, LogError);
- showMessageBox(QMessageBox::Critical, tr("Failed to Start the Debugger"), errorMessage);
+ Core::AsynchronousMessageBox::critical(tr("Failed to Start the Debugger"), errorMessage);
STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSetupFailed")
notifyEngineSetupFailed();
}
@@ -1235,14 +1240,12 @@ void CdbEngine::executeRunToFunction(const QString &functionName)
continueInferior();
}
-void CdbEngine::setRegisterValue(int regnr, const QString &value)
+void CdbEngine::setRegisterValue(const QByteArray &name, const QString &value)
{
- const Registers registers = registerHandler()->registers();
- QTC_ASSERT(regnr < registers.size(), return);
// Value is decimal or 0x-hex-prefixed
QByteArray cmd;
ByteArrayInputStream str(cmd);
- str << "r " << registers.at(regnr).name << '=' << value;
+ str << "r " << name << '=' << value;
postCommand(cmd, 0);
reloadRegisters();
}
@@ -1854,29 +1857,14 @@ void CdbEngine::handlePid(const CdbExtensionCommandPtr &reply)
}
}
-// Parse CDB gdbmi register syntax.
-static Register parseRegister(const GdbMi &gdbmiReg)
-{
- Register reg;
- reg.name = gdbmiReg["name"].data();
- const GdbMi description = gdbmiReg["description"];
- if (description.type() != GdbMi::Invalid) {
- reg.name += " (";
- reg.name += description.data();
- reg.name += ')';
- }
- reg.value = gdbmiReg["value"].data();
- return reg;
-}
-
void CdbEngine::handleModules(const CdbExtensionCommandPtr &reply)
{
if (reply->success) {
GdbMi value;
value.fromString(reply->reply);
if (value.type() == GdbMi::List) {
- Modules modules;
- modules.reserve(value.childCount());
+ ModulesHandler *handler = modulesHandler();
+ handler->beginUpdateAll();
foreach (const GdbMi &gdbmiModule, value.children()) {
Module module;
module.moduleName = QString::fromLatin1(gdbmiModule["name"].data());
@@ -1885,9 +1873,9 @@ void CdbEngine::handleModules(const CdbExtensionCommandPtr &reply)
module.endAddress = gdbmiModule["end"].data().toULongLong(0, 0);
if (gdbmiModule["deferred"].type() == GdbMi::Invalid)
module.symbolsRead = Module::ReadOk;
- modules.push_back(module);
+ handler->updateModule(module);
}
- modulesHandler()->setModules(modules);
+ handler->endUpdateAll();
} else {
showMessage(QString::fromLatin1("Parse error in modules response."), LogError);
qWarning("Parse error in modules response:\n%s", reply->reply.constData());
@@ -1906,11 +1894,17 @@ void CdbEngine::handleRegisters(const CdbExtensionCommandPtr &reply)
GdbMi value;
value.fromString(reply->reply);
if (value.type() == GdbMi::List) {
- Registers registers;
- registers.reserve(value.childCount());
- foreach (const GdbMi &gdbmiReg, value.children())
- registers.push_back(parseRegister(gdbmiReg));
- registerHandler()->setAndMarkRegisters(registers);
+ RegisterHandler *handler = registerHandler();
+ foreach (const GdbMi &item, value.children()) {
+ Register reg;
+ reg.name = item["name"].data();
+ reg.description = item["description"].data();
+ reg.reportedType = item["type"].data();
+ reg.value = item["value"].data();
+ reg.size = item["size"].data().toInt();
+ handler->updateRegister(reg);
+ }
+ handler->commitUpdates();
} else {
showMessage(QString::fromLatin1("Parse error in registers response."), LogError);
qWarning("Parse error in registers response:\n%s", reply->reply.constData());
@@ -1944,7 +1938,7 @@ void CdbEngine::handleLocals(const CdbExtensionCommandPtr &reply)
WatchData dummy;
dummy.iname = child["iname"].data();
dummy.name = QLatin1String(child["name"].data());
- parseWatchData(handler->expandedINames(), dummy, child, &watchData);
+ parseWatchData(dummy, child, &watchData);
}
// Fix the names of watch data.
for (int i =0; i < watchData.size(); ++i) {
@@ -2084,9 +2078,10 @@ unsigned CdbEngine::examineStopReason(const GdbMi &stopReason,
// Step out creates temporary breakpoints with id 10000.
int number = 0;
BreakpointModelId id = cdbIdToBreakpointModelId(stopReason["breakpointId"]);
- if (id.isValid()) {
- if (breakHandler()->engineBreakpointIds(this).contains(id)) {
- const BreakpointResponse parameters = breakHandler()->response(id);
+ Breakpoint bp = breakHandler()->breakpointById(id);
+ if (bp) {
+ if (bp.engine() == this) {
+ const BreakpointResponse parameters = bp.response();
if (!parameters.message.isEmpty()) {
showMessage(parameters.message + QLatin1Char('\n'), AppOutput);
showMessage(parameters.message, LogMisc);
@@ -2107,16 +2102,16 @@ unsigned CdbEngine::examineStopReason(const GdbMi &stopReason,
return StopReportLog;
}
} else {
- id = BreakpointModelId();
+ bp = Breakpoint();
}
}
QString tid = QString::number(threadId);
- if (id && breakHandler()->type(id) == WatchpointAtAddress)
- *message = msgWatchpointByAddressTriggered(id, number, breakHandler()->address(id), tid);
- else if (id && breakHandler()->type(id) == WatchpointAtExpression)
- *message = msgWatchpointByExpressionTriggered(id, number, breakHandler()->expression(id), tid);
+ if (bp.type() == WatchpointAtAddress)
+ *message = bp.msgWatchpointByAddressTriggered(number, bp.address(), tid);
+ else if (bp.type() == WatchpointAtExpression)
+ *message = bp.msgWatchpointByExpressionTriggered(number, bp.expression(), tid);
else
- *message = msgBreakpointTriggered(id, number, tid);
+ *message = bp.msgBreakpointTriggered(number, tid);
rc |= StopReportStatusMessage|StopNotifyStop;
return rc;
}
@@ -2328,6 +2323,7 @@ void CdbEngine::handleBreakInsert(const CdbBuiltinCommandPtr &cmd)
if (!ok)
return;
const BreakpointModelId &originalId = cdbIdToBreakpointModelId(cdbBreakPointId);
+ Breakpoint bp = breakHandler()->breakpointById(originalId);
// add break point for every match
const QList<QByteArray>::const_iterator &end = reply.constEnd();
int subBreakPointID = 0;
@@ -2347,7 +2343,7 @@ void CdbEngine::handleBreakInsert(const CdbBuiltinCommandPtr &cmd)
continue;
BreakpointModelId id(originalId.majorPart(), ++subBreakPointID);
- BreakpointResponse res = breakHandler()->response(originalId);
+ BreakpointResponse res = bp.response();
res.type = BreakpointByAddress;
res.address = address;
m_insertSubBreakpointMap.insert(id, res);
@@ -2759,12 +2755,11 @@ bool CdbEngine::stateAcceptsBreakpointChanges() const
return false;
}
-bool CdbEngine::acceptsBreakpoint(BreakpointModelId id) const
+bool CdbEngine::acceptsBreakpoint(Breakpoint bp) const
{
- const BreakpointParameters &data = breakHandler()->breakpointData(id);
- if (!data.isCppBreakpoint())
+ if (!bp.parameters().isCppBreakpoint())
return false;
- switch (data.type) {
+ switch (bp.type()) {
case UnknownBreakpointType:
case LastBreakpointType:
case BreakpointAtFork:
@@ -2838,23 +2833,21 @@ unsigned BreakpointCorrectionContext::fixLineNumber(const QString &fileName,
void CdbEngine::attemptBreakpointSynchronization()
{
-
-
if (debug)
qDebug("attemptBreakpointSynchronization in %s", stateName(state()));
// Check if there is anything to be done at all.
BreakHandler *handler = breakHandler();
// Take ownership of the breakpoint. Requests insertion. TODO: Cpp only?
- foreach (BreakpointModelId id, handler->unclaimedBreakpointIds())
- if (acceptsBreakpoint(id))
- handler->setEngine(id, this);
+ foreach (Breakpoint bp, handler->unclaimedBreakpoints())
+ if (acceptsBreakpoint(bp))
+ bp.setEngine(this);
// Quick check: is there a need to change something? - Populate module cache
bool changed = !m_insertSubBreakpointMap.isEmpty();
- const BreakpointModelIds ids = handler->engineBreakpointIds(this);
+ const Breakpoints bps = handler->engineBreakpoints(this);
if (!changed) {
- foreach (BreakpointModelId id, ids) {
- switch (handler->state(id)) {
+ foreach (Breakpoint bp, bps) {
+ switch (bp.state()) {
case BreakpointInsertRequested:
case BreakpointRemoveRequested:
case BreakpointChangeRequested:
@@ -2863,7 +2856,7 @@ void CdbEngine::attemptBreakpointSynchronization()
case BreakpointInserted: {
// Collect the new modules matching the files.
// In the future, that information should be obtained from the build system.
- const BreakpointParameters &data = handler->breakpointData(id);
+ const BreakpointParameters &data = bp.parameters();
if (data.type == BreakpointByFileAndLine && !data.module.isEmpty())
m_fileNameModuleHash.insert(data.fileName, data.module);
}
@@ -2876,7 +2869,7 @@ void CdbEngine::attemptBreakpointSynchronization()
if (debugBreakpoints)
qDebug("attemptBreakpointSynchronizationI %dms accessible=%d, %s %d breakpoints, changed=%d",
- elapsedLogTime(), m_accessible, stateName(state()), ids.size(), changed);
+ elapsedLogTime(), m_accessible, stateName(state()), bps.size(), changed);
if (!changed)
return;
@@ -2891,8 +2884,9 @@ void CdbEngine::attemptBreakpointSynchronization()
// handleBreakPoints will the complete that information and set it on the break handler.
bool addedChanged = false;
QScopedPointer<BreakpointCorrectionContext> lineCorrection;
- foreach (BreakpointModelId id, ids) {
- BreakpointParameters parameters = handler->breakpointData(id);
+ foreach (Breakpoint bp, bps) {
+ BreakpointParameters parameters = bp.parameters();
+ BreakpointModelId id = bp.id();
BreakpointResponse response;
response.fromParameters(parameters);
response.id = BreakpointResponseId(id.majorPart(), id.minorPart());
@@ -2902,7 +2896,7 @@ void CdbEngine::attemptBreakpointSynchronization()
if (it != m_fileNameModuleHash.constEnd())
parameters.module = it.value();
}
- switch (handler->state(id)) {
+ switch (bp.state()) {
case BreakpointInsertRequested:
if (!m_autoBreakPointCorrection
&& parameters.type == BreakpointByFileAndLine
@@ -2921,29 +2915,29 @@ void CdbEngine::attemptBreakpointSynchronization()
}
if (!parameters.enabled)
postCommand("bd " + QByteArray::number(breakPointIdToCdbId(id)), 0);
- handler->notifyBreakpointInsertProceeding(id);
- handler->notifyBreakpointInsertOk(id);
+ bp.notifyBreakpointInsertProceeding();
+ bp.notifyBreakpointInsertOk();
m_pendingBreakpointMap.insert(id, response);
addedChanged = true;
// Ensure enabled/disabled is correct in handler and line number is there.
- handler->setResponse(id, response);
+ bp.setResponse(response);
if (debugBreakpoints)
qDebug("Adding %d %s\n", id.toInternalId(),
qPrintable(response.toString()));
break;
case BreakpointChangeRequested:
- handler->notifyBreakpointChangeProceeding(id);
+ bp.notifyBreakpointChangeProceeding();
if (debugBreakpoints)
qDebug("Changing %d:\n %s\nTo %s\n", id.toInternalId(),
- qPrintable(handler->response(id).toString()),
+ qPrintable(bp.response().toString()),
qPrintable(parameters.toString()));
- if (parameters.enabled != handler->response(id).enabled) {
+ if (parameters.enabled != bp.response().enabled) {
// Change enabled/disabled breakpoints without triggering update.
postCommand((parameters.enabled ? "be " : "bd ")
+ QByteArray::number(breakPointIdToCdbId(id)), 0);
response.pending = false;
response.enabled = parameters.enabled;
- handler->setResponse(id, response);
+ bp.setResponse(response);
} else {
// Delete and re-add, triggering update
addedChanged = true;
@@ -2953,12 +2947,12 @@ void CdbEngine::attemptBreakpointSynchronization()
&CdbEngine::handleBreakInsert);
m_pendingBreakpointMap.insert(id, response);
}
- handler->notifyBreakpointChangeOk(id);
+ bp.notifyBreakpointChangeOk();
break;
case BreakpointRemoveRequested:
postCommand(cdbClearBreakpointCommand(id), 0);
- handler->notifyBreakpointRemoveProceeding(id);
- handler->notifyBreakpointRemoveOk(id);
+ bp.notifyBreakpointRemoveProceeding();
+ bp.notifyBreakpointRemoveOk();
m_pendingBreakpointMap.remove(id);
break;
default:
@@ -2991,7 +2985,7 @@ CdbEngine::NormalizedSourceFileName CdbEngine::sourceMapNormalizeFileNameFromDeb
const QString fileName = cdbSourcePathMapping(QDir::toNativeSeparators(f), m_sourcePathMappings,
DebuggerToSource);
// Up/lower case normalization according to Windows.
- const QString normalized = Utils::FileUtils::normalizePathName(fileName);
+ const QString normalized = FileUtils::normalizePathName(fileName);
if (debugSourceMapping)
qDebug(" sourceMapNormalizeFileNameFromDebugger %s->%s", qPrintable(fileName), qPrintable(normalized));
// Check if it really exists, that is normalize worked and QFileInfo confirms it.
@@ -3301,12 +3295,12 @@ void CdbEngine::handleBreakPoints(const GdbMi &value)
reportedResponse.pending,
qPrintable(reportedResponse.toString()));
if (reportedResponse.id.isValid() && !reportedResponse.pending) {
- const BreakpointModelId mid = handler->findBreakpointByResponseId(reportedResponse.id);
- if (!mid.isValid() && reportedResponse.type == BreakpointByFunction)
+ Breakpoint bp = handler->findBreakpointByResponseId(reportedResponse.id);
+ if (!bp && reportedResponse.type == BreakpointByFunction)
continue; // Breakpoints from options, CrtDbgReport() and others.
- QTC_ASSERT(mid.isValid(), continue);
- const PendingBreakPointMap::iterator it = m_pendingBreakpointMap.find(mid);
- const PendingBreakPointMap::iterator subIt = m_pendingSubBreakpointMap.find(
+ QTC_ASSERT(bp, continue);
+ const auto it = m_pendingBreakpointMap.find(bp.id());
+ const auto subIt = m_pendingSubBreakpointMap.find(
BreakpointModelId(reportedResponse.id.majorPart(),
reportedResponse.id.minorPart()));
if (it != m_pendingBreakpointMap.end() || subIt != m_pendingSubBreakpointMap.end()) {
@@ -3321,16 +3315,16 @@ void CdbEngine::handleBreakPoints(const GdbMi &value)
currentResponse.enabled = reportedResponse.enabled;
currentResponse.fileName = reportedResponse.fileName;
currentResponse.lineNumber = reportedResponse.lineNumber;
- formatCdbBreakPointResponse(mid, currentResponse, str);
+ formatCdbBreakPointResponse(bp.id(), currentResponse, str);
if (debugBreakpoints)
qDebug(" Setting for %d: %s\n", currentResponse.id.majorPart(),
qPrintable(currentResponse.toString()));
if (it != m_pendingBreakpointMap.end()) {
- handler->setResponse(mid, currentResponse);
+ bp.setResponse(currentResponse);
m_pendingBreakpointMap.erase(it);
}
if (subIt != m_pendingSubBreakpointMap.end()) {
- handler->insertSubBreakpoint(mid, currentResponse);
+ bp.insertSubBreakpoint(currentResponse);
m_pendingSubBreakpointMap.erase(subIt);
}
}
diff --git a/src/plugins/debugger/cdb/cdbengine.h b/src/plugins/debugger/cdb/cdbengine.h
index cf2cb6ced6a..ce7f263e63e 100644
--- a/src/plugins/debugger/cdb/cdbengine.h
+++ b/src/plugins/debugger/cdb/cdbengine.h
@@ -32,6 +32,7 @@
#define DEBUGGER_CDBENGINE_H
#include <debugger/debuggerengine.h>
+#include <debugger/breakhandler.h>
#include <projectexplorer/devicesupport/idevice.h>
@@ -52,7 +53,7 @@ struct MemoryViewCookie;
class ByteArrayInputStream;
class GdbMi;
-class CdbEngine : public Debugger::DebuggerEngine
+class CdbEngine : public DebuggerEngine
{
Q_OBJECT
@@ -90,7 +91,7 @@ public:
const WatchUpdateFlags & flags = WatchUpdateFlags());
virtual bool hasCapability(unsigned cap) const;
virtual void watchPoint(const QPoint &);
- virtual void setRegisterValue(int regnr, const QString &value);
+ virtual void setRegisterValue(const QByteArray &name, const QString &value);
virtual void executeStep();
virtual void executeStepOut();
@@ -111,7 +112,7 @@ public:
virtual void selectThread(ThreadId threadId);
virtual bool stateAcceptsBreakpointChanges() const;
- virtual bool acceptsBreakpoint(BreakpointModelId id) const;
+ virtual bool acceptsBreakpoint(Breakpoint bp) const;
virtual void attemptBreakpointSynchronization();
virtual void fetchDisassembler(DisassemblerAgent *agent);
diff --git a/src/plugins/debugger/cdb/cdbparsehelpers.cpp b/src/plugins/debugger/cdb/cdbparsehelpers.cpp
index 75b2870a112..57c19eb5eea 100644
--- a/src/plugins/debugger/cdb/cdbparsehelpers.cpp
+++ b/src/plugins/debugger/cdb/cdbparsehelpers.cpp
@@ -37,6 +37,7 @@
#include <debugger/shared/hostutils.h>
#include <debugger/threaddata.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QDir>
@@ -87,7 +88,7 @@ static inline QString cdbBreakPointFileName(const BreakpointParameters &bp,
if (bp.fileName.isEmpty())
return bp.fileName;
if (bp.pathUsage == BreakpointUseShortPath)
- return QFileInfo(bp.fileName).fileName();
+ return Utils::FileName::fromString(bp.fileName).fileName();
return cdbSourcePathMapping(QDir::toNativeSeparators(bp.fileName), sourcePathMapping, SourceToDebugger);
}
diff --git a/src/plugins/debugger/commonoptionspage.cpp b/src/plugins/debugger/commonoptionspage.cpp
index 6aef1913e68..31f7e5c161d 100644
--- a/src/plugins/debugger/commonoptionspage.cpp
+++ b/src/plugins/debugger/commonoptionspage.cpp
@@ -230,8 +230,8 @@ CommonOptionsPageWidget::CommonOptionsPageWidget
Utils::SavedAction *registerAction = action(RegisterForPostMortem);
m_group->insert(registerAction,
checkBoxRegisterForPostMortem);
- connect(registerAction, SIGNAL(toggled(bool)),
- checkBoxRegisterForPostMortem, SLOT(setChecked(bool)));
+ connect(registerAction, &QAction::toggled,
+ checkBoxRegisterForPostMortem, &QAbstractButton::setChecked);
} else {
checkBoxRegisterForPostMortem->setVisible(false);
}
diff --git a/src/plugins/debugger/debugger.pro b/src/plugins/debugger/debugger.pro
index edf9a727093..83e790c0427 100644
--- a/src/plugins/debugger/debugger.pro
+++ b/src/plugins/debugger/debugger.pro
@@ -15,7 +15,6 @@ CONFIG += exceptions
HEADERS += \
breakhandler.h \
breakpoint.h \
- breakpointmarker.h \
breakwindow.h \
commonoptionspage.h \
debugger_global.h \
@@ -25,7 +24,6 @@ HEADERS += \
debuggerinternalconstants.h \
debuggeritem.h \
debuggeritemmanager.h \
- debuggeritemmodel.h \
debuggerdialogs.h \
debuggerengine.h \
debuggermainwindow.h \
@@ -58,6 +56,7 @@ HEADERS += \
stackframe.h \
stackhandler.h \
stackwindow.h \
+ terminal.h \
threadswindow.h \
watchhandler.h \
watchutils.h \
@@ -76,7 +75,6 @@ HEADERS += \
SOURCES += \
breakhandler.cpp \
breakpoint.cpp \
- breakpointmarker.cpp \
breakwindow.cpp \
commonoptionspage.cpp \
debuggeractions.cpp \
@@ -84,7 +82,6 @@ SOURCES += \
debuggerengine.cpp \
debuggeritem.cpp \
debuggeritemmanager.cpp \
- debuggeritemmodel.cpp \
debuggermainwindow.cpp \
debuggerplugin.cpp \
debuggerprotocol.cpp \
@@ -114,6 +111,7 @@ SOURCES += \
stackwindow.cpp \
threadshandler.cpp \
threadswindow.cpp \
+ terminal.cpp \
watchdata.cpp \
watchhandler.cpp \
watchutils.cpp \
diff --git a/src/plugins/debugger/debugger.qbs b/src/plugins/debugger/debugger.qbs
index e03c038beb8..7001f560b3f 100644
--- a/src/plugins/debugger/debugger.qbs
+++ b/src/plugins/debugger/debugger.qbs
@@ -28,7 +28,6 @@ QtcPlugin {
files: [
"breakhandler.cpp", "breakhandler.h",
"breakpoint.cpp", "breakpoint.h",
- "breakpointmarker.cpp", "breakpointmarker.h",
"breakwindow.cpp", "breakwindow.h",
"commonoptionspage.cpp", "commonoptionspage.h",
"debugger.qrc",
@@ -41,7 +40,6 @@ QtcPlugin {
"debuggerinternalconstants.h",
"debuggeritem.cpp", "debuggeritem.h",
"debuggeritemmanager.cpp", "debuggeritemmanager.h",
- "debuggeritemmodel.cpp", "debuggeritemmodel.h",
"debuggerkitconfigwidget.cpp", "debuggerkitconfigwidget.h",
"debuggerkitinformation.cpp", "debuggerkitinformation.h",
"debuggermainwindow.cpp", "debuggermainwindow.h",
@@ -77,6 +75,7 @@ QtcPlugin {
"stackframe.cpp", "stackframe.h",
"stackhandler.cpp", "stackhandler.h",
"stackwindow.cpp", "stackwindow.h",
+ "terminal.cpp", "terminal.h",
"threaddata.h",
"threadshandler.cpp", "threadshandler.h",
"threadswindow.cpp", "threadswindow.h",
diff --git a/src/plugins/debugger/debuggeractions.cpp b/src/plugins/debugger/debuggeractions.cpp
index 234c44e4340..e58367e4798 100644
--- a/src/plugins/debugger/debuggeractions.cpp
+++ b/src/plugins/debugger/debuggeractions.cpp
@@ -34,6 +34,7 @@
#include "registerpostmortemaction.h"
#endif
+#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <utils/savedaction.h>
#include <utils/qtcassert.h>
@@ -184,6 +185,18 @@ DebuggerSettings::DebuggerSettings()
insertItem(OperateByInstruction, item);
item = new SavedAction(this);
+ item->setText(tr("Native Mixed Mode"));
+ item->setCheckable(true);
+ item->setDefaultValue(true);
+ item->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
+ item->setToolTip(tr("This switches the debugger to native-mixed "
+ "operation mode. In this mode, stepping and data display will "
+ "be handled by the native debugger backend (GDB, LLDB or CDB) "
+ "for C++, QML and JS sources."));
+ item->setIconVisibleInMenu(false);
+ insertItem(OperateNativeMixed, item);
+
+ item = new SavedAction(this);
item->setText(tr("Dereference Pointers Automatically"));
item->setCheckable(true);
item->setDefaultValue(true);
diff --git a/src/plugins/debugger/debuggeractions.h b/src/plugins/debugger/debuggeractions.h
index 99ffa70b50e..2b3202fcd5a 100644
--- a/src/plugins/debugger/debuggeractions.h
+++ b/src/plugins/debugger/debuggeractions.h
@@ -99,6 +99,7 @@ enum DebuggerActionCode
LogTimeStamps,
VerboseLog,
OperateByInstruction,
+ OperateNativeMixed,
CloseSourceBuffersOnExit,
CloseMemoryBuffersOnExit,
SwitchModeOnExit,
diff --git a/src/plugins/debugger/debuggerconstants.h b/src/plugins/debugger/debuggerconstants.h
index 0b1270225b1..0bfb5f749b2 100644
--- a/src/plugins/debugger/debuggerconstants.h
+++ b/src/plugins/debugger/debuggerconstants.h
@@ -61,6 +61,7 @@ const char NEXT[] = "Debugger.NextLine";
const char REVERSE[] = "Debugger.ReverseDirection";
const char RESET[] = "Debugger.Reset";
const char OPERATE_BY_INSTRUCTION[] = "Debugger.OperateByInstruction";
+const char OPERATE_NATIVE_MIXED[] = "Debugger.OperateNativeMixed";
const char QML_SHOW_APP_ON_TOP[] = "Debugger.QmlShowAppOnTop";
const char QML_UPDATE_ON_SAVE[] = "Debugger.QmlUpdateOnSave";
const char QML_SELECTTOOL[] = "Debugger.QmlSelectTool";
@@ -163,7 +164,8 @@ enum DebuggerCapabilities
ShowModuleSectionsCapability = 0x200000,
WatchComplexExpressionsCapability = 0x400000, // Used to filter out challenges for cdb.
AdditionalQmlStackCapability = 0x800000, // C++ debugger engine is able to retrieve QML stack as well.
- ResetInferiorCapability = 0x1000000 //!< restart program while debugging
+ ResetInferiorCapability = 0x1000000, //!< restart program while debugging
+ NativeMixedCapability = 0x2000000
};
enum LogChannel
diff --git a/src/plugins/debugger/debuggercore.h b/src/plugins/debugger/debuggercore.h
index 84b29f7ab6b..d4818670621 100644
--- a/src/plugins/debugger/debuggercore.h
+++ b/src/plugins/debugger/debuggercore.h
@@ -50,12 +50,10 @@ namespace CPlusPlus { class Snapshot; }
namespace Utils { class SavedAction; }
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
class BreakHandler;
+class DebuggerEngine;
class Symbol;
class Section;
class GlobalDebuggerOptions;
@@ -112,6 +110,9 @@ DebuggerEngine *currentEngine();
QMessageBox *showMessageBox(int icon, const QString &title,
const QString &text, int buttons = 0);
+bool isNativeMixedActive();
+bool isNativeMixedEnabled();
+
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/debuggerdialogs.cpp b/src/plugins/debugger/debuggerdialogs.cpp
index b6e9f937c32..fd4137f78c4 100644
--- a/src/plugins/debugger/debuggerdialogs.cpp
+++ b/src/plugins/debugger/debuggerdialogs.cpp
@@ -105,19 +105,19 @@ namespace Internal {
///////////////////////////////////////////////////////////////////////
DebuggerKitChooser::DebuggerKitChooser(Mode mode, QWidget *parent)
- : ProjectExplorer::KitChooser(parent)
- , m_hostAbi(ProjectExplorer::Abi::hostAbi())
+ : KitChooser(parent)
+ , m_hostAbi(Abi::hostAbi())
, m_mode(mode)
{
}
// Match valid debuggers and restrict local debugging to compatible toolchains.
-bool DebuggerKitChooser::kitMatches(const ProjectExplorer::Kit *k) const
+bool DebuggerKitChooser::kitMatches(const Kit *k) const
{
if (!DebuggerKitInformation::isValidDebugger(k))
return false;
if (m_mode == LocalDebugging) {
- const ProjectExplorer::ToolChain *tc = ToolChainKitInformation::toolChain(k);
+ const ToolChain *tc = ToolChainKitInformation::toolChain(k);
return tc && tc->targetAbi().os() == m_hostAbi.os();
}
return true;
@@ -181,7 +181,7 @@ QString StartApplicationParameters::displayName() const
{
const int maxLength = 60;
- QString name = QFileInfo(localExecutable).fileName() + QLatin1Char(' ') + processArgs;
+ QString name = FileName::fromString(localExecutable).fileName() + QLatin1Char(' ') + processArgs;
if (name.size() > 60) {
int index = name.lastIndexOf(QLatin1Char(' '), maxLength);
if (index == -1)
@@ -247,7 +247,7 @@ StartApplicationDialog::StartApplicationDialog(QWidget *parent)
d->serverAddressEdit = new QLineEdit(this);
d->localExecutablePathChooser = new PathChooser(this);
- d->localExecutablePathChooser->setExpectedKind(PathChooser::File);
+ d->localExecutablePathChooser->setExpectedKind(PathChooser::ExistingCommand);
d->localExecutablePathChooser->setPromptDialogTitle(tr("Select Executable"));
d->localExecutablePathChooser->setHistoryCompleter(QLatin1String("LocalExecutable"));
@@ -282,11 +282,11 @@ StartApplicationDialog::StartApplicationDialog(QWidget *parent)
"If empty, $SYSROOT/usr/lib/debug will be chosen."));
d->debuginfoPathChooser->setHistoryCompleter(QLatin1String("Debugger.DebugLocation.History"));
- QFrame *line = new QFrame(this);
+ auto line = new QFrame(this);
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
- QFrame *line2 = new QFrame(this);
+ auto line2 = new QFrame(this);
line2->setFrameShape(QFrame::HLine);
line2->setFrameShadow(QFrame::Sunken);
@@ -296,7 +296,7 @@ StartApplicationDialog::StartApplicationDialog(QWidget *parent)
d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
d->buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);
- QFormLayout *formLayout = new QFormLayout();
+ auto formLayout = new QFormLayout();
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
formLayout->addRow(tr("&Kit:"), d->kitChooser);
formLayout->addRow(d->serverPortLabel, d->serverPortSpinBox);
@@ -311,17 +311,18 @@ StartApplicationDialog::StartApplicationDialog(QWidget *parent)
formLayout->addRow(line2);
formLayout->addRow(tr("&Recent:"), d->historyComboBox);
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
+ auto verticalLayout = new QVBoxLayout(this);
verticalLayout->addLayout(formLayout);
verticalLayout->addStretch();
verticalLayout->addWidget(line);
verticalLayout->addWidget(d->buttonBox);
- connect(d->localExecutablePathChooser, SIGNAL(changed(QString)), SLOT(updateState()));
- connect(d->buttonBox, SIGNAL(accepted()), SLOT(accept()));
- connect(d->buttonBox, SIGNAL(rejected()), SLOT(reject()));
- connect(d->historyComboBox, SIGNAL(currentIndexChanged(int)),
- SLOT(historyIndexChanged(int)));
+ connect(d->localExecutablePathChooser, &PathChooser::changed,
+ this, &StartApplicationDialog::updateState);
+ connect(d->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(d->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ connect(d->historyComboBox, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &StartApplicationDialog::historyIndexChanged);
updateState();
}
@@ -493,20 +494,20 @@ AttachToQmlPortDialog::AttachToQmlPortDialog(QWidget *parent)
d->portSpinBox->setMaximum(65535);
d->portSpinBox->setValue(3768);
- QDialogButtonBox *buttonBox = new QDialogButtonBox(this);
+ auto buttonBox = new QDialogButtonBox(this);
buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
buttonBox->button(QDialogButtonBox::Ok)->setDefault(true);
- QFormLayout *formLayout = new QFormLayout();
+ auto formLayout = new QFormLayout();
formLayout->addRow(tr("Kit:"), d->kitChooser);
formLayout->addRow(tr("&Port:"), d->portSpinBox);
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
+ auto verticalLayout = new QVBoxLayout(this);
verticalLayout->addLayout(formLayout);
verticalLayout->addWidget(buttonBox);
- connect(buttonBox, SIGNAL(accepted()), SLOT(accept()));
- connect(buttonBox, SIGNAL(rejected()), SLOT(reject()));
+ connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
AttachToQmlPortDialog::~AttachToQmlPortDialog()
@@ -567,34 +568,38 @@ StartRemoteCdbDialog::StartRemoteCdbDialog(QWidget *parent) :
setWindowTitle(tr("Start a CDB Remote Session"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
- QGroupBox *groupBox = new QGroupBox;
+ auto groupBox = new QGroupBox;
- QLabel *helpLabel = new QLabel(cdbRemoteHelp());
+ auto helpLabel = new QLabel(cdbRemoteHelp());
helpLabel->setWordWrap(true);
helpLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
- QLabel *label = new QLabel(tr("&Connection:"));
+ auto label = new QLabel(tr("&Connection:"));
label->setBuddy(m_lineEdit);
m_lineEdit->setMinimumWidth(400);
- QDialogButtonBox *box = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
+ auto box = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
- QFormLayout *formLayout = new QFormLayout;
+ auto formLayout = new QFormLayout;
formLayout->addRow(helpLabel);
formLayout->addRow(label, m_lineEdit);
groupBox->setLayout(formLayout);
- QVBoxLayout *vLayout = new QVBoxLayout(this);
+ auto vLayout = new QVBoxLayout(this);
vLayout->addWidget(groupBox);
vLayout->addWidget(box);
m_okButton = box->button(QDialogButtonBox::Ok);
m_okButton->setEnabled(false);
- connect(m_lineEdit, SIGNAL(textChanged(QString)), this, SLOT(textChanged(QString)));
- connect(m_lineEdit, SIGNAL(returnPressed()), m_okButton, SLOT(animateClick()));
- connect(box, SIGNAL(accepted()), this, SLOT(accept()));
- connect(box, SIGNAL(rejected()), this, SLOT(reject()));
+ connect(m_lineEdit, &QLineEdit::textChanged,
+ this, &StartRemoteCdbDialog::textChanged);
+ connect(m_lineEdit, &QLineEdit::returnPressed,
+ [this] { m_okButton->animateClick(); });
+ connect(box, &QDialogButtonBox::accepted,
+ this, &StartRemoteCdbDialog::accept);
+ connect(box, &QDialogButtonBox::rejected,
+ this, &QDialog::reject);
}
void StartRemoteCdbDialog::accept()
@@ -636,18 +641,20 @@ AddressDialog::AddressDialog(QWidget *parent) :
{
setWindowTitle(tr("Select Start Address"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
- QHBoxLayout *hLayout = new QHBoxLayout;
+
+ auto hLayout = new QHBoxLayout;
hLayout->addWidget(new QLabel(tr("Enter an address:") + QLatin1Char(' ')));
hLayout->addWidget(m_lineEdit);
- QVBoxLayout *vLayout = new QVBoxLayout;
+
+ auto vLayout = new QVBoxLayout;
vLayout->addLayout(hLayout);
vLayout->addWidget(m_box);
setLayout(vLayout);
- connect(m_box, SIGNAL(accepted()), this, SLOT(accept()));
- connect(m_box, SIGNAL(rejected()), this, SLOT(reject()));
- connect(m_lineEdit, SIGNAL(returnPressed()), this, SLOT(accept()));
- connect(m_lineEdit, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
+ connect(m_box, &QDialogButtonBox::accepted, this, &AddressDialog::accept);
+ connect(m_box, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ connect(m_lineEdit, &QLineEdit::returnPressed, this, &AddressDialog::accept);
+ connect(m_lineEdit, &QLineEdit::textChanged, this, &AddressDialog::textChanged);
setOkButtonEnabled(false);
}
@@ -732,20 +739,20 @@ StartRemoteEngineDialog::StartRemoteEngineDialog(QWidget *parent)
d->buttonBox = new QDialogButtonBox(this);
d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
- QFormLayout *formLayout = new QFormLayout();
+ auto formLayout = new QFormLayout();
formLayout->addRow(tr("&Host:"), d->host);
formLayout->addRow(tr("&Username:"), d->username);
formLayout->addRow(tr("&Password:"), d->password);
formLayout->addRow(tr("&Engine path:"), d->enginePath);
formLayout->addRow(tr("&Inferior path:"), d->inferiorPath);
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
+ auto verticalLayout = new QVBoxLayout(this);
verticalLayout->addLayout(formLayout);
verticalLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
verticalLayout->addWidget(d->buttonBox);
- connect(d->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
- connect(d->buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
+ connect(d->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(d->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
StartRemoteEngineDialog::~StartRemoteEngineDialog()
diff --git a/src/plugins/debugger/debuggerengine.cpp b/src/plugins/debugger/debuggerengine.cpp
index a0b2d2d6d75..d79bee0df09 100644
--- a/src/plugins/debugger/debuggerengine.cpp
+++ b/src/plugins/debugger/debuggerengine.cpp
@@ -45,6 +45,7 @@
#include "registerhandler.h"
#include "sourcefileshandler.h"
#include "stackhandler.h"
+#include "terminal.h"
#include "threadshandler.h"
#include "watchhandler.h"
#include <debugger/shared/peutils.h>
@@ -52,6 +53,7 @@
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
@@ -72,8 +74,6 @@
#include <QFileInfo>
#include <QDir>
-#include <QMessageBox>
-
using namespace Core;
using namespace Debugger::Internal;
using namespace ProjectExplorer;
@@ -100,18 +100,6 @@ const char PrefixDebugExecutable[] = "DebuggedExecutable";
namespace Debugger {
-Internal::Location::Location(const StackFrame &frame, bool marker)
-{
- init();
- m_fileName = frame.file;
- m_lineNumber = frame.line;
- m_needsMarker = marker;
- m_functionName = frame.function;
- m_hasDebugInfo = frame.isUsable();
- m_address = frame.address;
- m_from = frame.from;
-}
-
QDebug operator<<(QDebug d, DebuggerState state)
{
//return d << DebuggerEngine::stateName(state) << '(' << int(state) << ')';
@@ -134,6 +122,20 @@ QDebug operator<<(QDebug str, const DebuggerStartParameters &sp)
return str;
}
+namespace Internal {
+
+Location::Location(const StackFrame &frame, bool marker)
+{
+ init();
+ m_fileName = frame.file;
+ m_lineNumber = frame.line;
+ m_needsMarker = marker;
+ m_functionName = frame.function;
+ m_hasDebugInfo = frame.isUsable();
+ m_address = frame.address;
+ m_from = frame.from;
+}
+
//////////////////////////////////////////////////////////////////////
//
@@ -175,9 +177,12 @@ public:
m_memoryAgent(engine),
m_isStateDebugging(false)
{
- connect(&m_locationTimer, SIGNAL(timeout()), SLOT(resetLocation()));
- connect(action(IntelFlavor), SIGNAL(valueChanged(QVariant)),
- SLOT(reloadDisassembly()));
+ connect(&m_locationTimer, &QTimer::timeout,
+ this, &DebuggerEnginePrivate::resetLocation);
+ connect(action(IntelFlavor), &Utils::SavedAction::valueChanged,
+ this, &DebuggerEnginePrivate::reloadDisassembly);
+ connect(action(OperateNativeMixed), &QAction::triggered,
+ engine, &DebuggerEngine::reloadFullStack);
Utils::globalMacroExpander()->registerFileVariables(PrefixDebugExecutable,
tr("Debugged executable"),
@@ -298,6 +303,7 @@ public:
// State of RemoteSetup signal/slots.
RemoteSetupState m_remoteSetupState;
+ Terminal m_terminal;
qint64 m_inferiorPid;
ModulesHandler m_modulesHandler;
@@ -310,7 +316,7 @@ public:
DisassemblerAgent m_disassemblerAgent;
MemoryAgent m_memoryAgent;
- QScopedPointer<TextEditor::TextMark> m_locationMark;
+ QScopedPointer<TextMark> m_locationMark;
QTimer m_locationTimer;
bool m_isStateDebugging;
@@ -476,9 +482,9 @@ void DebuggerEngine::changeMemory(MemoryAgent *, QObject *,
Q_UNUSED(data);
}
-void DebuggerEngine::setRegisterValue(int regnr, const QString &value)
+void DebuggerEngine::setRegisterValue(const QByteArray &name, const QString &value)
{
- Q_UNUSED(regnr);
+ Q_UNUSED(name);
Q_UNUSED(value);
}
@@ -520,7 +526,7 @@ void DebuggerEngine::startDebugger(DebuggerRunControl *runControl)
d->m_progress.setProgressRange(0, 1000);
FutureProgress *fp = ProgressManager::addTask(d->m_progress.future(),
tr("Launching Debugger"), "Debugger.Launcher");
- connect(fp, SIGNAL(canceled()), this, SLOT(quitDebugger()));
+ connect(fp, &FutureProgress::canceled, this, &DebuggerEngine::quitDebugger);
fp->setKeepOnFinish(FutureProgress::HideOnFinish);
d->m_progress.reportStarted();
@@ -541,6 +547,20 @@ void DebuggerEngine::startDebugger(DebuggerRunControl *runControl)
d->m_lastGoodState = DebuggerNotReady;
d->m_targetState = DebuggerNotReady;
d->m_progress.setProgressValue(200);
+
+ d->m_terminal.setup();
+ if (d->m_terminal.isUsable()) {
+ connect(&d->m_terminal, &Terminal::stdOutReady, [this, runControl](const QString &msg) {
+ runControl->appendMessage(msg, Utils::StdOutFormatSameLine);
+ });
+ connect(&d->m_terminal, &Terminal::stdErrReady, [this, runControl](const QString &msg) {
+ runControl->appendMessage(msg, Utils::StdErrFormatSameLine);
+ });
+ connect(&d->m_terminal, &Terminal::error, [this, runControl](const QString &msg) {
+ runControl->appendMessage(msg, Utils::ErrorMessageFormat);
+ });
+ }
+
d->queueSetupEngine();
}
@@ -577,9 +597,9 @@ void DebuggerEngine::gotoLocation(const Location &loc)
editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, true);
if (loc.needsMarker()) {
- d->m_locationMark.reset(new TextEditor::TextMark(file, line));
+ d->m_locationMark.reset(new TextMark(file, line));
d->m_locationMark->setIcon(Internal::locationMarkIcon());
- d->m_locationMark->setPriority(TextEditor::TextMark::HighPriority);
+ d->m_locationMark->setPriority(TextMark::HighPriority);
}
//qDebug() << "MEMORY: " << d->m_memoryAgent.hasVisibleEditor();
@@ -782,6 +802,7 @@ void DebuggerEngine::notifyInferiorSetupOk()
#ifdef WITH_BENCHMARK
CALLGRIND_START_INSTRUMENTATION;
#endif
+ aboutToNotifyInferiorSetupOk();
showMessage(_("NOTE: INFERIOR SETUP OK"));
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << this << state());
setState(InferiorSetupOk);
@@ -1204,9 +1225,8 @@ void DebuggerEngine::setState(DebuggerState state, bool forced)
if (state == DebuggerFinished) {
// Give up ownership on claimed breakpoints.
- BreakHandler *handler = breakHandler();
- foreach (BreakpointModelId id, handler->engineBreakpointIds(this))
- handler->notifyBreakpointReleased(id);
+ foreach (Breakpoint bp, breakHandler()->engineBreakpoints(this))
+ bp.notifyBreakpointReleased();
DebuggerToolTipManager::deregisterEngine(this);
}
@@ -1382,7 +1402,12 @@ DebuggerRunControl *DebuggerEngine::runControl() const
return d->runControl();
}
-bool DebuggerEngine::setToolTipExpression(TextEditor::TextEditorWidget *,
+Terminal *DebuggerEngine::terminal() const
+{
+ return &d->m_terminal;
+}
+
+bool DebuggerEngine::setToolTipExpression(TextEditorWidget *,
const DebuggerToolTipContext &)
{
return false;
@@ -1497,36 +1522,36 @@ void DebuggerEngine::attemptBreakpointSynchronization()
BreakHandler *handler = breakHandler();
- foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
+ foreach (Breakpoint bp, handler->unclaimedBreakpoints()) {
// Take ownership of the breakpoint. Requests insertion.
- if (acceptsBreakpoint(id)) {
+ if (acceptsBreakpoint(bp)) {
showMessage(_("TAKING OWNERSHIP OF BREAKPOINT %1 IN STATE %2")
- .arg(id.toString()).arg(handler->state(id)));
- handler->setEngine(id, this);
+ .arg(bp.id().toString()).arg(bp.state()));
+ bp.setEngine(this);
} else {
showMessage(_("BREAKPOINT %1 IN STATE %2 IS NOT ACCEPTABLE")
- .arg(id.toString()).arg(handler->state(id)));
+ .arg(bp.id().toString()).arg(bp.state()));
}
}
bool done = true;
- foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
- switch (handler->state(id)) {
+ foreach (Breakpoint bp, handler->engineBreakpoints(this)) {
+ switch (bp.state()) {
case BreakpointNew:
// Should not happen once claimed.
QTC_CHECK(false);
continue;
case BreakpointInsertRequested:
done = false;
- insertBreakpoint(id);
+ insertBreakpoint(bp);
continue;
case BreakpointChangeRequested:
done = false;
- changeBreakpoint(id);
+ changeBreakpoint(bp);
continue;
case BreakpointRemoveRequested:
done = false;
- removeBreakpoint(id);
+ removeBreakpoint(bp);
continue;
case BreakpointChangeProceeding:
case BreakpointInsertProceeding:
@@ -1543,7 +1568,7 @@ void DebuggerEngine::attemptBreakpointSynchronization()
QTC_CHECK(false);
continue;
}
- QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << id << state());
+ QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << bp.id() << state());
}
if (done) {
@@ -1554,24 +1579,33 @@ void DebuggerEngine::attemptBreakpointSynchronization()
}
}
-void DebuggerEngine::insertBreakpoint(BreakpointModelId id)
+bool DebuggerEngine::acceptsBreakpoint(Breakpoint bp) const
+{
+ Q_UNUSED(bp);
+ return false;
+}
+
+void DebuggerEngine::insertBreakpoint(Breakpoint bp)
{
- BreakpointState state = breakHandler()->state(id);
- QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << id << this << state);
+ BreakpointState state = bp.state();
+ QTC_ASSERT(state == BreakpointInsertRequested,
+ qDebug() << bp.id() << this << state);
QTC_CHECK(false);
}
-void DebuggerEngine::removeBreakpoint(BreakpointModelId id)
+void DebuggerEngine::removeBreakpoint(Breakpoint bp)
{
- BreakpointState state = breakHandler()->state(id);
- QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << id << this << state);
+ BreakpointState state = bp.state();
+ QTC_ASSERT(state == BreakpointRemoveRequested,
+ qDebug() << bp.id() << this << state);
QTC_CHECK(false);
}
-void DebuggerEngine::changeBreakpoint(BreakpointModelId id)
+void DebuggerEngine::changeBreakpoint(Breakpoint bp)
{
- BreakpointState state = breakHandler()->state(id);
- QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << id << this << state);
+ BreakpointState state = bp.state();
+ QTC_ASSERT(state == BreakpointChangeRequested,
+ qDebug() << bp.id() << this << state);
QTC_CHECK(false);
}
@@ -1650,56 +1684,6 @@ bool DebuggerEngine::isDying() const
return targetState() == DebuggerFinished;
}
-QString DebuggerEngine::msgWatchpointByExpressionTriggered(BreakpointModelId id,
- const int number, const QString &expr)
-{
- return id
- ? tr("Data breakpoint %1 (%2) at %3 triggered.")
- .arg(id.toString()).arg(number).arg(expr)
- : tr("Internal data breakpoint %1 at %2 triggered.")
- .arg(number).arg(expr);
-}
-
-QString DebuggerEngine::msgWatchpointByExpressionTriggered(BreakpointModelId id,
- const int number, const QString &expr, const QString &threadId)
-{
- return id
- ? tr("Data breakpoint %1 (%2) at %3 in thread %4 triggered.")
- .arg(id.toString()).arg(number).arg(expr).arg(threadId)
- : tr("Internal data breakpoint %1 at %2 in thread %3 triggered.")
- .arg(number).arg(expr).arg(threadId);
-}
-
-QString DebuggerEngine::msgWatchpointByAddressTriggered(BreakpointModelId id,
- const int number, quint64 address)
-{
- return id
- ? tr("Data breakpoint %1 (%2) at 0x%3 triggered.")
- .arg(id.toString()).arg(number).arg(address, 0, 16)
- : tr("Internal data breakpoint %1 at 0x%2 triggered.")
- .arg(number).arg(address, 0, 16);
-}
-
-QString DebuggerEngine::msgWatchpointByAddressTriggered(BreakpointModelId id,
- const int number, quint64 address, const QString &threadId)
-{
- return id
- ? tr("Data breakpoint %1 (%2) at 0x%3 in thread %4 triggered.")
- .arg(id.toString()).arg(number).arg(address, 0, 16).arg(threadId)
- : tr("Internal data breakpoint %1 at 0x%2 in thread %3 triggered.")
- .arg(id.toString()).arg(number).arg(address, 0, 16).arg(threadId);
-}
-
-QString DebuggerEngine::msgBreakpointTriggered(BreakpointModelId id,
- const int number, const QString &threadId)
-{
- return id
- ? tr("Stopped at breakpoint %1 (%2) in thread %3.")
- .arg(id.toString()).arg(number).arg(threadId)
- : tr("Stopped at internal breakpoint %1 in thread %2.")
- .arg(number).arg(threadId);
-}
-
QString DebuggerEngine::msgStopped(const QString &reason)
{
return reason.isEmpty() ? tr("Stopped.") : tr("Stopped: \"%1\"").arg(reason);
@@ -1733,7 +1717,7 @@ void DebuggerEngine::showStoppedBySignalMessageBox(QString meaning, QString name
"<table><tr><td>Signal name : </td><td>%1</td></tr>"
"<tr><td>Signal meaning : </td><td>%2</td></tr></table>")
.arg(name, meaning);
- showMessageBox(QMessageBox::Information, tr("Signal received"), msg);
+ AsynchronousMessageBox::information(tr("Signal received"), msg);
}
void DebuggerEngine::showStoppedByExceptionMessageBox(const QString &description)
@@ -1741,14 +1725,12 @@ void DebuggerEngine::showStoppedByExceptionMessageBox(const QString &description
const QString msg =
tr("<p>The inferior stopped because it triggered an exception.<p>%1").
arg(description);
- showMessageBox(QMessageBox::Information, tr("Exception Triggered"), msg);
+ AsynchronousMessageBox::information(tr("Exception Triggered"), msg);
}
-void DebuggerEngine::openMemoryView(quint64 startAddr, unsigned flags,
- const QList<MemoryMarkup> &ml, const QPoint &pos,
- const QString &title, QWidget *parent)
+void DebuggerEngine::openMemoryView(const MemoryViewSetupData &data)
{
- d->m_memoryAgent.createBinEditor(startAddr, flags, ml, pos, title, parent);
+ d->m_memoryAgent.createBinEditor(data);
}
void DebuggerEngine::updateMemoryViews()
@@ -1783,7 +1765,7 @@ void DebuggerEngine::validateExecutable(DebuggerStartParameters *sp)
const bool warnOnRelease = boolSetting(WarnOnReleaseBuilds);
QString detailedWarning;
switch (sp->toolChainAbi.binaryFormat()) {
- case ProjectExplorer::Abi::PEFormat: {
+ case Abi::PEFormat: {
if (!warnOnRelease || (sp->masterEngineType != CdbEngineType))
return;
if (!binary.endsWith(QLatin1String(".exe"), Qt::CaseInsensitive))
@@ -1798,7 +1780,7 @@ void DebuggerEngine::validateExecutable(DebuggerStartParameters *sp)
}
break;
}
- case ProjectExplorer::Abi::ElfFormat: {
+ case Abi::ElfFormat: {
Utils::ElfReader reader(binary);
Utils::ElfData elfData = reader.readHeaders();
@@ -1897,13 +1879,14 @@ void DebuggerEngine::validateExecutable(DebuggerStartParameters *sp)
return;
}
if (warnOnRelease) {
- showMessageBox(QMessageBox::Information, tr("Warning"),
+ AsynchronousMessageBox::information(tr("Warning"),
tr("This does not seem to be a \"Debug\" build.\n"
"Setting breakpoints by file name and line number may fail.")
+ QLatin1Char('\n') + detailedWarning);
}
}
+} // namespace Internal
} // namespace Debugger
#include "debuggerengine.moc"
diff --git a/src/plugins/debugger/debuggerengine.h b/src/plugins/debugger/debuggerengine.h
index 71c5ec831ad..a7313a9c7c4 100644
--- a/src/plugins/debugger/debuggerengine.h
+++ b/src/plugins/debugger/debuggerengine.h
@@ -33,8 +33,8 @@
#include "debugger_global.h"
#include "debuggerconstants.h"
+#include "debuggerprotocol.h"
#include "debuggerstartparameters.h"
-#include "breakpoint.h" // For BreakpointModelId.
#include "threaddata.h" // For ThreadId.
#include <QObject>
@@ -42,7 +42,6 @@
QT_BEGIN_NAMESPACE
class QDebug;
class QPoint;
-class QMessageBox;
class QAbstractItemModel;
QT_END_NAMESPACE
@@ -51,7 +50,6 @@ namespace Core { class IOptionsPage; }
namespace Debugger {
-class DebuggerEnginePrivate;
class DebuggerRunControl;
class DebuggerStartParameters;
@@ -60,6 +58,7 @@ DEBUGGER_EXPORT QDebug operator<<(QDebug str, DebuggerState state);
namespace Internal {
+class DebuggerEnginePrivate;
class DebuggerPluginPrivate;
class DisassemblerAgent;
class MemoryAgent;
@@ -72,11 +71,12 @@ class StackFrame;
class SourceFilesHandler;
class ThreadsHandler;
class WatchHandler;
-class BreakpointParameters;
+class Breakpoint;
class QmlAdapter;
class QmlCppEngine;
class DebuggerToolTipContext;
-class MemoryMarkup;
+class MemoryViewSetupData;
+class Terminal;
struct WatchUpdateFlags
{
@@ -130,11 +130,7 @@ public:
quint64 address;
};
-} // namespace Internal
-
-
-// FIXME: DEBUGGER_EXPORT?
-class DEBUGGER_EXPORT DebuggerEngine : public QObject
+class DebuggerEngine : public QObject
{
Q_OBJECT
@@ -163,10 +159,7 @@ public:
MemoryView = 0x4 //!< Open a separate view (using the pos-parameter).
};
- virtual void openMemoryView(quint64 startAddr, unsigned flags,
- const QList<Internal::MemoryMarkup> &ml,
- const QPoint &pos,
- const QString &title = QString(), QWidget *parent = 0);
+ virtual void openMemoryView(const MemoryViewSetupData &data);
virtual void fetchMemory(Internal::MemoryAgent *, QObject *,
quint64 addr, quint64 length);
virtual void changeMemory(Internal::MemoryAgent *, QObject *,
@@ -190,7 +183,7 @@ public:
virtual void loadAdditionalQmlStack();
virtual void reloadDebuggingHelpers();
- virtual void setRegisterValue(int regnr, const QString &value);
+ virtual void setRegisterValue(const QByteArray &name, const QString &value);
virtual void addOptionPages(QList<Core::IOptionsPage*> *) const;
virtual bool hasCapability(unsigned cap) const = 0;
virtual void debugLastCommand() {}
@@ -201,13 +194,12 @@ public:
virtual void createSnapshot();
virtual void updateAll();
- typedef Internal::BreakpointModelId BreakpointModelId;
virtual bool stateAcceptsBreakpointChanges() const { return true; }
virtual void attemptBreakpointSynchronization();
- virtual bool acceptsBreakpoint(BreakpointModelId id) const = 0;
- virtual void insertBreakpoint(BreakpointModelId id); // FIXME: make pure
- virtual void removeBreakpoint(BreakpointModelId id); // FIXME: make pure
- virtual void changeBreakpoint(BreakpointModelId id); // FIXME: make pure
+ virtual bool acceptsBreakpoint(Breakpoint bp) const = 0;
+ virtual void insertBreakpoint(Breakpoint bp); // FIXME: make pure
+ virtual void removeBreakpoint(Breakpoint bp); // FIXME: make pure
+ virtual void changeBreakpoint(Breakpoint bp); // FIXME: make pure
virtual bool acceptsDebuggerCommands() const { return true; }
virtual void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
@@ -264,9 +256,6 @@ public:
bool isMasterEngine() const;
DebuggerEngine *masterEngine() const;
- virtual bool setupQmlStep(bool /*on*/) { return false; }
- virtual void readyToExecuteQmlStep() {}
-
virtual bool canDisplayTooltip() const { return state() == InferiorStopOk; }
virtual void notifyInferiorIll();
@@ -286,6 +275,7 @@ signals:
* a server start script should be used, but none is given.
*/
void requestRemoteSetup();
+ void aboutToNotifyInferiorSetupOk();
protected:
// The base notify*() function implementation should be sufficient
@@ -319,7 +309,9 @@ protected:
virtual void notifyInferiorStopOk();
virtual void notifyInferiorSpontaneousStop();
virtual void notifyInferiorStopFailed();
- Q_SLOT virtual void notifyInferiorExited();
+
+ public:
+ virtual void notifyInferiorExited();
protected:
virtual void notifyInferiorShutdownOk();
@@ -362,17 +354,8 @@ protected:
void setMasterEngine(DebuggerEngine *masterEngine);
DebuggerRunControl *runControl() const;
+ Terminal *terminal() const;
- static QString msgWatchpointByAddressTriggered(BreakpointModelId id,
- int number, quint64 address);
- static QString msgWatchpointByAddressTriggered(BreakpointModelId id,
- int number, quint64 address, const QString &threadId);
- static QString msgWatchpointByExpressionTriggered(BreakpointModelId id,
- int number, const QString &expr);
- static QString msgWatchpointByExpressionTriggered(BreakpointModelId id,
- int number, const QString &expr, const QString &threadId);
- static QString msgBreakpointTriggered(BreakpointModelId id,
- int number, const QString &threadId);
static QString msgStopped(const QString &reason = QString());
static QString msgStoppedBySignal(const QString &meaning, const QString &name);
static QString msgStoppedByException(const QString &description,
@@ -396,9 +379,9 @@ protected:
private:
// Wrapper engine needs access to state of its subengines.
- friend class Internal::QmlCppEngine;
- friend class Internal::DebuggerPluginPrivate;
- friend class Internal::QmlAdapter;
+ friend class QmlCppEngine;
+ friend class DebuggerPluginPrivate;
+ friend class QmlAdapter;
virtual void setState(DebuggerState state, bool forced = false);
@@ -406,6 +389,7 @@ private:
DebuggerEnginePrivate *d;
};
+} // namespace Internal
} // namespace Debugger
Q_DECLARE_METATYPE(Debugger::Internal::ContextData)
diff --git a/src/plugins/debugger/debuggeritem.cpp b/src/plugins/debugger/debuggeritem.cpp
index def87bde117..f011a861dbf 100644
--- a/src/plugins/debugger/debuggeritem.cpp
+++ b/src/plugins/debugger/debuggeritem.cpp
@@ -142,9 +142,18 @@ void DebuggerItem::reinitializeFromFile()
.arg(version / 10000).arg((version / 100) % 100).arg(version % 100);
return;
}
- if (ba.contains("lldb") || ba.startsWith("LLDB")) {
+ if (ba.startsWith("lldb") || ba.startsWith("LLDB")) {
m_engineType = LldbEngineType;
m_abis = Abi::abisOfBinary(m_command);
+
+ // Version
+ if (ba.startsWith(("lldb version "))) { // Linux typically.
+ int pos1 = strlen("lldb version ");
+ int pos2 = ba.indexOf(' ', pos1);
+ m_version = QString::fromLatin1(ba.mid(pos1, pos2 - pos1));
+ } else if (ba.startsWith("lldb-") || ba.startsWith("LLDB-")) { // Mac typically.
+ m_version = QString::fromLatin1(ba.mid(5));
+ }
return;
}
if (ba.startsWith("Python")) {
@@ -223,7 +232,7 @@ void DebuggerItem::setEngineType(const DebuggerEngineType &engineType)
m_engineType = engineType;
}
-void DebuggerItem::setCommand(const Utils::FileName &command)
+void DebuggerItem::setCommand(const FileName &command)
{
m_command = command;
}
@@ -248,7 +257,7 @@ void DebuggerItem::setAutoDetectionSource(const QString &autoDetectionSource)
m_autoDetectionSource = autoDetectionSource;
}
-void DebuggerItem::setAbis(const QList<ProjectExplorer::Abi> &abis)
+void DebuggerItem::setAbis(const QList<Abi> &abis)
{
m_abis = abis;
}
diff --git a/src/plugins/debugger/debuggeritem.h b/src/plugins/debugger/debuggeritem.h
index ffffb2086bd..6117e6c5f34 100644
--- a/src/plugins/debugger/debuggeritem.h
+++ b/src/plugins/debugger/debuggeritem.h
@@ -97,6 +97,7 @@ public:
QStringList abiNames() const;
bool operator==(const DebuggerItem &other) const;
+ bool operator!=(const DebuggerItem &other) const { return !operator==(other); }
private:
DebuggerItem(const QVariant &id);
diff --git a/src/plugins/debugger/debuggeritemmanager.cpp b/src/plugins/debugger/debuggeritemmanager.cpp
index b4a38c29270..f7cad5d96c7 100644
--- a/src/plugins/debugger/debuggeritemmanager.cpp
+++ b/src/plugins/debugger/debuggeritemmanager.cpp
@@ -29,8 +29,6 @@
****************************************************************************/
#include "debuggeritemmanager.h"
-
-#include "debuggeritemmodel.h"
#include "debuggerkitinformation.h"
#include <coreplugin/icore.h>
@@ -46,26 +44,36 @@
#include <QFileInfo>
#include <QProcess>
+using namespace Core;
using namespace ProjectExplorer;
using namespace Utils;
namespace Debugger {
-static const char DEBUGGER_COUNT_KEY[] = "DebuggerItem.Count";
-static const char DEBUGGER_DATA_KEY[] = "DebuggerItem.";
-static const char DEBUGGER_LEGACY_FILENAME[] = "/qtcreator/profiles.xml";
-static const char DEBUGGER_FILE_VERSION_KEY[] = "Version";
-static const char DEBUGGER_FILENAME[] = "/qtcreator/debuggers.xml";
+const char DEBUGGER_COUNT_KEY[] = "DebuggerItem.Count";
+const char DEBUGGER_DATA_KEY[] = "DebuggerItem.";
+const char DEBUGGER_LEGACY_FILENAME[] = "/qtcreator/profiles.xml";
+const char DEBUGGER_FILE_VERSION_KEY[] = "Version";
+const char DEBUGGER_FILENAME[] = "/qtcreator/debuggers.xml";
+
+namespace {
+QList<DebuggerItem> m_debuggers;
+PersistentSettingsWriter *m_writer = 0;
+}
// --------------------------------------------------------------------------
// DebuggerItemManager
// --------------------------------------------------------------------------
-static DebuggerItemManager *m_instance = 0;
+static void addDebugger(const DebuggerItem &item)
+{
+ QTC_ASSERT(item.id().isValid(), return);
+ m_debuggers.append(item);
+}
static FileName userSettingsFileName()
{
- QFileInfo settingsLocation(Core::ICore::settings()->fileName());
+ QFileInfo settingsLocation(ICore::settings()->fileName());
return FileName::fromString(settingsLocation.absolutePath() + QLatin1String(DEBUGGER_FILENAME));
}
@@ -111,27 +119,15 @@ static void readDebuggers(const FileName &fileName, bool isSystem)
}
}
-QList<DebuggerItem> DebuggerItemManager::m_debuggers;
-PersistentSettingsWriter * DebuggerItemManager::m_writer = 0;
-
-DebuggerItemManager::DebuggerItemManager(QObject *parent)
- : QObject(parent)
+DebuggerItemManager::DebuggerItemManager()
{
- m_instance = this;
m_writer = new PersistentSettingsWriter(userSettingsFileName(), QLatin1String("QtCreatorDebuggers"));
- connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
- this, SLOT(saveDebuggers()));
-}
-
-DebuggerItemManager *DebuggerItemManager::instance()
-{
- return m_instance;
+ connect(ICore::instance(), &ICore::saveSettingsRequested,
+ this, &DebuggerItemManager::saveDebuggers);
}
DebuggerItemManager::~DebuggerItemManager()
{
- disconnect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
- this, SLOT(saveDebuggers()));
delete m_writer;
}
@@ -227,7 +223,7 @@ void DebuggerItemManager::autoDetectGdbOrLldbDebuggers()
}
*/
- QFileInfoList suspects;
+ QList<FileName> suspects;
if (HostOsInfo::isMacHost()) {
QProcess lldbInfo;
@@ -238,43 +234,38 @@ void DebuggerItemManager::autoDetectGdbOrLldbDebuggers()
lldbInfo.waitForFinished();
} else {
QByteArray lPath = lldbInfo.readAll();
- suspects.append(QFileInfo(QString::fromLocal8Bit(lPath.data(), lPath.size() -1)));
+ const QFileInfo fi(QString::fromLocal8Bit(lPath.data(), lPath.size() -1));
+ if (fi.exists() && fi.isExecutable() && !fi.isDir())
+ suspects.append(FileName::fromString(fi.absoluteFilePath()));
}
}
QStringList path = Environment::systemEnvironment().path();
+ path.removeDuplicates();
+ QDir dir;
+ dir.setNameFilters(filters);
+ dir.setFilter(QDir::Files | QDir::Executable);
foreach (const QString &base, path) {
- QDir dir(base);
- dir.setNameFilters(filters);
- suspects += dir.entryInfoList();
+ dir.setPath(base);
+ foreach (const QString &entry, dir.entryList())
+ suspects.append(FileName::fromString(dir.absoluteFilePath(entry)));
}
- foreach (const QFileInfo &fi, suspects) {
- if (fi.exists() && fi.isExecutable() && !fi.isDir()) {
- FileName command = FileName::fromString(fi.absoluteFilePath());
- if (findByCommand(command))
- continue;
- DebuggerItem item;
- item.createId();
- item.setCommand(command);
- item.reinitializeFromFile();
- //: %1: Debugger engine type (GDB, LLDB, CDB...), %2: Path
- item.setDisplayName(tr("System %1 at %2")
- .arg(item.engineTypeName()).arg(QDir::toNativeSeparators(fi.absoluteFilePath())));
- item.setAutoDetected(true);
- addDebugger(item);
- }
+ foreach (const FileName &command, suspects) {
+ if (findByCommand(command))
+ continue;
+ DebuggerItem item;
+ item.createId();
+ item.setCommand(command);
+ item.reinitializeFromFile();
+ //: %1: Debugger engine type (GDB, LLDB, CDB...), %2: Path
+ item.setDisplayName(tr("System %1 at %2")
+ .arg(item.engineTypeName()).arg(command.toUserOutput()));
+ item.setAutoDetected(true);
+ addDebugger(item);
}
}
-void DebuggerItemManager::readLegacyDebuggers()
-{
- QFileInfo systemLocation(Core::ICore::settings(QSettings::SystemScope)->fileName());
- readLegacyDebuggers(FileName::fromString(systemLocation.absolutePath() + QLatin1String(DEBUGGER_LEGACY_FILENAME)));
- QFileInfo userLocation(Core::ICore::settings()->fileName());
- readLegacyDebuggers(FileName::fromString(userLocation.absolutePath() + QLatin1String(DEBUGGER_LEGACY_FILENAME)));
-}
-
void DebuggerItemManager::readLegacyDebuggers(const FileName &file)
{
PersistentSettingsReader reader;
@@ -341,7 +332,7 @@ const DebuggerItem *DebuggerItemManager::findByEngineType(DebuggerEngineType eng
void DebuggerItemManager::restoreDebuggers()
{
// Read debuggers from SDK
- QFileInfo systemSettingsFile(Core::ICore::settings(QSettings::SystemScope)->fileName());
+ QFileInfo systemSettingsFile(ICore::settings(QSettings::SystemScope)->fileName());
readDebuggers(FileName::fromString(systemSettingsFile.absolutePath() + QLatin1String(DEBUGGER_FILENAME)), true);
// Read all debuggers from user file.
@@ -352,7 +343,10 @@ void DebuggerItemManager::restoreDebuggers()
autoDetectGdbOrLldbDebuggers();
// Add debuggers from pre-3.x profiles.xml
- readLegacyDebuggers();
+ QFileInfo systemLocation(ICore::settings(QSettings::SystemScope)->fileName());
+ readLegacyDebuggers(FileName::fromString(systemLocation.absolutePath() + QLatin1String(DEBUGGER_LEGACY_FILENAME)));
+ QFileInfo userLocation(ICore::settings()->fileName());
+ readLegacyDebuggers(FileName::fromString(userLocation.absolutePath() + QLatin1String(DEBUGGER_LEGACY_FILENAME)));
}
void DebuggerItemManager::saveDebuggers()
@@ -372,7 +366,7 @@ void DebuggerItemManager::saveDebuggers()
}
}
data.insert(QLatin1String(DEBUGGER_COUNT_KEY), count);
- m_writer->save(data, Core::ICore::mainWindow());
+ m_writer->save(data, ICore::mainWindow());
// Do not save default debuggers as they are set by the SDK.
}
@@ -390,44 +384,23 @@ QVariant DebuggerItemManager::registerDebugger(const DebuggerItem &item)
}
}
- // If item already has an id, add it. Otherwise, create a new id.
- if (item.id().isValid())
- return addDebugger(item);
-
+ // If item already has an id, use it. Otherwise, create a new id.
DebuggerItem di = item;
- di.createId();
- return addDebugger(di);
-}
+ if (!di.id().isValid())
+ di.createId();
-void DebuggerItemManager::deregisterDebugger(const QVariant &id)
-{
- if (findById(id))
- removeDebugger(id);
+ addDebugger(di);
+ return di.id();
}
-QVariant DebuggerItemManager::addDebugger(const DebuggerItem &item)
-{
- QTC_ASSERT(item.id().isValid(), return QVariant());
- m_debuggers.append(item);
- QVariant id = item.id();
- emit m_instance->debuggerAdded(id);
- return id;
-}
-
-void DebuggerItemManager::removeDebugger(const QVariant &id)
+void DebuggerItemManager::deregisterDebugger(const QVariant &id)
{
- bool ok = false;
for (int i = 0, n = m_debuggers.size(); i != n; ++i) {
if (m_debuggers.at(i).id() == id) {
- emit m_instance->aboutToRemoveDebugger(id);
m_debuggers.removeAt(i);
- emit m_instance->debuggerRemoved(id);
- ok = true;
break;
}
}
-
- QTC_ASSERT(ok, return);
}
QString DebuggerItemManager::uniqueDisplayName(const QString &base)
@@ -439,26 +412,18 @@ QString DebuggerItemManager::uniqueDisplayName(const QString &base)
return base;
}
-void DebuggerItemManager::setItemData(const QVariant &id, const QString &displayName, const FileName &fileName)
+void DebuggerItemManager::updateOrAddDebugger(const DebuggerItem &treeItem)
{
for (int i = 0, n = m_debuggers.size(); i != n; ++i) {
DebuggerItem &item = m_debuggers[i];
- if (item.id() == id) {
- bool changed = false;
- if (item.displayName() != displayName) {
- item.setDisplayName(displayName);
- changed = true;
- }
- if (item.command() != fileName) {
- item.setCommand(fileName);
- item.reinitializeFromFile();
- changed = true;
- }
- if (changed)
- emit m_instance->debuggerUpdated(id);
- break;
+ if (item.id() == treeItem.id()) {
+ item = treeItem;
+ return;
}
}
+
+ // This is a new item.
+ addDebugger(treeItem);
}
} // namespace Debugger;
diff --git a/src/plugins/debugger/debuggeritemmanager.h b/src/plugins/debugger/debuggeritemmanager.h
index 5bddfccbb59..25afa1b2df7 100644
--- a/src/plugins/debugger/debuggeritemmanager.h
+++ b/src/plugins/debugger/debuggeritemmanager.h
@@ -33,35 +33,27 @@
#include "debugger_global.h"
#include "debuggeritem.h"
-#include "debuggeritemmodel.h"
#include <QList>
#include <QObject>
#include <QString>
-namespace Utils { class PersistentSettingsWriter; }
-
namespace Debugger {
-namespace Internal { class DebuggerPlugin; }
-
// -----------------------------------------------------------------------
// DebuggerItemManager
// -----------------------------------------------------------------------
class DEBUGGER_EXPORT DebuggerItemManager : public QObject
{
- Q_OBJECT
-
public:
- static DebuggerItemManager *instance();
+ DebuggerItemManager();
~DebuggerItemManager();
static QList<DebuggerItem> debuggers();
static QVariant registerDebugger(const DebuggerItem &item);
static void deregisterDebugger(const QVariant &id);
- static void setItemData(const QVariant &id, const QString& displayName, const Utils::FileName &fileName);
static const DebuggerItem *findByCommand(const Utils::FileName &command);
static const DebuggerItem *findById(const QVariant &id);
@@ -70,30 +62,13 @@ public:
static void restoreDebuggers();
static QString uniqueDisplayName(const QString &base);
- static void removeDebugger(const QVariant &id);
- static QVariant addDebugger(const DebuggerItem &item);
-
-signals:
- void debuggerAdded(const QVariant &id);
- void aboutToRemoveDebugger(const QVariant &id);
- void debuggerRemoved(const QVariant &id);
- void debuggerUpdated(const QVariant &id);
-
-public slots:
- void saveDebuggers();
+ static void updateOrAddDebugger(const DebuggerItem &item);
+ static void saveDebuggers();
private:
- explicit DebuggerItemManager(QObject *parent = 0);
static void autoDetectGdbOrLldbDebuggers();
static void autoDetectCdbDebuggers();
- static void readLegacyDebuggers();
static void readLegacyDebuggers(const Utils::FileName &file);
-
- static Utils::PersistentSettingsWriter *m_writer;
- static QList<DebuggerItem> m_debuggers;
-
- friend class Internal::DebuggerItemModel;
- friend class Internal::DebuggerPlugin; // Enable constrcutor for DebuggerPlugin
};
} // namespace Debugger
diff --git a/src/plugins/debugger/debuggeritemmodel.cpp b/src/plugins/debugger/debuggeritemmodel.cpp
deleted file mode 100644
index 9b24144510c..00000000000
--- a/src/plugins/debugger/debuggeritemmodel.cpp
+++ /dev/null
@@ -1,311 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "debuggeritemmodel.h"
-
-#include "debuggeritem.h"
-#include "debuggeritemmanager.h"
-
-#include <utils/qtcassert.h>
-
-namespace Debugger {
-namespace Internal {
-
-const int AbiRole = Qt::UserRole + 2;
-
-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)->setData(item.abiNames(), AbiRole);
- row.at(0)->setEditable(false);
- row.at(1)->setEditable(false);
- row.at(1)->setData(item.toMap());
- row.at(2)->setEditable(false);
- row.at(2)->setData(static_cast<int>(item.engineType()));
- 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;
-}
-
-// --------------------------------------------------------------------------
-// DebuggerItemModel
-// --------------------------------------------------------------------------
-
-DebuggerItemModel::DebuggerItemModel(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);
-
- foreach (const DebuggerItem &item, DebuggerItemManager::debuggers())
- addDebuggerStandardItem(item, false);
-
- QObject *manager = DebuggerItemManager::instance();
- connect(manager, SIGNAL(debuggerAdded(QVariant)),
- this, SLOT(onDebuggerAdded(QVariant)));
- connect(manager, SIGNAL(debuggerUpdated(QVariant)),
- this, SLOT(onDebuggerUpdate(QVariant)));
- connect(manager, SIGNAL(debuggerRemoved(QVariant)),
- this, SLOT(onDebuggerRemoval(QVariant)));
-}
-
-QVariant DebuggerItemModel::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();
-}
-
-bool DebuggerItemModel::addDebuggerStandardItem(const DebuggerItem &item, bool changed)
-{
- if (findStandardItemById(item.id()))
- return false;
-
- QList<QStandardItem *> row = describeItem(item);
- foreach (QStandardItem *cell, row) {
- QFont font = cell->font();
- font.setBold(changed);
- cell->setFont(font);
- }
- (item.isAutoDetected() ? m_autoRoot : m_manualRoot)->appendRow(row);
- return true;
-}
-
-bool DebuggerItemModel::removeDebuggerStandardItem(const QVariant &id)
-{
- QStandardItem *sitem = findStandardItemById(id);
- QTC_ASSERT(sitem, return false);
- QStandardItem *parent = sitem->parent();
- QTC_ASSERT(parent, return false);
- // This will trigger a change of m_currentDebugger via changing the
- // view selection.
- parent->removeRow(sitem->row());
- return true;
-}
-
-bool DebuggerItemModel::updateDebuggerStandardItem(const DebuggerItem &item, bool changed)
-{
- QStandardItem *sitem = findStandardItemById(item.id());
- QTC_ASSERT(sitem, return false);
- QStandardItem *parent = sitem->parent();
- QTC_ASSERT(parent, return false);
-
- // Do not mark items as changed if they actually are not:
- const DebuggerItem *orig = DebuggerItemManager::findById(item.id());
- if (orig && *orig == item)
- changed = false;
-
- int row = sitem->row();
- QFont font = sitem->font();
- font.setBold(changed);
- parent->child(row, 0)->setData(item.displayName(), Qt::DisplayRole);
- parent->child(row, 0)->setData(item.abiNames(), AbiRole);
- 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)->setData(static_cast<int>(item.engineType()));
- parent->child(row, 2)->setFont(font);
- return true;
-}
-
-DebuggerItem DebuggerItemModel::debuggerItem(QStandardItem *sitem) const
-{
- DebuggerItem item = DebuggerItem(QVariant());
- if (sitem && sitem->parent()) {
- item.setAutoDetected(sitem->parent() == m_autoRoot);
-
- QStandardItem *i = sitem->parent()->child(sitem->row(), 0);
- item.m_id = i->data();
- item.setDisplayName(i->data(Qt::DisplayRole).toString());
-
- QStringList abis = i->data(AbiRole).toStringList();
- QList<ProjectExplorer::Abi> abiList;
- foreach (const QString &abi, abis)
- abiList << ProjectExplorer::Abi(abi);
- item.setAbis(abiList);
-
- i = sitem->parent()->child(sitem->row(), 1);
- item.setCommand(Utils::FileName::fromUserInput(i->data(Qt::DisplayRole).toString()));
-
- i = sitem->parent()->child(sitem->row(), 2);
- item.setEngineType(static_cast<DebuggerEngineType>(i->data().toInt()));
- }
- return item;
-}
-
-QList<DebuggerItem> DebuggerItemModel::debuggerItems() const
-{
- QList<DebuggerItem> result;
- for (int i = 0, n = m_autoRoot->rowCount(); i != n; ++i)
- result << debuggerItem(m_autoRoot->child(i));
- for (int i = 0, n = m_manualRoot->rowCount(); i != n; ++i)
- result << debuggerItem(m_manualRoot->child(i));
- return result;
-}
-
-QStandardItem *DebuggerItemModel::currentStandardItem() const
-{
- return findStandardItemById(m_currentDebugger);
-}
-
-QStandardItem *DebuggerItemModel::findStandardItemById(const QVariant &id) const
-{
- for (int i = 0, n = m_autoRoot->rowCount(); i != n; ++i) {
- QStandardItem *sitem = m_autoRoot->child(i);
- if (sitem->data() == id)
- return sitem;
- }
- for (int i = 0, n = m_manualRoot->rowCount(); i != n; ++i) {
- QStandardItem *sitem = m_manualRoot->child(i);
- if (sitem->data() == id)
- return sitem;
- }
- return 0;
-}
-
-QModelIndex DebuggerItemModel::currentIndex() const
-{
- QStandardItem *current = currentStandardItem();
- return current ? current->index() : QModelIndex();
-}
-
-QModelIndex DebuggerItemModel::lastIndex() const
-{
- int n = m_manualRoot->rowCount();
- QStandardItem *current = m_manualRoot->child(n - 1);
- return current ? current->index() : QModelIndex();
-}
-
-void DebuggerItemModel::onDebuggerAdded(const QVariant &id)
-{
- const DebuggerItem *item = DebuggerItemManager::findById(id);
- QTC_ASSERT(item, return);
- if (!addDebuggerStandardItem(*item, false))
- updateDebuggerStandardItem(*item, false); // already had it added, so just update it.
-}
-
-void DebuggerItemModel::onDebuggerUpdate(const QVariant &id)
-{
- const DebuggerItem *item = DebuggerItemManager::findById(id);
- QTC_ASSERT(item, return);
- updateDebuggerStandardItem(*item, false);
-}
-
-void DebuggerItemModel::onDebuggerRemoval(const QVariant &id)
-{
- removeDebuggerStandardItem(id);
-}
-
-void DebuggerItemModel::addDebugger(const DebuggerItem &item)
-{
- addDebuggerStandardItem(item, true);
-}
-
-void DebuggerItemModel::removeDebugger(const QVariant &id)
-{
- if (!removeDebuggerStandardItem(id)) // Nothing there!
- return;
-
- if (DebuggerItemManager::findById(id))
- m_removedItems.append(id);
-}
-
-void DebuggerItemModel::updateDebugger(const DebuggerItem &item)
-{
- updateDebuggerStandardItem(item, true);
-}
-
-void DebuggerItemModel::apply()
-{
- foreach (const QVariant &id, m_removedItems)
- DebuggerItemManager::deregisterDebugger(id);
-
- foreach (const DebuggerItem &item, debuggerItems()) {
- const DebuggerItem *managed = DebuggerItemManager::findById(item.id());
- if (managed) {
- if (*managed == item)
- continue;
- else
- DebuggerItemManager::setItemData(item.id(), item.displayName(), item.command());
- } else {
- DebuggerItemManager::registerDebugger(item);
- }
- }
-}
-
-void DebuggerItemModel::setCurrentIndex(const QModelIndex &index)
-{
- QStandardItem *sit = itemFromIndex(index);
- m_currentDebugger = sit ? sit->data() : QVariant();
-}
-
-DebuggerItem DebuggerItemModel::currentDebugger() const
-{
- return debuggerItem(currentStandardItem());
-}
-
-} // namespace Internal
-} // namespace Debugger
diff --git a/src/plugins/debugger/debuggeritemmodel.h b/src/plugins/debugger/debuggeritemmodel.h
deleted file mode 100644
index 682bd60247b..00000000000
--- a/src/plugins/debugger/debuggeritemmodel.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef DEBUGGER_DEBUGGERITEMMODEL_H
-#define DEBUGGER_DEBUGGERITEMMODEL_H
-
-#include "debuggeritem.h"
-
-#include <QStandardItemModel>
-#include <QVariant>
-
-namespace Debugger {
-namespace Internal {
-
-// -----------------------------------------------------------------------
-// DebuggerItemModel
-//------------------------------------------------------------------------
-
-class DebuggerItemModel : public QStandardItemModel
-{
- Q_OBJECT
-
-public:
- DebuggerItemModel(QObject *parent = 0);
-
- QModelIndex currentIndex() const;
- QModelIndex lastIndex() const;
- void setCurrentIndex(const QModelIndex &index);
- QVariant currentDebuggerId() const { return m_currentDebugger; }
- DebuggerItem currentDebugger() const;
- void addDebugger(const DebuggerItem &item);
- void removeDebugger(const QVariant &id);
- void updateDebugger(const DebuggerItem &item);
-
- void apply();
-
-private slots:
- void onDebuggerAdded(const QVariant &id);
- void onDebuggerUpdate(const QVariant &id);
- void onDebuggerRemoval(const QVariant &id);
-
-private:
- QStandardItem *currentStandardItem() const;
- QStandardItem *findStandardItemById(const QVariant &id) const;
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
-
- bool addDebuggerStandardItem(const DebuggerItem &item, bool changed);
- bool removeDebuggerStandardItem(const QVariant &id);
- bool updateDebuggerStandardItem(const DebuggerItem &item, bool changed);
-
- DebuggerItem debuggerItem(QStandardItem *sitem) const;
- QList<DebuggerItem> debuggerItems() const;
-
- QVariant m_currentDebugger;
-
- QStandardItem *m_autoRoot;
- QStandardItem *m_manualRoot;
- QStringList removed;
-
- QList<QVariant> m_removedItems;
-};
-
-} // namespace Internal
-} // namespace Debugger
-
-#endif // DEBUGGER_DEBUGGERITEMMODEL_H
diff --git a/src/plugins/debugger/debuggerkitconfigwidget.cpp b/src/plugins/debugger/debuggerkitconfigwidget.cpp
index 40f7e18c2ac..1812cb76e06 100644
--- a/src/plugins/debugger/debuggerkitconfigwidget.cpp
+++ b/src/plugins/debugger/debuggerkitconfigwidget.cpp
@@ -31,7 +31,6 @@
#include "debuggerkitconfigwidget.h"
#include "debuggeritemmanager.h"
-#include "debuggeritemmodel.h"
#include "debuggerkitinformation.h"
#include <coreplugin/icore.h>
@@ -64,8 +63,6 @@ using namespace ProjectExplorer;
namespace Debugger {
namespace Internal {
-class DebuggerItemConfigWidget;
-
// -----------------------------------------------------------------------
// DebuggerKitConfigWidget
// -----------------------------------------------------------------------
@@ -88,14 +85,6 @@ DebuggerKitConfigWidget::DebuggerKitConfigWidget(Kit *workingCopy, const KitInfo
m_manageButton->setContentsMargins(0, 0, 0, 0);
connect(m_manageButton, &QAbstractButton::clicked,
this, &DebuggerKitConfigWidget::manageDebuggers);
-
- DebuggerItemManager *manager = DebuggerItemManager::instance();
- connect(manager, &DebuggerItemManager::debuggerAdded,
- this, &DebuggerKitConfigWidget::onDebuggerAdded);
- connect(manager, &DebuggerItemManager::debuggerUpdated,
- this, &DebuggerKitConfigWidget::onDebuggerUpdated);
- connect(manager, &DebuggerItemManager::debuggerRemoved,
- this, &DebuggerKitConfigWidget::onDebuggerRemoved);
}
DebuggerKitConfigWidget::~DebuggerKitConfigWidget()
@@ -150,31 +139,6 @@ void DebuggerKitConfigWidget::currentDebuggerChanged(int)
m_kit->setValue(DebuggerKitInformation::id(), id);
}
-void DebuggerKitConfigWidget::onDebuggerAdded(const QVariant &id)
-{
- const DebuggerItem *item = DebuggerItemManager::findById(id);
- QTC_ASSERT(item, return);
- m_comboBox->addItem(item->displayName(), id);
-}
-
-void DebuggerKitConfigWidget::onDebuggerUpdated(const QVariant &id)
-{
- const DebuggerItem *item = DebuggerItemManager::findById(id);
- QTC_ASSERT(item, return);
- const int pos = indexOf(id);
- if (pos < 0)
- return;
- m_comboBox->setItemText(pos, item->displayName());
-}
-
-void DebuggerKitConfigWidget::onDebuggerRemoved(const QVariant &id)
-{
- if (const int pos = indexOf(id)) {
- m_comboBox->removeItem(pos);
- refresh();
- }
-}
-
int DebuggerKitConfigWidget::indexOf(const QVariant &id)
{
QTC_ASSERT(id.isValid(), return -1);
diff --git a/src/plugins/debugger/debuggerkitconfigwidget.h b/src/plugins/debugger/debuggerkitconfigwidget.h
index fc5d569e84d..cbe4e8b5948 100644
--- a/src/plugins/debugger/debuggerkitconfigwidget.h
+++ b/src/plugins/debugger/debuggerkitconfigwidget.h
@@ -31,8 +31,6 @@
#ifndef DEBUGGER_DEBUGGERKITCONFIGWIDGET_H
#define DEBUGGER_DEBUGGERKITCONFIGWIDGET_H
-#include "debuggeritemmodel.h"
-
#include <coreplugin/dialogs/ioptionspage.h>
#include <projectexplorer/kitconfigwidget.h>
#include <projectexplorer/abi.h>
@@ -72,14 +70,10 @@ public:
QWidget *buttonWidget() const;
QWidget *mainWidget() const;
-private slots:
+private:
void manageDebuggers();
void currentDebuggerChanged(int idx);
- void onDebuggerAdded(const QVariant &id);
- void onDebuggerUpdated(const QVariant &id);
- void onDebuggerRemoved(const QVariant &id);
-private:
int indexOf(const QVariant &id);
QVariant currentId() const;
void updateComboBox(const QVariant &id);
diff --git a/src/plugins/debugger/debuggerkitinformation.cpp b/src/plugins/debugger/debuggerkitinformation.cpp
index 06e24d80f37..f41f0edea2e 100644
--- a/src/plugins/debugger/debuggerkitinformation.cpp
+++ b/src/plugins/debugger/debuggerkitinformation.cpp
@@ -306,13 +306,28 @@ void DebuggerKitInformation::addToMacroExpander(Kit *kit, MacroExpander *expande
expander->registerVariable("Debugger:Type", tr("Type of Debugger Backend"),
[this, kit]() -> QString {
const DebuggerItem *item = debugger(kit);
- return item ? item->engineTypeName() : tr("unknown");
+ return item ? item->engineTypeName() : tr("Unknown debugger type");
});
- // FIXME: Use better strings.
+
expander->registerVariable("Debugger:Name", tr("Debugger"),
[this, kit]() -> QString {
const DebuggerItem *item = debugger(kit);
- return item ? item->displayName() : tr("unknown");
+ return item ? item->displayName() : tr("Unknown debugger");
+ });
+
+ expander->registerVariable("Debugger:Version", tr("Debugger"),
+ [this, kit]() -> QString {
+ const DebuggerItem *item = debugger(kit);
+ return item && !item->version().isEmpty()
+ ? item->version() : tr("Unknown debugger version");
+ });
+
+ expander->registerVariable("Debugger:Abi", tr("Debugger"),
+ [this, kit]() -> QString {
+ const DebuggerItem *item = debugger(kit);
+ return item && !item->abis().isEmpty()
+ ? item->abiNames().join(QLatin1Char(' '))
+ : tr("Unknown debugger ABI");
});
}
@@ -321,14 +336,14 @@ KitInformation::ItemList DebuggerKitInformation::toUserOutput(const Kit *k) cons
return ItemList() << qMakePair(tr("Debugger"), displayString(k));
}
-FileName DebuggerKitInformation::debuggerCommand(const ProjectExplorer::Kit *k)
+FileName DebuggerKitInformation::debuggerCommand(const Kit *k)
{
const DebuggerItem *item = debugger(k);
QTC_ASSERT(item, return FileName());
return item->command();
}
-DebuggerEngineType DebuggerKitInformation::engineType(const ProjectExplorer::Kit *k)
+DebuggerEngineType DebuggerKitInformation::engineType(const Kit *k)
{
const DebuggerItem *item = debugger(k);
QTC_ASSERT(item, return NoEngineType);
diff --git a/src/plugins/debugger/debuggermainwindow.cpp b/src/plugins/debugger/debuggermainwindow.cpp
index 8f433d05fd4..b2610ebf439 100644
--- a/src/plugins/debugger/debuggermainwindow.cpp
+++ b/src/plugins/debugger/debuggermainwindow.cpp
@@ -89,16 +89,16 @@ public:
bool isQmlActive() const;
void setSimpleDockWidgetArrangement();
// Debuggable languages are registered with this function.
- void addLanguage(DebuggerLanguage language, const Core::Context &context);
+ void addLanguage(DebuggerLanguage language, const Context &context);
QDockWidget *dockWidget(const QString &objectName) const
{ return q->findChild<QDockWidget *>(objectName); }
public slots:
void resetDebuggerLayout();
- void updateUiForProject(ProjectExplorer::Project *project);
- void updateUiForTarget(ProjectExplorer::Target *target);
- void updateUiForRunConfiguration(ProjectExplorer::RunConfiguration *rc);
+ void updateUiForProject(Project *project);
+ void updateUiForTarget(Target *target);
+ void updateUiForRunConfiguration(RunConfiguration *rc);
void updateUiForCurrentRunConfiguration();
void updateActiveLanguages();
void updateDockWidgetSettings();
@@ -162,26 +162,24 @@ DebuggerMainWindowPrivate::DebuggerMainWindowPrivate(DebuggerMainWindow *mw)
void DebuggerMainWindowPrivate::updateUiForProject(Project *project)
{
if (m_previousProject) {
- disconnect(m_previousProject,
- SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
- this, SLOT(updateUiForTarget(ProjectExplorer::Target*)));
+ disconnect(m_previousProject, &Project::activeTargetChanged,
+ this, &DebuggerMainWindowPrivate::updateUiForTarget);
}
m_previousProject = project;
if (!project) {
updateUiForTarget(0);
return;
}
- connect(project, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
- SLOT(updateUiForTarget(ProjectExplorer::Target*)));
+ connect(project, &Project::activeTargetChanged,
+ this, &DebuggerMainWindowPrivate::updateUiForTarget);
updateUiForTarget(project->activeTarget());
}
void DebuggerMainWindowPrivate::updateUiForTarget(Target *target)
{
if (m_previousTarget) {
- disconnect(m_previousTarget,
- SIGNAL(activeRunConfigurationChanged(ProjectExplorer::RunConfiguration*)),
- this, SLOT(updateUiForRunConfiguration(ProjectExplorer::RunConfiguration*)));
+ disconnect(m_previousTarget, &Target::activeRunConfigurationChanged,
+ this, &DebuggerMainWindowPrivate::updateUiForRunConfiguration);
}
m_previousTarget = target;
@@ -191,9 +189,8 @@ void DebuggerMainWindowPrivate::updateUiForTarget(Target *target)
return;
}
- connect(target,
- SIGNAL(activeRunConfigurationChanged(ProjectExplorer::RunConfiguration*)),
- SLOT(updateUiForRunConfiguration(ProjectExplorer::RunConfiguration*)));
+ connect(target, &Target::activeRunConfigurationChanged,
+ this, &DebuggerMainWindowPrivate::updateUiForRunConfiguration);
updateUiForRunConfiguration(target->activeRunConfiguration());
}
@@ -201,16 +198,15 @@ void DebuggerMainWindowPrivate::updateUiForTarget(Target *target)
void DebuggerMainWindowPrivate::updateUiForRunConfiguration(RunConfiguration *rc)
{
if (m_previousRunConfiguration)
- disconnect(m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>(),
- SIGNAL(requestRunActionsUpdate()),
- this, SLOT(updateUiForCurrentRunConfiguration()));
+ disconnect(m_previousRunConfiguration, &RunConfiguration::requestRunActionsUpdate,
+ this, &DebuggerMainWindowPrivate::updateUiForCurrentRunConfiguration);
m_previousRunConfiguration = rc;
updateUiForCurrentRunConfiguration();
if (!rc)
return;
- connect(m_previousRunConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>(),
- SIGNAL(requestRunActionsUpdate()),
- SLOT(updateUiForCurrentRunConfiguration()));
+
+ connect(m_previousRunConfiguration, &RunConfiguration::requestRunActionsUpdate,
+ this, &DebuggerMainWindowPrivate::updateUiForCurrentRunConfiguration);
}
void DebuggerMainWindowPrivate::updateUiForCurrentRunConfiguration()
@@ -298,30 +294,30 @@ void DebuggerMainWindow::onModeChanged(IMode *mode)
void DebuggerMainWindowPrivate::createViewsMenuItems()
{
Context debugcontext(Constants::C_DEBUGMODE);
- m_viewsMenu = Core::ActionManager::actionContainer(Id(Core::Constants::M_WINDOW_VIEWS));
+ m_viewsMenu = ActionManager::actionContainer(Id(Core::Constants::M_WINDOW_VIEWS));
QTC_ASSERT(m_viewsMenu, return);
QAction *openMemoryEditorAction = new QAction(this);
openMemoryEditorAction->setText(tr("Memory..."));
- connect(openMemoryEditorAction, SIGNAL(triggered()),
- SLOT(openMemoryEditor()));
+ connect(openMemoryEditorAction, &QAction::triggered,
+ this, &DebuggerMainWindowPrivate::openMemoryEditor);
// Add menu items
Command *cmd = 0;
- cmd = Core::ActionManager::registerAction(openMemoryEditorAction,
+ cmd = ActionManager::registerAction(openMemoryEditorAction,
"Debugger.Views.OpenMemoryEditor", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
- cmd = Core::ActionManager::registerAction(q->menuSeparator1(),
+ cmd = ActionManager::registerAction(q->menuSeparator1(),
"Debugger.Views.Separator1", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
- cmd = Core::ActionManager::registerAction(q->autoHideTitleBarsAction(),
+ cmd = ActionManager::registerAction(q->autoHideTitleBarsAction(),
"Debugger.Views.AutoHideTitleBars", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
- cmd = Core::ActionManager::registerAction(q->menuSeparator2(),
+ cmd = ActionManager::registerAction(q->menuSeparator2(),
"Debugger.Views.Separator2", debugcontext);
cmd->setAttribute(Command::CA_Hide);
m_viewsMenu->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
@@ -407,8 +403,8 @@ QDockWidget *DebuggerMainWindow::createDockWidget(const DebuggerLanguage &langua
Context globalContext(Core::Constants::C_GLOBAL);
QAction *toggleViewAction = dockWidget->toggleViewAction();
- Command *cmd = Core::ActionManager::registerAction(toggleViewAction,
- Core::Id("Debugger.").withSuffix(widget->objectName()), globalContext);
+ Command *cmd = ActionManager::registerAction(toggleViewAction,
+ Id("Debugger.").withSuffix(widget->objectName()), globalContext);
cmd->setAttribute(Command::CA_Hide);
dockWidget->installEventFilter(&d->m_resizeEventFilter);
@@ -430,10 +426,10 @@ void DebuggerMainWindow::addStagedMenuEntries()
QWidget *DebuggerMainWindow::createContents(IMode *mode)
{
- connect(SessionManager::instance(), SIGNAL(startupProjectChanged(ProjectExplorer::Project*)),
- d, SLOT(updateUiForProject(ProjectExplorer::Project*)));
+ connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
+ d, &DebuggerMainWindowPrivate::updateUiForProject);
- d->m_viewsMenu = Core::ActionManager::actionContainer(Core::Id(Core::Constants::M_WINDOW_VIEWS));
+ d->m_viewsMenu = ActionManager::actionContainer(Id(Core::Constants::M_WINDOW_VIEWS));
QTC_ASSERT(d->m_viewsMenu, return 0);
//d->m_mainWindow = new Internal::DebuggerMainWindow(this);
@@ -444,17 +440,17 @@ QWidget *DebuggerMainWindow::createContents(IMode *mode)
connect(autoHideTitleBarsAction(), SIGNAL(triggered()),
d, SLOT(updateDockWidgetSettings()));
- QBoxLayout *editorHolderLayout = new QVBoxLayout;
+ auto editorHolderLayout = new QVBoxLayout;
editorHolderLayout->setMargin(0);
editorHolderLayout->setSpacing(0);
- QWidget *editorAndFindWidget = new QWidget;
+ auto editorAndFindWidget = new QWidget;
editorAndFindWidget->setLayout(editorHolderLayout);
auto editorManagerPlaceHolder = new EditorManagerPlaceHolder(mode);
editorHolderLayout->addWidget(editorManagerPlaceHolder);
editorHolderLayout->addWidget(new FindToolBarPlaceHolder(editorAndFindWidget));
- MiniSplitter *documentAndRightPane = new MiniSplitter;
+ auto documentAndRightPane = new MiniSplitter;
documentAndRightPane->addWidget(editorAndFindWidget);
documentAndRightPane->addWidget(new RightPanePlaceHolder(mode));
documentAndRightPane->setStretchFactor(0, 1);
@@ -466,18 +462,18 @@ QWidget *DebuggerMainWindow::createContents(IMode *mode)
hackyName.replace(QLatin1Char('&'), QString());
d->m_viewButton->setText(hackyName);
- Utils::StyledBar *debugToolBar = new Utils::StyledBar;
+ auto debugToolBar = new Utils::StyledBar;
debugToolBar->setProperty("topBorder", true);
- QHBoxLayout *debugToolBarLayout = new QHBoxLayout(debugToolBar);
+ auto debugToolBarLayout = new QHBoxLayout(debugToolBar);
debugToolBarLayout->setMargin(0);
debugToolBarLayout->setSpacing(0);
debugToolBarLayout->addWidget(d->m_debugToolBar);
debugToolBarLayout->addWidget(new Utils::StyledSeparator);
debugToolBarLayout->addWidget(d->m_viewButton);
- connect(d->m_viewButton, SIGNAL(clicked()), this, SLOT(showViewsMenu()));
+ connect(d->m_viewButton, &QAbstractButton::clicked, this, &DebuggerMainWindow::showViewsMenu);
- QDockWidget *dock = new QDockWidget(DebuggerMainWindowPrivate::tr("Debugger Toolbar"));
+ auto dock = new QDockWidget(DebuggerMainWindowPrivate::tr("Debugger Toolbar"));
dock->setObjectName(QLatin1String("Debugger Toolbar"));
dock->setWidget(debugToolBar);
dock->setFeatures(QDockWidget::NoDockWidgetFeatures);
@@ -487,10 +483,10 @@ QWidget *DebuggerMainWindow::createContents(IMode *mode)
addDockWidget(Qt::BottomDockWidgetArea, dock);
setToolBarDockWidget(dock);
- QWidget *centralWidget = new QWidget;
+ auto centralWidget = new QWidget;
setCentralWidget(centralWidget);
- QVBoxLayout *centralLayout = new QVBoxLayout(centralWidget);
+ auto centralLayout = new QVBoxLayout(centralWidget);
centralWidget->setLayout(centralLayout);
centralLayout->setMargin(0);
centralLayout->setSpacing(0);
@@ -499,9 +495,9 @@ QWidget *DebuggerMainWindow::createContents(IMode *mode)
centralLayout->setStretch(1, 0);
// Right-side window with editor, output etc.
- MiniSplitter *mainWindowSplitter = new MiniSplitter;
+ auto mainWindowSplitter = new MiniSplitter;
mainWindowSplitter->addWidget(this);
- QWidget *outputPane = new OutputPanePlaceHolder(mode, mainWindowSplitter);
+ auto outputPane = new OutputPanePlaceHolder(mode, mainWindowSplitter);
outputPane->setObjectName(QLatin1String("DebuggerOutputPanePlaceHolder"));
mainWindowSplitter->addWidget(outputPane);
mainWindowSplitter->setStretchFactor(0, 10);
@@ -509,7 +505,7 @@ QWidget *DebuggerMainWindow::createContents(IMode *mode)
mainWindowSplitter->setOrientation(Qt::Vertical);
// Navigation and right-side window.
- MiniSplitter *splitter = new MiniSplitter;
+ auto splitter = new MiniSplitter;
splitter->setFocusProxy(editorManagerPlaceHolder);
splitter->addWidget(new NavigationWidgetPlaceHolder(mode));
splitter->addWidget(mainWindowSplitter);
diff --git a/src/plugins/debugger/debuggermainwindow.h b/src/plugins/debugger/debuggermainwindow.h
index 1dbf5f4712a..c6a0e1118c2 100644
--- a/src/plugins/debugger/debuggermainwindow.h
+++ b/src/plugins/debugger/debuggermainwindow.h
@@ -36,16 +36,11 @@
#include <utils/fancymainwindow.h>
-namespace Core {
-class Context;
-class IMode;
-}
+namespace Core { class IMode; }
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
+
class DebuggerMainWindowPrivate;
// DebuggerMainWindow dock widget names
diff --git a/src/plugins/debugger/debuggeroptionspage.cpp b/src/plugins/debugger/debuggeroptionspage.cpp
index d0b04a9b32c..0484757ca87 100644
--- a/src/plugins/debugger/debuggeroptionspage.cpp
+++ b/src/plugins/debugger/debuggeroptionspage.cpp
@@ -29,15 +29,14 @@
****************************************************************************/
#include "debuggeroptionspage.h"
-
#include "debuggeritemmanager.h"
-#include "debuggeritemmodel.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/detailswidget.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
+#include <utils/treemodel.h>
#include <utils/winutils.h>
#include <QFileInfo>
@@ -55,19 +54,176 @@ using namespace Utils;
namespace Debugger {
namespace Internal {
-static const char debuggingToolsWikiLinkC[] = "http://qt-project.org/wiki/Qt_Creator_Windows_Debugging";
+const char debuggingToolsWikiLinkC[] = "http://qt-project.org/wiki/Qt_Creator_Windows_Debugging";
+
+// --------------------------------------------------------------------------
+// DebuggerTreeItem
+// --------------------------------------------------------------------------
+
+class DebuggerTreeItem : public TreeItem
+{
+public:
+ DebuggerTreeItem(const DebuggerItem &item, bool changed) : m_item(item), m_changed(changed) {}
+
+ QVariant data(int column, int role) const
+ {
+ switch (role) {
+ case Qt::DisplayRole:
+ switch (column) {
+ case 0: return m_item.displayName();
+ case 1: return m_item.command().toUserOutput();
+ case 2: return m_item.engineTypeName();
+ }
+
+ case Qt::FontRole: {
+ QFont font;
+ font.setBold(m_changed);
+ return font;
+ }
+ }
+ return QVariant();
+ }
+
+ DebuggerItem m_item;
+ bool m_changed;
+};
+
+// --------------------------------------------------------------------------
+// DebuggerItemModel
+// --------------------------------------------------------------------------
+
+class DebuggerItemModel : public TreeModel
+{
+ Q_DECLARE_TR_FUNCTIONS(Debugger::DebuggerOptionsPage)
+
+public:
+ DebuggerItemModel();
+
+ QModelIndex lastIndex() const;
+ void setCurrentIndex(const QModelIndex &index);
+ DebuggerItem *currentDebugger() const;
+ void addDebugger(const DebuggerItem &item, bool changed);
+ void updateDebugger(const DebuggerItem &item);
+ void removeCurrentDebugger();
+ void apply();
+
+private:
+ DebuggerTreeItem *m_currentTreeItem;
+ QStringList removed;
+
+ QList<QVariant> m_removedItems;
+};
+
+DebuggerItemModel::DebuggerItemModel()
+ : m_currentTreeItem(0)
+{
+ setHeader(QStringList() << tr("Name") << tr("Location") << tr("Type"));
+ rootItem()->appendChild(new TreeItem(QStringList() << tr("Auto-detected") << QString() << QString()));
+ rootItem()->appendChild(new TreeItem(QStringList() << tr("Manual") << QString() << QString()));
+
+ foreach (const DebuggerItem &item, DebuggerItemManager::debuggers())
+ addDebugger(item, false);
+}
+
+void DebuggerItemModel::addDebugger(const DebuggerItem &item, bool changed)
+{
+ int group = item.isAutoDetected() ? 0 : 1;
+ rootItem()->child(group)->appendChild(new DebuggerTreeItem(item, changed));
+}
+
+void DebuggerItemModel::updateDebugger(const DebuggerItem &item)
+{
+ auto matcher = [item](DebuggerTreeItem *n) { return n->m_item.m_id == item.id(); };
+ DebuggerTreeItem *treeItem = findItemAtLevel<DebuggerTreeItem *>(2, matcher);
+ QTC_ASSERT(treeItem, return);
+
+ TreeItem *parent = treeItem->parent();
+ QTC_ASSERT(parent, return);
+
+ const DebuggerItem *orig = DebuggerItemManager::findById(item.id());
+ treeItem->m_changed = !orig || *orig != item;
+ treeItem->m_item = item;
+ treeItem->update(); // Notify views.
+}
+
+QModelIndex DebuggerItemModel::lastIndex() const
+{
+ TreeItem *manualGroup = rootItem()->lastChild();
+ TreeItem *lastItem = manualGroup->lastChild();
+ return lastItem ? indexFromItem(lastItem) : QModelIndex();
+}
+
+DebuggerItem *DebuggerItemModel::currentDebugger() const
+{
+ return m_currentTreeItem ? &m_currentTreeItem->m_item : 0;
+}
+
+void DebuggerItemModel::removeCurrentDebugger()
+{
+ QTC_ASSERT(m_currentTreeItem, return);
+ QVariant id = m_currentTreeItem->m_item.id();
+ DebuggerTreeItem *treeItem = m_currentTreeItem;
+ m_currentTreeItem = 0;
+ removeItem(treeItem);
+ delete treeItem;
+ m_removedItems.append(id);
+}
+
+void DebuggerItemModel::apply()
+{
+ foreach (const QVariant &id, m_removedItems)
+ DebuggerItemManager::deregisterDebugger(id);
+
+ foreach (auto item, treeLevelItems<DebuggerTreeItem *>(2)) {
+ item->m_changed = false;
+ DebuggerItemManager::updateOrAddDebugger(item->m_item);
+ }
+}
+
+void DebuggerItemModel::setCurrentIndex(const QModelIndex &index)
+{
+ TreeItem *treeItem = itemFromIndex(index);
+ m_currentTreeItem = treeItem && treeItem->level() == 2 ? static_cast<DebuggerTreeItem *>(treeItem) : 0;
+}
// -----------------------------------------------------------------------
// DebuggerItemConfigWidget
// -----------------------------------------------------------------------
-DebuggerItemConfigWidget::DebuggerItemConfigWidget(DebuggerItemModel *model) :
- m_model(model)
+class DebuggerItemConfigWidget : public QWidget
+{
+ Q_DECLARE_TR_FUNCTIONS(Debugger::DebuggerOptionsPage)
+
+public:
+ explicit DebuggerItemConfigWidget(DebuggerItemModel *model);
+ void load(const DebuggerItem *item);
+ void store() const;
+
+private:
+ void binaryPathHasChanged();
+ DebuggerItem item() const;
+ void setAbis(const QStringList &abiNames);
+
+ DebuggerItemModel *m_model;
+ QLineEdit *m_displayNameLineEdit;
+ QLineEdit *m_typeLineEdit;
+ QLabel *m_cdbLabel;
+ QLineEdit *m_versionLabel;
+ PathChooser *m_binaryChooser;
+ QLineEdit *m_abis;
+ bool m_autodetected;
+ DebuggerEngineType m_engineType;
+ QVariant m_id;
+};
+
+DebuggerItemConfigWidget::DebuggerItemConfigWidget(DebuggerItemModel *model)
+ : m_model(model)
{
- QTC_CHECK(model);
-
m_displayNameLineEdit = new QLineEdit(this);
+ m_typeLineEdit = new QLineEdit(this);
+ m_typeLineEdit->setEnabled(false);
+
m_binaryChooser = new PathChooser(this);
m_binaryChooser->setExpectedKind(PathChooser::ExistingCommand);
m_binaryChooser->setMinimumWidth(400);
@@ -87,21 +243,21 @@ DebuggerItemConfigWidget::DebuggerItemConfigWidget(DebuggerItemModel *model) :
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("Type:")), m_typeLineEdit);
formLayout->addRow(new QLabel(tr("ABIs:")), m_abis);
formLayout->addRow(new QLabel(tr("Version:")), m_versionLabel);
- connect(m_binaryChooser, SIGNAL(changed(QString)), this, SLOT(binaryPathHasChanged()));
+ connect(m_binaryChooser, &PathChooser::changed,
+ this, &DebuggerItemConfigWidget::binaryPathHasChanged);
+ connect(m_displayNameLineEdit, &QLineEdit::textChanged,
+ this, &DebuggerItemConfigWidget::store);
}
DebuggerItem DebuggerItemConfigWidget::item() const
{
DebuggerItem item(m_id);
- if (m_id.isNull())
- return item;
-
item.setDisplayName(m_displayNameLineEdit->text());
item.setCommand(m_binaryChooser->fileName());
item.setAutoDetected(m_autodetected);
@@ -117,12 +273,10 @@ DebuggerItem DebuggerItemConfigWidget::item() const
return item;
}
-
void DebuggerItemConfigWidget::store() const
{
- DebuggerItem i = item();
- if (i.isValid())
- m_model->updateDebugger(i);
+ if (!m_id.isNull())
+ m_model->updateDebugger(item());
}
void DebuggerItemConfigWidget::setAbis(const QStringList &abiNames)
@@ -130,50 +284,26 @@ void DebuggerItemConfigWidget::setAbis(const QStringList &abiNames)
m_abis->setText(abiNames.join(QLatin1String(", ")));
}
-void DebuggerItemConfigWidget::handleCommandChange()
+void DebuggerItemConfigWidget::load(const DebuggerItem *item)
{
- // Use DebuggerItemManager as a cache:
- const DebuggerItem *existing
- = DebuggerItemManager::findByCommand(m_binaryChooser->fileName());
- if (existing) {
- setAbis(existing->abiNames());
- m_versionLabel->setText(existing->version());
- m_engineType = existing->engineType();
- } else {
- QFileInfo fi = QFileInfo(m_binaryChooser->path());
- if (fi.isExecutable()) {
- DebuggerItem tmp = item();
- tmp.reinitializeFromFile();
- setAbis(tmp.abiNames());
- m_versionLabel->setText(tmp.version());
- m_engineType = tmp.engineType();
- } else {
- setAbis(QStringList());
- m_versionLabel->setText(QString());
- m_engineType = NoEngineType;
- }
- }
- m_model->updateDebugger(item());
-}
-
-void DebuggerItemConfigWidget::setItem(const DebuggerItem &item)
-{
- store(); // store away the (changed) settings for future use
-
m_id = QVariant(); // reset Id to avoid intermediate signal handling
+ if (!item)
+ return;
// Set values:
- m_autodetected = item.isAutoDetected();
+ m_autodetected = item->isAutoDetected();
- m_displayNameLineEdit->setEnabled(!item.isAutoDetected());
- m_displayNameLineEdit->setText(item.displayName());
+ m_displayNameLineEdit->setEnabled(!item->isAutoDetected());
+ m_displayNameLineEdit->setText(item->displayName());
- m_binaryChooser->setReadOnly(item.isAutoDetected());
- m_binaryChooser->setFileName(item.command());
+ m_typeLineEdit->setText(item->engineTypeName());
+
+ m_binaryChooser->setReadOnly(item->isAutoDetected());
+ m_binaryChooser->setFileName(item->command());
QString text;
QString versionCommand;
- if (item.engineType() == CdbEngineType) {
+ if (item->engineType() == CdbEngineType) {
const bool is64bit = is64BitWindowsSystem();
const QString versionString = is64bit ? tr("64-bit version") : tr("32-bit version");
//: Label text for path configuration. %2 is "x-bit version".
@@ -189,20 +319,10 @@ void DebuggerItemConfigWidget::setItem(const DebuggerItem &item)
m_cdbLabel->setText(text);
m_cdbLabel->setVisible(!text.isEmpty());
m_binaryChooser->setCommandVersionArguments(QStringList(versionCommand));
- m_versionLabel->setText(item.version());
- setAbis(item.abiNames());
- m_engineType = item.engineType();
- m_id = item.id();
-}
-
-void DebuggerItemConfigWidget::apply()
-{
- DebuggerItem current = m_model->currentDebugger();
- if (!current.isValid())
- return; // Nothing was selected here.
-
- store();
- setItem(item());
+ m_versionLabel->setText(item->version());
+ setAbis(item->abiNames());
+ m_engineType = item->engineType();
+ m_id = item->id();
}
void DebuggerItemConfigWidget::binaryPathHasChanged()
@@ -211,58 +331,57 @@ void DebuggerItemConfigWidget::binaryPathHasChanged()
if (!m_id.isValid())
return;
- handleCommandChange();
+ DebuggerItem tmp;
+ QFileInfo fi = QFileInfo(m_binaryChooser->path());
+ if (fi.isExecutable()) {
+ tmp = item();
+ tmp.reinitializeFromFile();
+ }
+
+ setAbis(tmp.abiNames());
+ m_versionLabel->setText(tmp.version());
+ m_engineType = tmp.engineType();
+ m_typeLineEdit->setText(tmp.engineTypeName());
+
+ store();
}
// --------------------------------------------------------------------------
-// DebuggerOptionsPage
+// DebuggerConfigWidget
// --------------------------------------------------------------------------
-DebuggerOptionsPage::DebuggerOptionsPage()
+class DebuggerConfigWidget : public QWidget
{
- m_model = 0;
- m_debuggerView = 0;
- m_container = 0;
- m_addButton = 0;
- m_cloneButton = 0;
- m_delButton = 0;
+public:
+ DebuggerConfigWidget()
+ {
+ m_addButton = new QPushButton(tr("Add"), this);
- 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::widget()
-{
- if (!m_configWidget) {
- m_configWidget = new QWidget;
+ m_cloneButton = new QPushButton(tr("Clone"), this);
+ m_cloneButton->setEnabled(false);
- 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_delButton = new QPushButton(tr("Remove"), this);
+ m_delButton->setEnabled(false);
- m_container = new DetailsWidget(m_configWidget);
+ m_container = new DetailsWidget(this);
m_container->setState(DetailsWidget::NoSummary);
m_container->setVisible(false);
- m_debuggerView = new QTreeView(m_configWidget);
- m_model = new DebuggerItemModel(m_debuggerView);
- m_debuggerView->setModel(m_model);
+ m_debuggerView = new QTreeView(this);
+ m_debuggerView->setModel(&m_model);
m_debuggerView->setUniformRowHeights(true);
+ m_debuggerView->setRootIsDecorated(false);
m_debuggerView->setSelectionMode(QAbstractItemView::SingleSelection);
m_debuggerView->setSelectionBehavior(QAbstractItemView::SelectRows);
m_debuggerView->expandAll();
- QHeaderView *header = m_debuggerView->header();
+ auto header = m_debuggerView->header();
header->setStretchLastSection(false);
header->setSectionResizeMode(0, QHeaderView::ResizeToContents);
header->setSectionResizeMode(1, QHeaderView::ResizeToContents);
header->setSectionResizeMode(2, QHeaderView::Stretch);
- QVBoxLayout *buttonLayout = new QVBoxLayout();
+ auto buttonLayout = new QVBoxLayout();
buttonLayout->setSpacing(6);
buttonLayout->setContentsMargins(0, 0, 0, 0);
buttonLayout->addWidget(m_addButton);
@@ -270,54 +389,62 @@ QWidget *DebuggerOptionsPage::widget()
buttonLayout->addWidget(m_delButton);
buttonLayout->addItem(new QSpacerItem(10, 40, QSizePolicy::Minimum, QSizePolicy::Expanding));
- QVBoxLayout *verticalLayout = new QVBoxLayout();
+ auto verticalLayout = new QVBoxLayout();
verticalLayout->addWidget(m_debuggerView);
verticalLayout->addWidget(m_container);
- QHBoxLayout *horizontalLayout = new QHBoxLayout(m_configWidget);
+ auto horizontalLayout = new QHBoxLayout(this);
horizontalLayout->addLayout(verticalLayout);
horizontalLayout->addLayout(buttonLayout);
- connect(m_debuggerView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(debuggerSelectionChanged()));
+ connect(m_debuggerView->selectionModel(), &QItemSelectionModel::currentChanged,
+ this, &DebuggerConfigWidget::currentDebuggerChanged, Qt::QueuedConnection);
- 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);
+ connect(m_addButton, &QAbstractButton::clicked,
+ this, &DebuggerConfigWidget::addDebugger, Qt::QueuedConnection);
+ connect(m_cloneButton, &QAbstractButton::clicked,
+ this, &DebuggerConfigWidget::cloneDebugger, Qt::QueuedConnection);
+ connect(m_delButton, &QAbstractButton::clicked,
+ this, &DebuggerConfigWidget::removeDebugger, Qt::QueuedConnection);
- m_itemConfigWidget = new DebuggerItemConfigWidget(m_model);
+ m_itemConfigWidget = new DebuggerItemConfigWidget(&m_model);
m_container->setWidget(m_itemConfigWidget);
-
- updateState();
}
- return m_configWidget;
-}
-void DebuggerOptionsPage::apply()
+ void cloneDebugger();
+ void addDebugger();
+ void removeDebugger();
+ void currentDebuggerChanged(const QModelIndex &newCurrent);
+ void updateState();
+
+ DebuggerItemModel m_model;
+ QTreeView *m_debuggerView;
+ QPushButton *m_addButton;
+ QPushButton *m_cloneButton;
+ QPushButton *m_delButton;
+ DetailsWidget *m_container;
+ DebuggerItemConfigWidget *m_itemConfigWidget;
+};
+
+void DebuggerConfigWidget::cloneDebugger()
{
- m_itemConfigWidget->apply();
- m_model->apply();
-}
-
-void DebuggerOptionsPage::cloneDebugger()
-{
- DebuggerItem item = m_model->currentDebugger();
- if (!item.isValid())
+ DebuggerItem *item = m_model.currentDebugger();
+ if (!item)
return;
DebuggerItem newItem;
newItem.createId();
newItem.setAutoDetected(false);
- newItem.setCommand(item.command());
- newItem.setEngineType(item.engineType());
- newItem.setAbis(item.abis());
- newItem.setDisplayName(DebuggerItemManager::uniqueDisplayName(tr("Clone of %1").arg(item.displayName())));
+ newItem.setCommand(item->command());
+ newItem.setEngineType(item->engineType());
+ newItem.setAbis(item->abis());
+ newItem.setDisplayName(DebuggerItemManager::uniqueDisplayName(tr("Clone of %1").arg(item->displayName())));
newItem.setAutoDetected(false);
- m_model->addDebugger(newItem);
- m_debuggerView->setCurrentIndex(m_model->lastIndex());
+ m_model.addDebugger(newItem, true);
+ m_debuggerView->setCurrentIndex(m_model.lastIndex());
}
-void DebuggerOptionsPage::addDebugger()
+void DebuggerConfigWidget::addDebugger()
{
DebuggerItem item;
item.createId();
@@ -325,72 +452,60 @@ void DebuggerOptionsPage::addDebugger()
item.setEngineType(NoEngineType);
item.setDisplayName(DebuggerItemManager::uniqueDisplayName(tr("New Debugger")));
item.setAutoDetected(false);
- m_model->addDebugger(item);
- m_debuggerView->setCurrentIndex(m_model->lastIndex());
+ m_model.addDebugger(item, true);
+ m_debuggerView->setCurrentIndex(m_model.lastIndex());
}
-void DebuggerOptionsPage::removeDebugger()
+void DebuggerConfigWidget::removeDebugger()
{
- QVariant id = m_model->currentDebuggerId();
- m_model->removeDebugger(id);
- m_debuggerView->setCurrentIndex(m_model->lastIndex());
+ m_model.removeCurrentDebugger();
+ m_debuggerView->setCurrentIndex(m_model.lastIndex());
}
-void DebuggerOptionsPage::finish()
+void DebuggerConfigWidget::currentDebuggerChanged(const QModelIndex &newCurrent)
{
- delete m_configWidget;
-
- // Children of m_configWidget.
- m_model = 0;
- m_container = 0;
- m_debuggerView = 0;
- m_addButton = 0;
- m_cloneButton = 0;
- m_delButton = 0;
-}
+ m_model.setCurrentIndex(newCurrent);
-void DebuggerOptionsPage::debuggerSelectionChanged()
-{
- QTC_ASSERT(m_container, return);
+ DebuggerItem *item = m_model.currentDebugger();
- QModelIndex mi = m_debuggerView->currentIndex();
- mi = mi.sibling(mi.row(), 0);
- m_model->setCurrentIndex(mi);
+ m_itemConfigWidget->load(item);
+ m_container->setVisible(item);
+ m_cloneButton->setEnabled(item && item->isValid() && item->canClone());
+ m_delButton->setEnabled(item && !item->isAutoDetected());
+}
- DebuggerItem item = m_model->currentDebugger();
+// --------------------------------------------------------------------------
+// DebuggerOptionsPage
+// --------------------------------------------------------------------------
- m_itemConfigWidget->setItem(item);
- m_container->setVisible(item.isValid());
- updateState();
+DebuggerOptionsPage::DebuggerOptionsPage()
+{
+ 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));
}
-void DebuggerOptionsPage::debuggerModelChanged()
+QWidget *DebuggerOptionsPage::widget()
{
- QTC_ASSERT(m_container, return);
-
- QVariant id = m_model->currentDebuggerId();
- const DebuggerItem *item = DebuggerItemManager::findById(id);
- if (!item)
- return;
-
- m_itemConfigWidget->setItem(*item);
- m_container->setVisible(m_model->currentDebuggerId().isValid());
- m_debuggerView->setCurrentIndex(m_model->currentIndex());
- updateState();
+ if (!m_configWidget)
+ m_configWidget = new DebuggerConfigWidget;
+ return m_configWidget;
}
-void DebuggerOptionsPage::updateState()
+void DebuggerOptionsPage::apply()
{
- if (!m_cloneButton)
- return;
-
- DebuggerItem item = m_model->currentDebugger();
-
- bool canCopy = item.isValid() && item.canClone();
- bool canDelete = m_model->currentIndex().parent().isValid() && !item.isAutoDetected();
+ QTC_ASSERT(m_configWidget, return);
+ m_configWidget->m_itemConfigWidget->store();
+ m_configWidget->m_model.apply();
+}
- m_cloneButton->setEnabled(canCopy);
- m_delButton->setEnabled(canDelete);
+void DebuggerOptionsPage::finish()
+{
+ delete m_configWidget;
+ m_configWidget = 0;
}
} // namespace Internal
diff --git a/src/plugins/debugger/debuggeroptionspage.h b/src/plugins/debugger/debuggeroptionspage.h
index df9b169853b..5db065b49c0 100644
--- a/src/plugins/debugger/debuggeroptionspage.h
+++ b/src/plugins/debugger/debuggeroptionspage.h
@@ -31,73 +31,19 @@
#ifndef DEBUGGER_DEBUGGEROPTIONSPAGE_H
#define DEBUGGER_DEBUGGEROPTIONSPAGE_H
-#include "debuggeritem.h"
-
#include <coreplugin/dialogs/ioptionspage.h>
+#include <QCoreApplication>
#include <QPointer>
-#include <QWidget>
-
-QT_BEGIN_NAMESPACE
-class QLabel;
-class QLineEdit;
-class QPushButton;
-class QTreeView;
-QT_END_NAMESPACE
-
-namespace Utils {
-class DetailsWidget;
-class PathChooser;
-} // namespace Utils
namespace Debugger {
namespace Internal {
-class DebuggerItemModel;
-class DebuggerItemConfigWidget;
-class DebuggerKitConfigWidget;
-
-// -----------------------------------------------------------------------
-// DebuggerItemConfigWidget
-// -----------------------------------------------------------------------
-
-class DebuggerItemConfigWidget : public QWidget
-{
- Q_OBJECT
-
-public:
- explicit DebuggerItemConfigWidget(DebuggerItemModel *model);
- void setItem(const DebuggerItem &item);
- void apply();
-
-private slots:
- void binaryPathHasChanged();
-
-private:
- DebuggerItem item() const;
- void store() const;
- void setAbis(const QStringList &abiNames);
-
- void handleCommandChange();
-
- QLineEdit *m_displayNameLineEdit;
- QLabel *m_cdbLabel;
- QLineEdit *m_versionLabel;
- Utils::PathChooser *m_binaryChooser;
- QLineEdit *m_abis;
- DebuggerItemModel *m_model;
- bool m_autodetected;
- DebuggerEngineType m_engineType;
- QVariant m_id;
-};
-
-// --------------------------------------------------------------------------
-// DebuggerOptionsPage
-// --------------------------------------------------------------------------
+class DebuggerConfigWidget;
class DebuggerOptionsPage : public Core::IOptionsPage
{
- Q_OBJECT
+ Q_DECLARE_TR_FUNCTIONS(Debugger::DebuggerOptionsPage)
public:
DebuggerOptionsPage();
@@ -106,24 +52,8 @@ public:
void apply();
void finish();
-private slots:
- void debuggerSelectionChanged();
- void debuggerModelChanged();
- void updateState();
- void cloneDebugger();
- void addDebugger();
- void removeDebugger();
-
private:
- QPointer<QWidget> m_configWidget;
-
- DebuggerItemModel *m_model;
- DebuggerItemConfigWidget *m_itemConfigWidget;
- QTreeView *m_debuggerView;
- Utils::DetailsWidget *m_container;
- QPushButton *m_addButton;
- QPushButton *m_cloneButton;
- QPushButton *m_delButton;
+ QPointer<DebuggerConfigWidget> m_configWidget;
};
} // namespace Internal
diff --git a/src/plugins/debugger/debuggerplugin.cpp b/src/plugins/debugger/debuggerplugin.cpp
index aaddbd5e9d5..6ab869034c0 100644
--- a/src/plugins/debugger/debuggerplugin.cpp
+++ b/src/plugins/debugger/debuggerplugin.cpp
@@ -78,6 +78,7 @@
#include <coreplugin/imode.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <coreplugin/messagemanager.h>
#include <coreplugin/modemanager.h>
@@ -93,6 +94,7 @@
#include <projectexplorer/devicesupport/deviceprocesslist.h>
#include <projectexplorer/devicesupport/deviceprocessesdialog.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/projectexplorersettings.h>
#include <projectexplorer/project.h>
#include <projectexplorer/session.h>
@@ -387,19 +389,6 @@ namespace PE = ProjectExplorer::Constants;
namespace Debugger {
namespace Internal {
-// To be passed through margin menu action's data
-struct BreakpointMenuContextData : public ContextData
-{
- enum Mode
- {
- Breakpoint,
- MessageTracePoint
- };
-
- BreakpointMenuContextData() : mode(Breakpoint) {}
- Mode mode;
-};
-
struct TestCallBack
{
TestCallBack() : receiver(0), slot(0) {}
@@ -414,27 +403,13 @@ struct TestCallBack
} // namespace Internal
} // namespace Debugger
-Q_DECLARE_METATYPE(Debugger::Internal::BreakpointMenuContextData)
Q_DECLARE_METATYPE(Debugger::Internal::TestCallBack)
-
namespace Debugger {
namespace Internal {
-// FIXME: Outdated?
-// The createCdbEngine function takes a list of options pages it can add to.
-// This allows for having a "enabled" toggle on the page independently
-// of the engine. That's good for not enabling the related ActiveX control
-// unnecessarily.
-
void addCdbOptionPages(QList<IOptionsPage*> *opts);
void addGdbOptionPages(QList<IOptionsPage*> *opts);
-void addScriptOptionPages(QList<IOptionsPage*> *opts);
-void addTcfOptionPages(QList<IOptionsPage*> *opts);
-
-#ifdef WITH_LLDB
-void addLldbOptionPages(QList<IOptionsPage*> *opts);
-#endif
static QToolButton *toolButton(QAction *action)
{
@@ -443,12 +418,12 @@ static QToolButton *toolButton(QAction *action)
return button;
}
-static void setProxyAction(ProxyAction *proxy, Core::Id id)
+static void setProxyAction(ProxyAction *proxy, Id id)
{
proxy->setAction(ActionManager::command(id)->action());
}
-static QToolButton *toolButton(Core::Id id)
+static QToolButton *toolButton(Id id)
{
return toolButton(ActionManager::command(id)->action());
}
@@ -461,8 +436,6 @@ static QToolButton *toolButton(Core::Id id)
class DummyEngine : public DebuggerEngine
{
- Q_OBJECT
-
public:
DummyEngine() : DebuggerEngine(DebuggerStartParameters()) {}
~DummyEngine() {}
@@ -473,7 +446,7 @@ public:
void shutdownEngine() {}
void shutdownInferior() {}
bool hasCapability(unsigned cap) const;
- bool acceptsBreakpoint(BreakpointModelId) const { return false; }
+ bool acceptsBreakpoint(Breakpoint) const { return false; }
bool acceptsDebuggerCommands() const { return false; }
void selectThread(ThreadId) {}
};
@@ -481,7 +454,7 @@ public:
bool DummyEngine::hasCapability(unsigned cap) const
{
// This can only be a first approximation of what to expect when running.
- Project *project = ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
if (!project)
return 0;
Target *target = project->activeTarget();
@@ -494,6 +467,7 @@ bool DummyEngine::hasCapability(unsigned cap) const
return cap & (WatchpointByAddressCapability
| BreakConditionCapability
| TracePointCapability
+ | OperateNativeMixed
| OperateByInstructionCapability);
// This is a Qml or unknown engine.
@@ -578,7 +552,7 @@ static bool currentTextEditorPosition(ContextData *data)
return false;
const TextDocument *document = textEditor->textDocument();
QTC_ASSERT(document, return false);
- data->fileName = document->filePath();
+ data->fileName = document->filePath().toString();
if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) {
int lineNumber = textEditor->currentLine();
QString line = textEditor->textDocument()->plainText()
@@ -639,7 +613,6 @@ public:
}
DebuggerRunControl *attachToRunningProcess(Kit *kit, DeviceProcessItem process);
-public slots:
void writeSettings()
{
m_debuggerSettings->writeSettings();
@@ -652,20 +625,16 @@ public slots:
m_currentEngine->selectThread(id);
}
- void breakpointSetMarginActionTriggered()
+ void breakpointSetMarginActionTriggered(bool isMessageOnly, const ContextData &data)
{
- const QAction *action = qobject_cast<const QAction *>(sender());
- QTC_ASSERT(action, return);
- const BreakpointMenuContextData data =
- action->data().value<BreakpointMenuContextData>();
QString message;
- if (data.mode == BreakpointMenuContextData::MessageTracePoint) {
+ if (isMessageOnly) {
if (data.address) {
//: Message tracepoint: Address hit.
message = tr("0x%1 hit").arg(data.address, 0, 16);
} else {
//: Message tracepoint: %1 file, %2 line %3 function hit.
- message = tr("%1:%2 %3() hit").arg(QFileInfo(data.fileName).fileName()).
+ message = tr("%1:%2 %3() hit").arg(FileName::fromString(data.fileName).fileName()).
arg(data.lineNumber).
arg(cppFunctionAt(data.fileName, data.lineNumber));
}
@@ -686,30 +655,6 @@ public slots:
toggleBreakpointByFileAndLine(data.fileName, data.lineNumber, message);
}
- void breakpointRemoveMarginActionTriggered()
- {
- const QAction *act = qobject_cast<QAction *>(sender());
- QTC_ASSERT(act, return);
- BreakpointModelId id = act->data().value<BreakpointModelId>();
- m_breakHandler->removeBreakpoint(id);
- }
-
- void breakpointEnableMarginActionTriggered()
- {
- const QAction *act = qobject_cast<QAction *>(sender());
- QTC_ASSERT(act, return);
- BreakpointModelId id = act->data().value<BreakpointModelId>();
- breakHandler()->setEnabled(id, true);
- }
-
- void breakpointDisableMarginActionTriggered()
- {
- const QAction *act = qobject_cast<QAction *>(sender());
- QTC_ASSERT(act, return);
- BreakpointModelId id = act->data().value<BreakpointModelId>();
- breakHandler()->setEnabled(id, false);
- }
-
void updateWatchersHeader(int section, int, int newSize)
{
m_watchersView->header()->resizeSection(section, newSize);
@@ -743,12 +688,12 @@ public slots:
}
}
- void editorOpened(Core::IEditor *editor);
- void updateBreakMenuItem(Core::IEditor *editor);
+ void editorOpened(IEditor *editor);
+ void updateBreakMenuItem(IEditor *editor);
void setBusyCursor(bool busy);
- void requestMark(TextEditor::TextEditorWidget *widget, int lineNumber,
- TextEditor::TextMarkRequestKind kind);
- void requestContextMenu(TextEditor::TextEditorWidget *widget,
+ void requestMark(TextEditorWidget *widget, int lineNumber,
+ TextMarkRequestKind kind);
+ void requestContextMenu(TextEditorWidget *widget,
int lineNumber, QMenu *menu);
void activatePreviousMode();
@@ -758,7 +703,7 @@ public slots:
const QString &tracePointMessage = QString());
void toggleBreakpointByAddress(quint64 address,
const QString &tracePointMessage = QString());
- void onModeChanged(Core::IMode *mode);
+ void onModeChanged(IMode *mode);
void onCoreAboutToOpen();
void showSettingsDialog();
void updateDebugWithoutDeployMenu();
@@ -776,7 +721,7 @@ public slots:
void attachToFoundProcess();
void continueOnAttach(Debugger::DebuggerState state);
void attachToQmlPort();
- void runScheduled();
+ Q_SLOT void runScheduled();
void attachCore();
void enableReverseDebuggingTriggered(const QVariant &value);
@@ -800,11 +745,11 @@ public slots:
void cleanupViews();
void setInitialState();
- void fontSettingsChanged(const TextEditor::FontSettings &settings);
+ void fontSettingsChanged(const FontSettings &settings);
void updateState(DebuggerEngine *engine);
void updateWatchersWindow(bool showWatch, bool showReturn);
- void onCurrentProjectChanged(ProjectExplorer::Project *project);
+ void onCurrentProjectChanged(Project *project);
void sessionLoaded();
void aboutToUnloadSession();
@@ -815,7 +760,7 @@ public slots:
#ifdef WITH_TESTS
public slots:
void testLoadProject(const QString &proFile, const TestCallBack &cb);
- void testProjectLoaded(ProjectExplorer::Project *project);
+ void testProjectLoaded(Project *project);
void testProjectEvaluated();
void testProjectBuilt(bool success);
void testUnloadProject();
@@ -957,31 +902,6 @@ public slots:
}
}
- void slotEditBreakpoint()
- {
- const QAction *act = qobject_cast<QAction *>(sender());
- QTC_ASSERT(act, return);
- const BreakpointModelId id = act->data().value<BreakpointModelId>();
- QTC_ASSERT(id > 0, return);
- BreakTreeView::editBreakpoint(id, ICore::dialogParent());
- }
-
- void slotRunToLine()
- {
- const QAction *action = qobject_cast<const QAction *>(sender());
- QTC_ASSERT(action, return);
- const BreakpointMenuContextData data = action->data().value<BreakpointMenuContextData>();
- currentEngine()->executeRunToLine(data);
- }
-
- void slotJumpToLine()
- {
- const QAction *action = qobject_cast<const QAction *>(sender());
- QTC_ASSERT(action, return);
- const BreakpointMenuContextData data = action->data().value<BreakpointMenuContextData>();
- currentEngine()->executeJumpToLine(data);
- }
-
void slotDisassembleFunction()
{
const QAction *action = qobject_cast<const QAction *>(sender());
@@ -1356,9 +1276,9 @@ bool DebuggerPluginPrivate::initialize(const QStringList &arguments,
// Cpp/Qml ui setup
m_mainWindow = new DebuggerMainWindow;
- TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO,
+ TaskHub::addCategory(TASK_CATEGORY_DEBUGGER_DEBUGINFO,
tr("Debug Information"));
- TaskHub::addCategory(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME,
+ TaskHub::addCategory(TASK_CATEGORY_DEBUGGER_RUNTIME,
tr("Debugger Runtime"));
return true;
@@ -1410,7 +1330,7 @@ void DebuggerPluginPrivate::onCurrentProjectChanged(Project *project)
m_startAction->setEnabled(canRun);
m_startAction->setToolTip(whyNot);
m_debugWithoutDeployAction->setEnabled(canRun);
- setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
+ setProxyAction(m_visibleStartAction, Id(Constants::DEBUG));
}
void DebuggerPluginPrivate::debugProject()
@@ -1521,7 +1441,7 @@ void DebuggerPluginPrivate::attachToProcess(bool startServerOnly)
DebuggerKitChooser::RemoteDebugging : DebuggerKitChooser::LocalDebugging;
DebuggerKitChooser *kitChooser = new DebuggerKitChooser(mode);
DeviceProcessesDialog *dlg = new DeviceProcessesDialog(kitChooser, ICore::dialogParent());
- dlg->addAcceptButton(ProjectExplorer::DeviceProcessesDialog::tr("&Attach to Process"));
+ dlg->addAcceptButton(DeviceProcessesDialog::tr("&Attach to Process"));
dlg->showAllDevices();
if (dlg->exec() == QDialog::Rejected) {
delete dlg;
@@ -1588,8 +1508,8 @@ DebuggerRunControl *DebuggerPluginPrivate::attachToRunningProcess(Kit *kit,
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
QTC_ASSERT(device, return 0);
if (process.pid == 0) {
- QMessageBox::warning(ICore::dialogParent(), tr("Warning"),
- tr("Cannot attach to process with PID 0"));
+ AsynchronousMessageBox::warning(tr("Warning"),
+ tr("Cannot attach to process with PID 0"));
return 0;
}
@@ -1597,14 +1517,14 @@ DebuggerRunControl *DebuggerPluginPrivate::attachToRunningProcess(Kit *kit,
if (const ToolChain *tc = ToolChainKitInformation::toolChain(kit))
isWindows = tc->targetAbi().os() == Abi::WindowsOS;
if (isWindows && isWinProcessBeingDebugged(process.pid)) {
- QMessageBox::warning(ICore::mainWindow(), tr("Process Already Under Debugger Control"),
+ AsynchronousMessageBox::warning(tr("Process Already Under Debugger Control"),
tr("The process %1 is already under the control of a debugger.\n"
"Qt Creator cannot attach to it.").arg(process.pid));
return 0;
}
if (device->type() != PE::DESKTOP_DEVICE_TYPE) {
- QMessageBox::warning(ICore::mainWindow(), tr("Not a Desktop Device Type"),
+ AsynchronousMessageBox::warning(tr("Not a Desktop Device Type"),
tr("It is only possible to attach to a locally running process."));
return 0;
}
@@ -1727,13 +1647,13 @@ void DebuggerPluginPrivate::updateBreakMenuItem(IEditor *editor)
void DebuggerPluginPrivate::requestContextMenu(TextEditorWidget *widget,
int lineNumber, QMenu *menu)
{
- BreakpointMenuContextData args;
+ ContextData args;
args.lineNumber = lineNumber;
bool contextUsable = true;
- BreakpointModelId id = BreakpointModelId();
+ Breakpoint bp;
TextDocument *document = widget->textDocument();
- args.fileName = document->filePath();
+ args.fileName = document->filePath().toString();
if (document->property(Constants::OPENED_WITH_DISASSEMBLY).toBool()) {
QString line = document->plainText()
.section(QLatin1Char('\n'), lineNumber - 1, lineNumber - 1);
@@ -1742,87 +1662,77 @@ void DebuggerPluginPrivate::requestContextMenu(TextEditorWidget *widget,
needle.address = DisassemblerLine::addressFromDisassemblyLine(line);
args.address = needle.address;
needle.lineNumber = -1;
- id = breakHandler()->findSimilarBreakpoint(needle);
+ bp = breakHandler()->findSimilarBreakpoint(needle);
contextUsable = args.address != 0;
} else {
- id = breakHandler()
+ bp = breakHandler()
->findBreakpointByFileAndLine(args.fileName, lineNumber);
- if (!id)
- id = breakHandler()->findBreakpointByFileAndLine(args.fileName, lineNumber, false);
+ if (!bp)
+ bp = breakHandler()->findBreakpointByFileAndLine(args.fileName, lineNumber, false);
}
- if (id) {
+ if (bp) {
+ QString id = bp.id().toString();
+
// Remove existing breakpoint.
- QAction *act = new QAction(menu);
- act->setData(QVariant::fromValue(id));
- act->setText(tr("Remove Breakpoint %1").arg(id.toString()));
- connect(act, SIGNAL(triggered()),
- SLOT(breakpointRemoveMarginActionTriggered()));
- menu->addAction(act);
+ auto act = menu->addAction(tr("Remove Breakpoint %1").arg(id));
+ connect(act, &QAction::triggered, [bp] { bp.removeBreakpoint(); });
// Enable/disable existing breakpoint.
- act = new QAction(menu);
- act->setData(QVariant::fromValue(id));
- if (breakHandler()->isEnabled(id)) {
- act->setText(tr("Disable Breakpoint %1").arg(id.toString()));
- connect(act, SIGNAL(triggered()),
- SLOT(breakpointDisableMarginActionTriggered()));
+ if (bp.isEnabled()) {
+ act = menu->addAction(tr("Disable Breakpoint %1").arg(id));
+ connect(act, &QAction::triggered, [bp] { bp.setEnabled(false); });
} else {
- act->setText(tr("Enable Breakpoint %1").arg(id.toString()));
- connect(act, SIGNAL(triggered()),
- SLOT(breakpointEnableMarginActionTriggered()));
+ act = menu->addAction(tr("Enable Breakpoint %1").arg(id));
+ connect(act, &QAction::triggered, [bp] { bp.setEnabled(true); });
}
- menu->addAction(act);
// Edit existing breakpoint.
- act = new QAction(menu);
- act->setText(tr("Edit Breakpoint %1...").arg(id.toString()));
- connect(act, SIGNAL(triggered()), SLOT(slotEditBreakpoint()));
- act->setData(QVariant::fromValue(id));
- menu->addAction(act);
+ act = menu->addAction(tr("Edit Breakpoint %1...").arg(id));
+ connect(act, &QAction::triggered, [bp] {
+ BreakTreeView::editBreakpoint(bp, ICore::dialogParent());
+ });
+
} else {
// Handle non-existing breakpoint.
const QString text = args.address
? tr("Set Breakpoint at 0x%1").arg(args.address, 0, 16)
: tr("Set Breakpoint at Line %1").arg(lineNumber);
- QAction *act = new QAction(text, menu);
- act->setData(QVariant::fromValue(args));
+ auto act = menu->addAction(text);
act->setEnabled(contextUsable);
- connect(act, SIGNAL(triggered()),
- SLOT(breakpointSetMarginActionTriggered()));
- menu->addAction(act);
+ connect(act, &QAction::triggered, [this, args] {
+ breakpointSetMarginActionTriggered(false, args);
+ });
+
// Message trace point
- args.mode = BreakpointMenuContextData::MessageTracePoint;
const QString tracePointText = args.address
? tr("Set Message Tracepoint at 0x%1...").arg(args.address, 0, 16)
: tr("Set Message Tracepoint at Line %1...").arg(lineNumber);
- act = new QAction(tracePointText, menu);
- act->setData(QVariant::fromValue(args));
+ act = menu->addAction(tracePointText);
act->setEnabled(contextUsable);
- connect(act, SIGNAL(triggered()),
- SLOT(breakpointSetMarginActionTriggered()));
- menu->addAction(act);
+ connect(act, &QAction::triggered, [this, args] {
+ breakpointSetMarginActionTriggered(true, args);
+ });
}
+
// Run to, jump to line below in stopped state.
if (currentEngine()->state() == InferiorStopOk && contextUsable) {
menu->addSeparator();
if (currentEngine()->hasCapability(RunToLineCapability)) {
- const QString runText = args.address
+ auto act = menu->addAction(args.address
? DebuggerEngine::tr("Run to Address 0x%1").arg(args.address, 0, 16)
- : DebuggerEngine::tr("Run to Line %1").arg(args.lineNumber);
- QAction *runToLineAction = new QAction(runText, menu);
- runToLineAction->setData(QVariant::fromValue(args));
- connect(runToLineAction, SIGNAL(triggered()), SLOT(slotRunToLine()));
- menu->addAction(runToLineAction);
+ : DebuggerEngine::tr("Run to Line %1").arg(args.lineNumber));
+ connect(act, &QAction::triggered, [this, args] {
+ currentEngine()->executeRunToLine(args);
+ });
}
if (currentEngine()->hasCapability(JumpToLineCapability)) {
- const QString jumpText = args.address
+ auto act = menu->addAction(args.address
? DebuggerEngine::tr("Jump to Address 0x%1").arg(args.address, 0, 16)
- : DebuggerEngine::tr("Jump to Line %1").arg(args.lineNumber);
- QAction *jumpToLineAction = new QAction(jumpText, menu);
- jumpToLineAction->setData(QVariant::fromValue(args));
- connect(jumpToLineAction, SIGNAL(triggered()), SLOT(slotJumpToLine()));
- menu->addAction(jumpToLineAction);
+ : DebuggerEngine::tr("Jump to Line %1").arg(args.lineNumber));
+ connect(act, &QAction::triggered, [this, args] {
+ currentEngine()->executeJumpToLine(args);
+ });
}
// Disassemble current function in stopped state.
if (currentEngine()->state() == InferiorStopOk
@@ -1835,7 +1745,7 @@ void DebuggerPluginPrivate::requestContextMenu(TextEditorWidget *widget,
.arg(frame.function);
QAction *disassembleAction = new QAction(text, menu);
disassembleAction->setData(QVariant::fromValue(frame));
- connect(disassembleAction, SIGNAL(triggered()), SLOT(slotDisassembleFunction()));
+ connect(disassembleAction, &QAction::triggered, this, &DebuggerPluginPrivate::slotDisassembleFunction);
menu->addAction(disassembleAction );
}
}
@@ -1853,7 +1763,7 @@ void DebuggerPluginPrivate::toggleBreakpoint()
quint64 address = DisassemblerLine::addressFromDisassemblyLine(line);
toggleBreakpointByAddress(address);
} else if (lineNumber >= 0) {
- toggleBreakpointByFileAndLine(textEditor->document()->filePath(), lineNumber);
+ toggleBreakpointByFileAndLine(textEditor->document()->filePath().toString(), lineNumber);
}
}
@@ -1861,13 +1771,12 @@ void DebuggerPluginPrivate::toggleBreakpointByFileAndLine(const QString &fileNam
int lineNumber, const QString &tracePointMessage)
{
BreakHandler *handler = m_breakHandler;
- BreakpointModelId id =
- handler->findBreakpointByFileAndLine(fileName, lineNumber, true);
- if (!id)
- id = handler->findBreakpointByFileAndLine(fileName, lineNumber, false);
+ Breakpoint bp = handler->findBreakpointByFileAndLine(fileName, lineNumber, true);
+ if (!bp)
+ bp = handler->findBreakpointByFileAndLine(fileName, lineNumber, false);
- if (id) {
- handler->removeBreakpoint(id);
+ if (bp) {
+ bp.removeBreakpoint();
} else {
BreakpointParameters data(BreakpointByFileAndLine);
if (boolSetting(BreakpointsFullPathByDefault))
@@ -1884,10 +1793,8 @@ void DebuggerPluginPrivate::toggleBreakpointByAddress(quint64 address,
const QString &tracePointMessage)
{
BreakHandler *handler = m_breakHandler;
- BreakpointModelId id = handler->findBreakpointByAddress(address);
-
- if (id) {
- handler->removeBreakpoint(id);
+ if (Breakpoint bp = handler->findBreakpointByAddress(address)) {
+ bp.removeBreakpoint();
} else {
BreakpointParameters data(BreakpointByAddress);
data.tracepoint = !tracePointMessage.isEmpty();
@@ -1910,7 +1817,7 @@ void DebuggerPluginPrivate::requestMark(TextEditorWidget *widget, int lineNumber
quint64 address = DisassemblerLine::addressFromDisassemblyLine(line);
toggleBreakpointByAddress(address);
} else {
- toggleBreakpointByFileAndLine(document->filePath(), lineNumber);
+ toggleBreakpointByFileAndLine(document->filePath().toString(), lineNumber);
}
}
@@ -1958,7 +1865,7 @@ static void changeFontSize(QWidget *widget, qreal size)
}
void DebuggerPluginPrivate::fontSettingsChanged
- (const TextEditor::FontSettings &settings)
+ (const FontSettings &settings)
{
if (!boolSetting(FontSizeFollowsEditor))
return;
@@ -1992,7 +1899,7 @@ void DebuggerPluginPrivate::cleanupViews()
bool keepIt = true;
if (document->isModified())
keepIt = true;
- else if (document->filePath().contains(_("qeventdispatcher")))
+ else if (document->filePath().toString().contains(_("qeventdispatcher")))
keepIt = false;
else if (isMemory)
keepIt = !closeMemory;
@@ -2069,7 +1976,6 @@ void DebuggerPluginPrivate::setInitialState()
action(AutoDerefPointers)->setEnabled(true);
action(ExpandStack)->setEnabled(false);
-
}
void DebuggerPluginPrivate::updateWatchersWindow(bool showWatch, bool showReturn)
@@ -2107,7 +2013,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(false);
m_startAction->setEnabled(true);
m_debugWithoutDeployAction->setEnabled(true);
- setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
+ setProxyAction(m_visibleStartAction, Id(Constants::DEBUG));
m_hiddenStopAction->setAction(m_undisturbableAction);
} else if (state == InferiorStopOk) {
// F5 continues, Shift-F5 kills. It is "continuable".
@@ -2116,7 +2022,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(true);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
- setProxyAction(m_visibleStartAction, Core::Id(Constants::CONTINUE));
+ setProxyAction(m_visibleStartAction, Id(Constants::CONTINUE));
m_hiddenStopAction->setAction(m_exitAction);
m_localsAndExpressionsWindow->setShowLocals(true);
} else if (state == InferiorRunOk) {
@@ -2126,7 +2032,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(true);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
- setProxyAction(m_visibleStartAction, Core::Id(Constants::INTERRUPT));
+ setProxyAction(m_visibleStartAction, Id(Constants::INTERRUPT));
m_hiddenStopAction->setAction(m_interruptAction);
m_localsAndExpressionsWindow->setShowLocals(false);
} else if (state == DebuggerFinished) {
@@ -2138,7 +2044,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(false);
m_startAction->setEnabled(canRun);
m_debugWithoutDeployAction->setEnabled(canRun);
- setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
+ setProxyAction(m_visibleStartAction, Id(Constants::DEBUG));
m_hiddenStopAction->setAction(m_undisturbableAction);
m_codeModelSnapshot = CPlusPlus::Snapshot();
setBusyCursor(false);
@@ -2526,16 +2432,27 @@ QMessageBox *showMessageBox(int icon, const QString &title,
return mb;
}
+bool isNativeMixedEnabled()
+{
+ static bool enabled = qEnvironmentVariableIsSet("QTC_DEBUGGER_NATIVE_MIXED");
+ return enabled;
+}
+
+bool isNativeMixedActive()
+{
+ return isNativeMixedEnabled() && boolSetting(OperateNativeMixed);
+}
+
void DebuggerPluginPrivate::extensionsInitialized()
{
const QKeySequence debugKey = QKeySequence(UseMacShortcuts ? tr("Ctrl+Y") : tr("F5"));
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
m_debuggerSettings = new DebuggerSettings;
m_debuggerSettings->readSettings();
- connect(ICore::instance(), SIGNAL(coreAboutToClose()), this, SLOT(coreShutdown()));
+ connect(ICore::instance(), &ICore::coreAboutToClose, this, &DebuggerPluginPrivate::coreShutdown);
const Context globalcontext(CC::C_GLOBAL);
const Context cppDebuggercontext(C_CPPDEBUGGER);
@@ -2608,22 +2525,22 @@ void DebuggerPluginPrivate::extensionsInitialized()
m_snapshotWindow = addSearch(m_snapshotView, tr("Snapshots"), DOCKWIDGET_SNAPSHOTS);
// Watchers
- connect(m_localsView->header(), SIGNAL(sectionResized(int,int,int)),
- SLOT(updateWatchersHeader(int,int,int)), Qt::QueuedConnection);
+ connect(m_localsView->header(), &QHeaderView::sectionResized,
+ this, &DebuggerPluginPrivate::updateWatchersHeader, Qt::QueuedConnection);
QAction *act = 0;
act = m_continueAction = new QAction(tr("Continue"), this);
act->setIcon(m_continueIcon);
- connect(act, SIGNAL(triggered()), SLOT(handleExecContinue()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecContinue);
act = m_exitAction = new QAction(tr("Stop Debugger"), this);
act->setIcon(m_exitIcon);
- connect(act, SIGNAL(triggered()), SLOT(handleExecExit()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecExit);
act = m_interruptAction = new QAction(tr("Interrupt"), this);
act->setIcon(m_interruptIcon);
- connect(act, SIGNAL(triggered()), SLOT(handleExecInterrupt()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecInterrupt);
// A "disabled pause" seems to be a good choice.
act = m_undisturbableAction = new QAction(tr("Debugger is Busy"), this);
@@ -2633,46 +2550,46 @@ void DebuggerPluginPrivate::extensionsInitialized()
act = m_abortAction = new QAction(tr("Abort Debugging"), this);
act->setToolTip(tr("Aborts debugging and "
"resets the debugger to the initial state."));
- connect(act, SIGNAL(triggered()), SLOT(handleAbort()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAbort);
act = m_resetAction = new QAction(tr("Restart Debugging"),this);
act->setToolTip(tr("Restart the debugging session."));
act->setIcon(m_resetIcon);
- connect(act,SIGNAL(triggered()),SLOT(handleReset()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleReset);
act = m_nextAction = new QAction(tr("Step Over"), this);
act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepover_small.png")));
- connect(act, SIGNAL(triggered()), SLOT(handleExecNext()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecNext);
act = m_stepAction = new QAction(tr("Step Into"), this);
act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepinto_small.png")));
- connect(act, SIGNAL(triggered()), SLOT(handleExecStep()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecStep);
act = m_stepOutAction = new QAction(tr("Step Out"), this);
act->setIcon(QIcon(QLatin1String(":/debugger/images/debugger_stepout_small.png")));
- connect(act, SIGNAL(triggered()), SLOT(handleExecStepOut()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecStepOut);
act = m_runToLineAction = new QAction(tr("Run to Line"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleExecRunToLine()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecRunToLine);
act = m_runToSelectedFunctionAction =
new QAction(tr("Run to Selected Function"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleExecRunToSelectedFunction()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecRunToSelectedFunction);
act = m_returnFromFunctionAction =
new QAction(tr("Immediately Return From Inner Function"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleExecReturn()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecReturn);
act = m_jumpToLineAction = new QAction(tr("Jump to Line"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleExecJumpToLine()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecJumpToLine);
m_breakAction = new QAction(tr("Toggle Breakpoint"), this);
act = m_watchAction1 = new QAction(tr("Add Expression Evaluator"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleAddToWatchWindow()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAddToWatchWindow);
act = m_watchAction2 = new QAction(tr("Add Expression Evaluator"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleAddToWatchWindow()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleAddToWatchWindow);
//m_snapshotAction = new QAction(tr("Create Snapshot"), this);
//m_snapshotAction->setProperty(Role, RequestCreateSnapshotRole);
@@ -2688,10 +2605,10 @@ void DebuggerPluginPrivate::extensionsInitialized()
act->setIconVisibleInMenu(false);
act = m_frameDownAction = new QAction(tr("Move to Called Frame"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleFrameDown()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleFrameDown);
act = m_frameUpAction = new QAction(tr("Move to Calling Frame"), this);
- connect(act, SIGNAL(triggered()), SLOT(handleFrameUp()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleFrameUp);
connect(action(OperateByInstruction), SIGNAL(triggered(bool)),
SLOT(handleOperateByInstructionTriggered(bool)));
@@ -2701,16 +2618,16 @@ void DebuggerPluginPrivate::extensionsInitialized()
// Dock widgets
QDockWidget *dock = 0;
dock = m_mainWindow->createDockWidget(CppLanguage, m_modulesWindow);
- connect(dock->toggleViewAction(), SIGNAL(toggled(bool)),
- SLOT(modulesDockToggled(bool)), Qt::QueuedConnection);
+ connect(dock->toggleViewAction(), &QAction::toggled,
+ this, &DebuggerPluginPrivate::modulesDockToggled, Qt::QueuedConnection);
dock = m_mainWindow->createDockWidget(CppLanguage, m_registerWindow);
- connect(dock->toggleViewAction(), SIGNAL(toggled(bool)),
- SLOT(registerDockToggled(bool)), Qt::QueuedConnection);
+ connect(dock->toggleViewAction(), &QAction::toggled,
+ this, &DebuggerPluginPrivate::registerDockToggled, Qt::QueuedConnection);
dock = m_mainWindow->createDockWidget(CppLanguage, m_sourceFilesWindow);
- connect(dock->toggleViewAction(), SIGNAL(toggled(bool)),
- SLOT(sourceFilesDockToggled(bool)), Qt::QueuedConnection);
+ connect(dock->toggleViewAction(), &QAction::toggled,
+ this, &DebuggerPluginPrivate::sourceFilesDockToggled, Qt::QueuedConnection);
dock = m_mainWindow->createDockWidget(AnyLanguage, m_logWindow);
dock->setProperty(DOCKWIDGET_DEFAULT_AREA, Qt::TopDockWidgetArea);
@@ -2741,49 +2658,49 @@ void DebuggerPluginPrivate::extensionsInitialized()
debuggerIcon.addFile(QLatin1String(":/projectexplorer/images/debugger_start.png"));
act->setIcon(debuggerIcon);
act->setText(tr("Start Debugging"));
- connect(act, SIGNAL(triggered()), this, SLOT(debugProject()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::debugProject);
act = m_debugWithoutDeployAction = new QAction(this);
act->setText(tr("Start Debugging Without Deployment"));
- connect(act, SIGNAL(triggered()), this, SLOT(debugProjectWithoutDeploy()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::debugProjectWithoutDeploy);
act = m_startAndDebugApplicationAction = new QAction(this);
act->setText(tr("Start and Debug External Application..."));
- connect(act, SIGNAL(triggered()), SLOT(startAndDebugApplication()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::startAndDebugApplication);
act = m_attachToCoreAction = new QAction(this);
act->setText(tr("Load Core File..."));
- connect(act, SIGNAL(triggered()), SLOT(attachCore()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachCore);
act = m_attachToRemoteServerAction = new QAction(this);
act->setText(tr("Attach to Remote Debug Server..."));
- connect(act, SIGNAL(triggered()), SLOT(attachToRemoteServer()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToRemoteServer);
act = m_startRemoteServerAction = new QAction(this);
act->setText(tr("Start Remote Debug Server Attached to Process..."));
- connect(act, SIGNAL(triggered()), SLOT(startRemoteServer()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::startRemoteServer);
act = m_attachToRunningApplication = new QAction(this);
act->setText(tr("Attach to Running Application..."));
- connect(act, SIGNAL(triggered()), SLOT(attachToRunningApplication()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToRunningApplication);
act = m_attachToUnstartedApplication = new QAction(this);
act->setText(tr("Attach to Unstarted Application..."));
- connect(act, SIGNAL(triggered()), SLOT(attachToUnstartedApplicationDialog()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToUnstartedApplicationDialog);
act = m_attachToQmlPortAction = new QAction(this);
act->setText(tr("Attach to QML Port..."));
- connect(act, SIGNAL(triggered()), SLOT(attachToQmlPort()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::attachToQmlPort);
if (HostOsInfo::isWindowsHost()) {
m_startRemoteCdbAction = new QAction(tr("Attach to Remote CDB Session..."), this);
- connect(m_startRemoteCdbAction, SIGNAL(triggered()),
- SLOT(startRemoteCdbSession()));
+ connect(m_startRemoteCdbAction, &QAction::triggered,
+ this, &DebuggerPluginPrivate::startRemoteCdbSession);
}
act = m_detachAction = new QAction(this);
act->setText(tr("Detach Debugger"));
- connect(act, SIGNAL(triggered()), SLOT(handleExecDetach()));
+ connect(act, &QAction::triggered, this, &DebuggerPluginPrivate::handleExecDetach);
// "Start Debugging" sub-menu
// groups:
@@ -2816,17 +2733,17 @@ void DebuggerPluginPrivate::extensionsInitialized()
cmd = ActionManager::registerAction(m_attachToRunningApplication,
"Debugger.AttachToRemoteProcess", globalcontext);
cmd->setDescription(tr("Attach to Running Application"));
- mstart->addAction(cmd, Debugger::Constants::G_GENERAL);
+ mstart->addAction(cmd, G_GENERAL);
cmd = ActionManager::registerAction(m_attachToUnstartedApplication,
"Debugger.AttachToUnstartedProcess", globalcontext);
cmd->setDescription(tr("Attach to Unstarted Application"));
- mstart->addAction(cmd, Debugger::Constants::G_GENERAL);
+ mstart->addAction(cmd, G_GENERAL);
cmd = ActionManager::registerAction(m_startAndDebugApplicationAction,
"Debugger.StartAndDebugApplication", globalcontext);
cmd->setAttribute(Command::CA_Hide);
- mstart->addAction(cmd, Debugger::Constants::G_GENERAL);
+ mstart->addAction(cmd, G_GENERAL);
cmd = ActionManager::registerAction(m_attachToCoreAction,
"Debugger.AttachCore", globalcontext);
@@ -2964,12 +2881,23 @@ void DebuggerPluginPrivate::extensionsInitialized()
cmd->setAttribute(Command::CA_Hide);
debugMenu->addAction(cmd);
+ if (isNativeMixedEnabled()) {
+ SavedAction *act = action(OperateNativeMixed);
+ act->setValue(true);
+ cmd = ActionManager::registerAction(act,
+ Constants::OPERATE_NATIVE_MIXED, globalcontext);
+ cmd->setAttribute(Command::CA_Hide);
+ debugMenu->addAction(cmd);
+ connect(cmd->action(), &QAction::triggered,
+ [this] { currentEngine()->updateAll(); });
+ }
+
cmd = ActionManager::registerAction(m_breakAction,
"Debugger.ToggleBreak", globalcontext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("F8") : tr("F9")));
debugMenu->addAction(cmd);
- connect(m_breakAction, SIGNAL(triggered()),
- SLOT(toggleBreakpoint()));
+ connect(m_breakAction, &QAction::triggered,
+ this, &DebuggerPluginPrivate::toggleBreakpoint);
debugMenu->addSeparator(globalcontext);
@@ -3032,32 +2960,26 @@ void DebuggerPluginPrivate::extensionsInitialized()
QList<IOptionsPage *> engineOptionPages;
addGdbOptionPages(&engineOptionPages);
addCdbOptionPages(&engineOptionPages);
-#ifdef WITH_LLDB
- addLldbOptionPages(&engineOptionPages);
-#endif
-
- // addScriptOptionPages(&engineOptionPages);
- // addTcfOptionPages(&engineOptionPages);
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*)));
- connect(ICore::instance(), SIGNAL(coreAboutToOpen()),
- SLOT(onCoreAboutToOpen()));
- connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
- this, SLOT(updateDebugWithoutDeployMenu()));
+ connect(ModeManager::instance(), &ModeManager::currentModeChanged,
+ this, &DebuggerPluginPrivate::onModeChanged);
+ connect(ICore::instance(), &ICore::coreAboutToOpen,
+ this, &DebuggerPluginPrivate::onCoreAboutToOpen);
+ connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::settingsChanged,
+ this, &DebuggerPluginPrivate::updateDebugWithoutDeployMenu);
// Debug mode setup
DebugMode *debugMode = new DebugMode;
QWidget *widget = m_mainWindow->createContents(debugMode);
- Core::IContext *modeContextObject = new Core::IContext(this);
- modeContextObject->setContext(Core::Context(CC::C_EDITORMANAGER));
+ IContext *modeContextObject = new IContext(this);
+ modeContextObject->setContext(Context(CC::C_EDITORMANAGER));
modeContextObject->setWidget(widget);
- Core::ICore::addContextObject(modeContextObject);
+ ICore::addContextObject(modeContextObject);
debugMode->setWidget(widget);
m_plugin->addAutoReleasedObject(debugMode);
@@ -3112,6 +3034,8 @@ void DebuggerPluginPrivate::extensionsInitialized()
hbox->addWidget(toolButton(Constants::STEPOUT));
hbox->addWidget(toolButton(Constants::RESET));
hbox->addWidget(toolButton(Constants::OPERATE_BY_INSTRUCTION));
+ if (isNativeMixedEnabled())
+ hbox->addWidget(toolButton(Constants::OPERATE_NATIVE_MIXED));
//hbox->addWidget(new StyledSeparator);
m_reverseToolButton = toolButton(Constants::REVERSE);
@@ -3347,8 +3271,11 @@ bool isDockVisible(const QString &objectName)
void openMemoryEditor()
{
AddressDialog dialog;
- if (dialog.exec() == QDialog::Accepted)
- currentEngine()->openMemoryView(dialog.address(), 0, QList<MemoryMarkup>(), QPoint());
+ if (dialog.exec() == QDialog::Accepted) {
+ MemoryViewSetupData data;
+ data.startAddress = dialog.address();
+ currentEngine()->openMemoryView(data);
+ }
}
void setThreads(const QStringList &list, int index)
@@ -3437,7 +3364,7 @@ void DebuggerPlugin::extensionsInitialized()
void DebuggerPluginPrivate::testLoadProject(const QString &proFile, const TestCallBack &cb)
{
- connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::currentProjectChanged,
+ connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
this, &DebuggerPluginPrivate::testProjectLoaded);
m_testCallbacks.append(cb);
@@ -3471,7 +3398,7 @@ void DebuggerPluginPrivate::testProjectEvaluated()
QVERIFY(!fileName.isEmpty());
qWarning("Project %s loaded", qPrintable(fileName));
connect(BuildManager::instance(), SIGNAL(buildQueueFinished(bool)),
- SLOT(testProjectBuilt(bool)));
+ this, SLOT(testProjectBuilt(bool)));
ProjectExplorerPlugin::buildProject(m_testProject);
}
@@ -3578,7 +3505,7 @@ void DebuggerPluginPrivate::testBenchmark1()
{
#ifdef WITH_BENCHMARK
CALLGRIND_START_INSTRUMENTATION;
- volatile Core::Id id1 = Core::Id(DEBUGGER_COMMON_SETTINGS_ID);
+ volatile Id id1 = Id(DEBUGGER_COMMON_SETTINGS_ID);
CALLGRIND_STOP_INSTRUMENTATION;
CALLGRIND_DUMP_STATS;
diff --git a/src/plugins/debugger/debuggerprotocol.cpp b/src/plugins/debugger/debuggerprotocol.cpp
index 3bb5db075c8..5393e89d8f1 100644
--- a/src/plugins/debugger/debuggerprotocol.cpp
+++ b/src/plugins/debugger/debuggerprotocol.cpp
@@ -395,19 +395,19 @@ qulonglong GdbMi::toAddress() const
//
//////////////////////////////////////////////////////////////////////////////////
-QByteArray GdbResponse::stringFromResultClass(GdbResultClass resultClass)
+QByteArray DebuggerResponse::stringFromResultClass(ResultClass resultClass)
{
switch (resultClass) {
- case GdbResultDone: return "done";
- case GdbResultRunning: return "running";
- case GdbResultConnected: return "connected";
- case GdbResultError: return "error";
- case GdbResultExit: return "exit";
+ case ResultDone: return "done";
+ case ResultRunning: return "running";
+ case ResultConnected: return "connected";
+ case ResultError: return "error";
+ case ResultExit: return "exit";
default: return "unknown";
}
}
-QByteArray GdbResponse::toString() const
+QByteArray DebuggerResponse::toString() const
{
QByteArray result;
if (token != -1)
@@ -716,10 +716,136 @@ QString decodeData(const QByteArray &ba, int encoding)
}
return dateTime.toString();
}
+ case Hex2EncodedFloat4: {
+ const QByteArray s = QByteArray::fromHex(ba);
+ QTC_ASSERT(s.size() == 4, break);
+ union { char c[4]; float f; } u = { { s[3], s[2], s[1], s[0] } };
+ return QString::number(u.f);
+ }
+ case Hex2EncodedFloat8: {
+ const QByteArray s = QByteArray::fromHex(ba);
+ QTC_ASSERT(s.size() == 8, break);
+ union { char c[8]; double d; } u = { { s[7], s[6], s[5], s[4], s[3], s[2], s[1], s[0] } };
+ return QString::number(u.d);
+ }
}
qDebug() << "ENCODING ERROR: " << encoding;
return QCoreApplication::translate("Debugger", "<Encoding error>");
}
+//////////////////////////////////////////////////////////////////////////////////
+//
+// DebuggerCommand
+//
+//////////////////////////////////////////////////////////////////////////////////
+
+void DebuggerCommand::argHelper(const char *name, const QByteArray &data)
+{
+ args.append('"');
+ args.append(name);
+ args.append("\":");
+ args.append(data);
+ args.append(",");
+}
+
+QByteArray DebuggerCommand::toData(const QList<QByteArray> &value)
+{
+ QByteArray res;
+ foreach (const QByteArray &item, value) {
+ if (!res.isEmpty())
+ res.append(',');
+ res += item;
+ }
+ return '[' + res + ']';
+}
+
+QByteArray DebuggerCommand::toData(const QHash<QByteArray, QByteArray> &value)
+{
+ QByteArray res;
+ QHashIterator<QByteArray, QByteArray> it(value);
+ while (it.hasNext()) {
+ it.next();
+ if (!res.isEmpty())
+ res.append(',');
+ res += '"' + it.key() + "\":" + it.value();
+ }
+ return '{' + res + '}';
+}
+
+void DebuggerCommand::arg(const char *name, int value)
+{
+ argHelper(name, QByteArray::number(value));
+}
+
+void DebuggerCommand::arg(const char *name, qlonglong value)
+{
+ argHelper(name, QByteArray::number(value));
+}
+
+void DebuggerCommand::arg(const char *name, qulonglong value)
+{
+ argHelper(name, QByteArray::number(value));
+}
+
+void DebuggerCommand::arg(const char *name, const QString &value)
+{
+ arg(name, value.toUtf8().data());
+}
+
+void DebuggerCommand::arg(const char *name, const QByteArray &value)
+{
+ arg(name, value.data());
+}
+
+void DebuggerCommand::arg(const char *name, const char *value)
+{
+ args.append('"');
+ args.append(name);
+ args.append("\":\"");
+ args.append(value);
+ args.append("\",");
+}
+
+void DebuggerCommand::arg(const char *value)
+{
+ args.append("\"");
+ args.append(value);
+ args.append("\",");
+}
+
+void DebuggerCommand::beginList(const char *name)
+{
+ if (name) {
+ args += '"';
+ args += name;
+ args += "\":";
+ }
+ args += '[';
+}
+
+void DebuggerCommand::endList()
+{
+ if (args.endsWith(','))
+ args.chop(1);
+ args += "],";
+}
+
+void DebuggerCommand::beginGroup(const char *name)
+{
+ if (name) {
+ args += '"';
+ args += name;
+ args += "\":";
+ }
+ args += '{';
+}
+
+void DebuggerCommand::endGroup()
+{
+ if (args.endsWith(','))
+ args.chop(1);
+ args += "},";
+}
+
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/debuggerprotocol.h b/src/plugins/debugger/debuggerprotocol.h
index dc8908fe137..943fe8b4424 100644
--- a/src/plugins/debugger/debuggerprotocol.h
+++ b/src/plugins/debugger/debuggerprotocol.h
@@ -32,10 +32,52 @@
#define DEBUGGER_PROTOCOL_H
#include <QVariant>
+#include <QTime>
+
+#include <functional>
namespace Debugger {
namespace Internal {
+class DebuggerResponse;
+
+// Convenience structure to build up backend commands.
+class DebuggerCommand
+{
+public:
+ typedef std::function<void(const DebuggerResponse &)> Callback;
+
+ DebuggerCommand() : flags(0) {}
+ DebuggerCommand(const char *f, int flags = 0, Callback cb = Callback())
+ : function(f), callback(cb), flags(flags)
+ {}
+ DebuggerCommand(const QByteArray &f) : function(f), flags(0) {}
+
+ void arg(const char *name);
+ void arg(const char *name, int value);
+ void arg(const char *name, qlonglong value);
+ void arg(const char *name, qulonglong value);
+ void arg(const char *name, const QString &value);
+ void arg(const char *name, const QByteArray &value);
+ void arg(const char *name, const char *value);
+ void beginList(const char *name = 0);
+ void endList();
+ void beginGroup(const char *name = 0);
+ void endGroup();
+
+ static QByteArray toData(const QList<QByteArray> &value);
+ static QByteArray toData(const QHash<QByteArray, QByteArray> &value);
+
+ QByteArray function;
+ QByteArray args;
+ Callback callback;
+ QTime postTime;
+ int flags;
+
+private:
+ void argHelper(const char *name, const QByteArray &value);
+};
+
/*
output ==>
@@ -141,28 +183,27 @@ public:
void dumpChildren(QByteArray *str, bool multiline, int indent) const;
};
-enum GdbResultClass
+enum ResultClass
{
// "done" | "running" | "connected" | "error" | "exit"
- GdbResultUnknown,
- GdbResultDone,
- GdbResultRunning,
- GdbResultConnected,
- GdbResultError,
- GdbResultExit
+ ResultUnknown,
+ ResultDone,
+ ResultRunning,
+ ResultConnected,
+ ResultError,
+ ResultExit
};
-class GdbResponse
+class DebuggerResponse
{
public:
- GdbResponse() : token(-1), resultClass(GdbResultUnknown) {}
+ DebuggerResponse() : token(-1), resultClass(ResultUnknown) {}
QByteArray toString() const;
- static QByteArray stringFromResultClass(GdbResultClass resultClass);
+ static QByteArray stringFromResultClass(ResultClass resultClass);
int token;
- GdbResultClass resultClass;
+ ResultClass resultClass;
GdbMi data;
- QVariant cookie;
QByteArray logStreamOutput;
QByteArray consoleStreamOutput;
};
diff --git a/src/plugins/debugger/debuggerrunconfigurationaspect.cpp b/src/plugins/debugger/debuggerrunconfigurationaspect.cpp
index aba7ead634a..6356815491a 100644
--- a/src/plugins/debugger/debuggerrunconfigurationaspect.cpp
+++ b/src/plugins/debugger/debuggerrunconfigurationaspect.cpp
@@ -122,18 +122,18 @@ DebuggerRunConfigWidget::DebuggerRunConfigWidget(DebuggerRunConfigurationAspect
connect(m_qmlDebuggerInfoLabel, SIGNAL(linkActivated(QString)),
Core::HelpManager::instance(), SLOT(handleHelpRequest(QString)));
- connect(m_useQmlDebugger, SIGNAL(toggled(bool)),
- SLOT(useQmlDebuggerToggled(bool)));
- connect(m_useQmlDebugger, SIGNAL(clicked(bool)),
- SLOT(useQmlDebuggerClicked(bool)));
- connect(m_useCppDebugger, SIGNAL(clicked(bool)),
- SLOT(useCppDebuggerClicked(bool)));
- connect(m_debugServerPort, SIGNAL(valueChanged(int)),
- SLOT(qmlDebugServerPortChanged(int)));
- connect(m_useMultiProcess, SIGNAL(toggled(bool)),
- SLOT(useMultiProcessToggled(bool)));
-
- QHBoxLayout *qmlLayout = new QHBoxLayout;
+ connect(m_useQmlDebugger, &QAbstractButton::toggled,
+ this, &DebuggerRunConfigWidget::useQmlDebuggerToggled);
+ connect(m_useQmlDebugger, &QAbstractButton::clicked,
+ this, &DebuggerRunConfigWidget::useQmlDebuggerClicked);
+ connect(m_useCppDebugger, &QAbstractButton::clicked,
+ this, &DebuggerRunConfigWidget::useCppDebuggerClicked);
+ connect(m_debugServerPort, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged),
+ this, &DebuggerRunConfigWidget::qmlDebugServerPortChanged);
+ connect(m_useMultiProcess, &QAbstractButton::toggled,
+ this, &DebuggerRunConfigWidget::useMultiProcessToggled);
+
+ auto qmlLayout = new QHBoxLayout;
qmlLayout->setMargin(0);
qmlLayout->addWidget(m_useQmlDebugger);
qmlLayout->addWidget(m_debugServerPortLabel);
@@ -141,7 +141,7 @@ DebuggerRunConfigWidget::DebuggerRunConfigWidget(DebuggerRunConfigurationAspect
qmlLayout->addWidget(m_qmlDebuggerInfoLabel);
qmlLayout->addStretch();
- QVBoxLayout *layout = new QVBoxLayout;
+ auto layout = new QVBoxLayout;
layout->setMargin(0);
layout->addWidget(m_useCppDebugger);
layout->addLayout(qmlLayout);
@@ -234,13 +234,13 @@ DebuggerRunConfigurationAspect::DebuggerRunConfigurationAspect(
void DebuggerRunConfigurationAspect::setUseQmlDebugger(bool value)
{
m_useQmlDebugger = value ? EnabledLanguage : DisabledLanguage;
- emit requestRunActionsUpdate();
+ runConfiguration()->requestRunActionsUpdate();
}
void DebuggerRunConfigurationAspect::setUseCppDebugger(bool value)
{
m_useCppDebugger = value ? EnabledLanguage : DisabledLanguage;
- emit requestRunActionsUpdate();
+ runConfiguration()->requestRunActionsUpdate();
}
bool DebuggerRunConfigurationAspect::useCppDebugger() const
diff --git a/src/plugins/debugger/debuggerruncontrol.cpp b/src/plugins/debugger/debuggerruncontrol.cpp
index ea2c1bb61c3..48c5cb24d63 100644
--- a/src/plugins/debugger/debuggerruncontrol.cpp
+++ b/src/plugins/debugger/debuggerruncontrol.cpp
@@ -108,6 +108,13 @@ DebuggerRunControl::DebuggerRunControl(RunConfiguration *runConfiguration, Debug
{
setIcon(QLatin1String(ProjectExplorer::Constants::ICON_DEBUG_SMALL));
connect(this, &RunControl::finished, this, &DebuggerRunControl::handleFinished);
+
+ connect(engine, &DebuggerEngine::requestRemoteSetup,
+ this, &DebuggerRunControl::requestRemoteSetup);
+ connect(engine, &DebuggerEngine::stateChanged,
+ this, &DebuggerRunControl::stateChanged);
+ connect(engine, &DebuggerEngine::aboutToNotifyInferiorSetupOk,
+ this, &DebuggerRunControl::aboutToNotifyInferiorSetupOk);
}
DebuggerRunControl::~DebuggerRunControl()
@@ -141,10 +148,9 @@ void DebuggerRunControl::start()
if (m_engine->startParameters().startMode == StartInternal) {
QStringList unhandledIds;
- foreach (const BreakpointModelId &id, breakHandler()->allBreakpointIds()) {
- if (m_engine->breakHandler()->breakpointData(id).enabled
- && !m_engine->acceptsBreakpoint(id))
- unhandledIds.append(id.toString());
+ foreach (Breakpoint bp, breakHandler()->allBreakpoints()) {
+ if (bp.isEnabled() && !m_engine->acceptsBreakpoint(bp))
+ unhandledIds.append(bp.id().toString());
}
if (!unhandledIds.isEmpty()) {
QString warningMessage =
@@ -186,6 +192,16 @@ void DebuggerRunControl::startFailed()
m_engine->handleStartFailed();
}
+void DebuggerRunControl::notifyEngineRemoteServerRunning(const QByteArray &msg, int pid)
+{
+ m_engine->notifyEngineRemoteServerRunning(msg, pid);
+}
+
+void DebuggerRunControl::notifyEngineRemoteSetupFinished(const RemoteSetupResult &result)
+{
+ m_engine->notifyEngineRemoteSetupFinished(result);
+}
+
void DebuggerRunControl::handleFinished()
{
appendMessage(tr("Debugging has finished") + QLatin1Char('\n'), NormalMessageFormat);
@@ -222,15 +238,39 @@ void DebuggerRunControl::debuggingFinished()
emit finished();
}
+void DebuggerRunControl::showMessage(const QString &msg, int channel)
+{
+ m_engine->showMessage(msg, channel);
+}
+
bool DebuggerRunControl::isRunning() const
{
return m_running;
}
-DebuggerEngine *DebuggerRunControl::engine()
+DebuggerStartParameters &DebuggerRunControl::startParameters()
+{
+ return m_engine->startParameters();
+}
+
+void DebuggerRunControl::notifyInferiorIll()
+{
+ m_engine->notifyInferiorIll();
+}
+
+void DebuggerRunControl::notifyInferiorExited()
+{
+ m_engine->notifyInferiorExited();
+}
+
+void DebuggerRunControl::quitDebugger()
+{
+ m_engine->quitDebugger();
+}
+
+void DebuggerRunControl::abortDebugger()
{
- QTC_CHECK(m_engine);
- return m_engine;
+ m_engine->abortDebugger();
}
////////////////////////////////////////////////////////////////////////
@@ -255,7 +295,7 @@ bool DebuggerRunControlFactory::fillParametersFromLocalRunConfiguration
QTC_ASSERT(runConfiguration, return false);
auto rc = qobject_cast<const LocalApplicationRunConfiguration *>(runConfiguration);
QTC_ASSERT(rc, return false);
- EnvironmentAspect *environmentAspect = rc->extraAspect<ProjectExplorer::EnvironmentAspect>();
+ EnvironmentAspect *environmentAspect = rc->extraAspect<EnvironmentAspect>();
QTC_ASSERT(environmentAspect, return false);
Target *target = runConfiguration->target();
@@ -291,7 +331,7 @@ bool DebuggerRunControlFactory::fillParametersFromLocalRunConfiguration
sp->languages |= CppLanguage;
if (debuggerAspect->useQmlDebugger()) {
- const ProjectExplorer::IDevice::ConstPtr device =
+ const IDevice::ConstPtr device =
DeviceKitInformation::device(runConfiguration->target()->kit());
QTC_ASSERT(device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE, return sp);
QTcpServer server;
@@ -338,46 +378,12 @@ RunControl *DebuggerRunControlFactory::create
if (mode == DebugRunModeWithBreakOnMain)
sp.breakOnMain = true;
- return doCreate(sp, runConfiguration, errorMessage);
-}
-
-static bool fixupEngineTypes(DebuggerStartParameters &sp, RunConfiguration *rc, QString *errorMessage)
-{
- if (sp.masterEngineType != NoEngineType)
- return true;
-
- if (sp.executable.endsWith(_(".py"))) {
- sp.masterEngineType = PdbEngineType;
- return true;
- }
-
- if (rc) {
- DebuggerRunConfigurationAspect *aspect
- = rc->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
- if (const Target *target = rc->target())
- if (!DebuggerRunControlFactory::fillParametersFromKit(&sp, target->kit(), errorMessage))
- return false;
- const bool useCppDebugger = aspect->useCppDebugger() && (sp.languages & CppLanguage);
- const bool useQmlDebugger = aspect->useQmlDebugger() && (sp.languages & QmlLanguage);
- if (useQmlDebugger) {
- if (useCppDebugger) {
- sp.masterEngineType = QmlCppEngineType;
- sp.firstSlaveEngineType = sp.cppEngineType;
- sp.secondSlaveEngineType = QmlCppEngineType;
- } else {
- sp.masterEngineType = QmlEngineType;
- }
- } else {
- sp.masterEngineType = sp.cppEngineType;
- }
- return true;
- }
- sp.masterEngineType = sp.cppEngineType;
- return true;
+ sp.runConfiguration = runConfiguration;
+ return doCreate(sp, errorMessage);
}
DebuggerRunControl *DebuggerRunControlFactory::doCreate
- (const DebuggerStartParameters &sp0, RunConfiguration *rc, QString *errorMessage)
+ (const DebuggerStartParameters &sp0, QString *errorMessage)
{
TaskHub::clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO);
TaskHub::clearTasks(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME);
@@ -395,8 +401,34 @@ DebuggerRunControl *DebuggerRunControlFactory::doCreate
}
}
- if (!fixupEngineTypes(sp, rc, errorMessage))
- return 0;
+ if (sp.masterEngineType == NoEngineType) {
+ if (sp.executable.endsWith(_(".py"))) {
+ sp.masterEngineType = PdbEngineType;
+ } else {
+ if (RunConfiguration *rc = sp.runConfiguration) {
+ DebuggerRunConfigurationAspect *aspect
+ = rc->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
+ if (const Target *target = rc->target())
+ if (!DebuggerRunControlFactory::fillParametersFromKit(&sp, target->kit(), errorMessage))
+ return 0;
+ const bool useCppDebugger = aspect->useCppDebugger() && (sp.languages & CppLanguage);
+ const bool useQmlDebugger = aspect->useQmlDebugger() && (sp.languages & QmlLanguage);
+ if (useQmlDebugger) {
+ if (useCppDebugger) {
+ sp.masterEngineType = QmlCppEngineType;
+ sp.firstSlaveEngineType = sp.cppEngineType;
+ sp.secondSlaveEngineType = QmlCppEngineType;
+ } else {
+ sp.masterEngineType = QmlEngineType;
+ }
+ } else {
+ sp.masterEngineType = sp.cppEngineType;
+ }
+ } else {
+ sp.masterEngineType = sp.cppEngineType;
+ }
+ }
+ }
QString error;
DebuggerEngine *engine = createEngine(sp.masterEngineType, sp, &error);
@@ -406,7 +438,7 @@ DebuggerRunControl *DebuggerRunControlFactory::doCreate
*errorMessage = error;
return 0;
}
- return new DebuggerRunControl(rc, engine);
+ return new DebuggerRunControl(sp.runConfiguration, engine);
}
IRunConfigurationAspect *DebuggerRunControlFactory::createRunConfigurationAspect(RunConfiguration *rc)
@@ -417,7 +449,7 @@ IRunConfigurationAspect *DebuggerRunControlFactory::createRunConfigurationAspect
DebuggerRunControl *DebuggerRunControlFactory::createAndScheduleRun(const DebuggerStartParameters &sp)
{
QString errorMessage;
- DebuggerRunControl *rc = doCreate(sp, 0, &errorMessage);
+ DebuggerRunControl *rc = doCreate(sp, &errorMessage);
if (!rc) {
ProjectExplorerPlugin::showRunErrorMessage(errorMessage);
return 0;
@@ -451,7 +483,7 @@ bool DebuggerRunControlFactory::fillParametersFromKit(DebuggerStartParameters *s
sp->executable = executableForPid(sp->attachPID);
}
if (!sp->executable.isEmpty())
- abis = Abi::abisOfBinary(Utils::FileName::fromString(sp->executable));
+ abis = Abi::abisOfBinary(FileName::fromString(sp->executable));
}
if (!abis.isEmpty()) {
// Try exact abis.
diff --git a/src/plugins/debugger/debuggerruncontrol.h b/src/plugins/debugger/debuggerruncontrol.h
index c09aa46c1b9..9b7b15d8e8c 100644
--- a/src/plugins/debugger/debuggerruncontrol.h
+++ b/src/plugins/debugger/debuggerruncontrol.h
@@ -40,7 +40,10 @@ namespace ProjectExplorer { class Kit; }
namespace Debugger {
-class DebuggerEngine;
+class RemoteSetupResult;
+
+namespace Internal { class DebuggerEngine; }
+
class DebuggerStartParameters;
class DEBUGGER_EXPORT DebuggerRunControl
@@ -59,20 +62,32 @@ public:
QString displayName() const;
void startFailed();
+ void notifyEngineRemoteServerRunning(const QByteArray &msg, int pid);
+ void notifyEngineRemoteSetupFinished(const RemoteSetupResult &result);
+ void notifyInferiorIll();
+ Q_SLOT void notifyInferiorExited();
+ void quitDebugger();
+ void abortDebugger();
void debuggingFinished();
- DebuggerEngine *engine();
+
+ void showMessage(const QString &msg, int channel = LogDebug);
+
+ DebuggerStartParameters &startParameters();
signals:
- void engineRequestSetup();
+ void requestRemoteSetup();
+ void aboutToNotifyInferiorSetupOk();
+ void stateChanged(Debugger::DebuggerState state);
private slots:
void handleFinished();
private:
friend class DebuggerRunControlFactory;
- DebuggerRunControl(ProjectExplorer::RunConfiguration *runConfiguration, DebuggerEngine *engine);
+ DebuggerRunControl(ProjectExplorer::RunConfiguration *runConfiguration,
+ Internal::DebuggerEngine *engine);
- DebuggerEngine *m_engine;
+ Internal::DebuggerEngine *m_engine;
bool m_running;
};
@@ -91,7 +106,7 @@ public:
bool canRun(ProjectExplorer::RunConfiguration *runConfiguration,
ProjectExplorer::RunMode mode) const;
- static DebuggerEngine *createEngine(DebuggerEngineType et,
+ static Internal::DebuggerEngine *createEngine(DebuggerEngineType et,
const DebuggerStartParameters &sp,
QString *errorMessage);
@@ -103,8 +118,7 @@ public:
static DebuggerRunControl *createAndScheduleRun(const DebuggerStartParameters &sp);
- static DebuggerRunControl *doCreate(const DebuggerStartParameters &sp,
- ProjectExplorer::RunConfiguration *rc, QString *errorMessage);
+ static DebuggerRunControl *doCreate(const DebuggerStartParameters &sp, QString *errorMessage);
ProjectExplorer::IRunConfigurationAspect *createRunConfigurationAspect(
ProjectExplorer::RunConfiguration *rc);
diff --git a/src/plugins/debugger/debuggersourcepathmappingwidget.cpp b/src/plugins/debugger/debuggersourcepathmappingwidget.cpp
index 1f081559b53..1f9dfaa43e2 100644
--- a/src/plugins/debugger/debuggersourcepathmappingwidget.cpp
+++ b/src/plugins/debugger/debuggersourcepathmappingwidget.cpp
@@ -228,40 +228,41 @@ DebuggerSourcePathMappingWidget::DebuggerSourcePathMappingWidget(QWidget *parent
m_treeView->setSelectionMode(QAbstractItemView::SingleSelection);
m_treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
m_treeView->setModel(m_model);
- connect(m_treeView->selectionModel(),
- SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
- SLOT(slotCurrentRowChanged(QModelIndex,QModelIndex)));
+ connect(m_treeView->selectionModel(), &QItemSelectionModel::currentRowChanged,
+ this, &DebuggerSourcePathMappingWidget::slotCurrentRowChanged);
// Top list/Right part: Buttons.
- QVBoxLayout *buttonLayout = new QVBoxLayout;
+ auto buttonLayout = new QVBoxLayout;
buttonLayout->addWidget(m_addButton);
buttonLayout->addWidget(m_addQtButton);
m_addQtButton->setVisible(sizeof(qtBuildPaths) > 0);
m_addQtButton->setToolTip(tr("Add a mapping for Qt's source folders "
"when using an unpatched version of Qt."));
buttonLayout->addWidget(m_removeButton);
- connect(m_addButton, SIGNAL(clicked()), this, SLOT(slotAdd()));
- connect(m_addQtButton, SIGNAL(clicked()), this, SLOT(slotAddQt()));
-
- connect(m_removeButton, SIGNAL(clicked()), this, SLOT(slotRemove()));
+ connect(m_addButton, &QAbstractButton::clicked,
+ this, &DebuggerSourcePathMappingWidget::slotAdd);
+ connect(m_addQtButton, &QAbstractButton::clicked,
+ this, &DebuggerSourcePathMappingWidget::slotAddQt);
+ connect(m_removeButton, &QAbstractButton::clicked,
+ this, &DebuggerSourcePathMappingWidget::slotRemove);
buttonLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
// Assemble top
- QHBoxLayout *treeHLayout = new QHBoxLayout;
+ auto treeHLayout = new QHBoxLayout;
treeHLayout->addWidget(m_treeView);
treeHLayout->addLayout(buttonLayout);
// Edit part
m_targetChooser->setExpectedKind(PathChooser::ExistingDirectory);
m_targetChooser->setHistoryCompleter(QLatin1String("Debugger.MappingTarget.History"));
- connect(m_sourceLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(slotEditSourceFieldChanged()));
- connect(m_targetChooser, SIGNAL(changed(QString)),
- this, SLOT(slotEditTargetFieldChanged()));
- QFormLayout *editLayout = new QFormLayout;
+ connect(m_sourceLineEdit, &QLineEdit::textChanged,
+ this, &DebuggerSourcePathMappingWidget::slotEditSourceFieldChanged);
+ connect(m_targetChooser, &PathChooser::changed,
+ this, &DebuggerSourcePathMappingWidget::slotEditTargetFieldChanged);
+ auto editLayout = new QFormLayout;
const QString sourceToolTip = tr("The source path contained in the "
"debug information of the executable as reported by the debugger");
- QLabel *editSourceLabel = new QLabel(tr("&Source path:"));
+ auto editSourceLabel = new QLabel(tr("&Source path:"));
editSourceLabel->setToolTip(sourceToolTip);
m_sourceLineEdit->setToolTip(sourceToolTip);
editSourceLabel->setBuddy(m_sourceLineEdit);
@@ -269,7 +270,7 @@ DebuggerSourcePathMappingWidget::DebuggerSourcePathMappingWidget(QWidget *parent
const QString targetToolTip = tr("The actual location of the source "
"tree on the local machine");
- QLabel *editTargetLabel = new QLabel(tr("&Target path:"));
+ auto editTargetLabel = new QLabel(tr("&Target path:"));
editTargetLabel->setToolTip(targetToolTip);
editTargetLabel->setBuddy(m_targetChooser);
m_targetChooser->setToolTip(targetToolTip);
@@ -279,7 +280,7 @@ DebuggerSourcePathMappingWidget::DebuggerSourcePathMappingWidget(QWidget *parent
chooser->addSupportedWidget(m_targetChooser->lineEdit());
// Main layout
- QVBoxLayout *mainLayout = new QVBoxLayout;
+ auto mainLayout = new QVBoxLayout;
mainLayout->addLayout(treeHLayout);
mainLayout->addLayout(editLayout);
setLayout(mainLayout);
diff --git a/src/plugins/debugger/debuggerstartparameters.h b/src/plugins/debugger/debuggerstartparameters.h
index 3233511ce03..d89af005cc2 100644
--- a/src/plugins/debugger/debuggerstartparameters.h
+++ b/src/plugins/debugger/debuggerstartparameters.h
@@ -39,9 +39,11 @@
#include <utils/environment.h>
#include <projectexplorer/abi.h>
#include <projectexplorer/kit.h>
+#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/devicesupport/idevice.h>
#include <QMetaType>
+#include <QVector>
namespace Debugger {
@@ -81,6 +83,7 @@ public:
firstSlaveEngineType(NoEngineType),
secondSlaveEngineType(NoEngineType),
cppEngineType(NoEngineType),
+ runConfiguration(0),
isSnapshot(false),
attachPID(-1),
useTerminal(false),
@@ -111,6 +114,7 @@ public:
QString debuggerCommand;
ProjectExplorer::Abi toolChainAbi;
ProjectExplorer::IDevice::ConstPtr device;
+ QPointer<ProjectExplorer::RunConfiguration> runConfiguration;
QString platform;
QString executable;
@@ -156,6 +160,9 @@ public:
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
+ // Used by Valgrind
+ QVector<QByteArray> expectedSignals;
+
QStringList solibSearchPath;
DebuggerStartMode startMode;
DebuggerCloseMode closeMode;
diff --git a/src/plugins/debugger/debuggertooltipmanager.cpp b/src/plugins/debugger/debuggertooltipmanager.cpp
index 7fa9e63ee5b..5855b03366a 100644
--- a/src/plugins/debugger/debuggertooltipmanager.cpp
+++ b/src/plugins/debugger/debuggertooltipmanager.cpp
@@ -44,7 +44,7 @@
#include <texteditor/texteditor.h>
#include <utils/tooltip/tooltip.h>
-#include <utils/tooltip/tipcontents.h>
+#include <utils/treemodel.h>
#include <utils/qtcassert.h>
#include <QAbstractItemModel>
@@ -66,6 +66,7 @@
using namespace Core;
using namespace TextEditor;
+using namespace Utils;
namespace Debugger {
namespace Internal {
@@ -94,9 +95,9 @@ const char dateAttributeC[] = "date";
const char treeElementC[] = "tree";
const char treeExpressionAttributeC[] = "expression";
const char treeInameAttributeC[] = "iname";
-const char modelElementC[] = "model";
-const char modelColumnCountAttributeC[] = "columncount";
-const char modelRowElementC[] = "row";
+// const char modelElementC[] = "model";
+// const char modelColumnCountAttributeC[] = "columncount";
+// const char modelRowElementC[] = "row";
const char modelItemElementC[] = "item";
static void purgeClosedToolTips();
@@ -179,299 +180,176 @@ void DraggableLabel::mouseMoveEvent(QMouseEvent * event)
QLabel::mouseMoveEvent(event);
}
-// Helper for building a QStandardItemModel of a tree form (see TreeModelVisitor).
-// The recursion/building is based on the scheme: \code
-// <row><item1><item2>
-// <row><item11><item12></row>
-// </row>
-// \endcode
-
-class StandardItemTreeModelBuilder
-{
-public:
- typedef QList<QStandardItem *> StandardItemRow;
-
- explicit StandardItemTreeModelBuilder(QStandardItemModel *m, Qt::ItemFlags f = Qt::ItemIsSelectable);
-
- void addItem(const QString &);
- void startRow();
- void endRow();
-
-private:
- void pushRow();
-
- QStandardItemModel *m_model;
- const Qt::ItemFlags m_flags;
- StandardItemRow m_row;
- QStack<QStandardItem *> m_rowParents;
-};
-
-StandardItemTreeModelBuilder::StandardItemTreeModelBuilder(QStandardItemModel *m, Qt::ItemFlags f) :
- m_model(m), m_flags(f)
-{
- m_model->removeRows(0, m_model->rowCount());
-}
-
-void StandardItemTreeModelBuilder::addItem(const QString &s)
-{
- QStandardItem *item = new QStandardItem(s);
- item->setFlags(m_flags);
- m_row.push_back(item);
-}
-
-void StandardItemTreeModelBuilder::pushRow()
-{
- if (m_rowParents.isEmpty())
- m_model->appendRow(m_row);
- else
- m_rowParents.top()->appendRow(m_row);
- m_rowParents.push(m_row.front());
- m_row.clear();
-}
-
-void StandardItemTreeModelBuilder::startRow()
-{
- // Push parent in case rows are nested. This is a Noop for the very first row.
- if (!m_row.isEmpty())
- pushRow();
-}
-
-void StandardItemTreeModelBuilder::endRow()
-{
- if (!m_row.isEmpty()) // Push row if no child rows have been encountered
- pushRow();
- m_rowParents.pop();
-}
+/////////////////////////////////////////////////////////////////////////
+//
+// ToolTipWatchItem
+//
+/////////////////////////////////////////////////////////////////////////
-// Helper visitor base class for recursing over a tree model
-// (see StandardItemTreeModelBuilder for the scheme).
-class TreeModelVisitor
+class ToolTipWatchItem : public Utils::TreeItem
{
public:
- virtual void run() { run(QModelIndex()); }
-
-protected:
- TreeModelVisitor(const QAbstractItemModel *model) : m_model(model) {}
-
- virtual void rowStarted() {}
- virtual void handleItem(const QModelIndex &m) = 0;
- virtual void rowEnded() {}
+ ToolTipWatchItem() : expandable(false) {}
+ ToolTipWatchItem(WatchItem *item);
- const QAbstractItemModel *model() const { return m_model; }
+ bool hasChildren() const { return expandable; }
+ bool canFetchMore() const { return children().isEmpty() && expandable && model(); }
+ void fetchMore() {}
+ QVariant data(int column, int role) const;
-private:
- void run(const QModelIndex &parent);
-
- const QAbstractItemModel *m_model;
-};
-
-void TreeModelVisitor::run(const QModelIndex &parent)
-{
- const int columnCount = m_model->columnCount(parent);
- const int rowCount = m_model->rowCount(parent);
- for (int r = 0; r < rowCount; r++) {
- rowStarted();
- QModelIndex left;
- for (int c = 0; c < columnCount; c++) {
- const QModelIndex index = m_model->index(r, c, parent);
- handleItem(index);
- if (!c)
- left = index;
- }
- if (left.isValid())
- run(left);
- rowEnded();
- }
-}
-
-// Visitor writing out a tree model in XML format.
-class XmlWriterTreeModelVisitor : public TreeModelVisitor
-{
public:
- XmlWriterTreeModelVisitor(const QAbstractItemModel *model, QXmlStreamWriter &w);
-
- virtual void run();
-
-protected:
- virtual void rowStarted() { m_writer.writeStartElement(QLatin1String(modelRowElementC)); }
- virtual void handleItem(const QModelIndex &m);
- virtual void rowEnded() { m_writer.writeEndElement(); }
-
-private:
- const QString m_modelItemElement;
- QXmlStreamWriter &m_writer;
+ QString name;
+ QString value;
+ QString type;
+ QColor color;
+ bool expandable;
+ QByteArray iname;
};
-XmlWriterTreeModelVisitor::XmlWriterTreeModelVisitor(const QAbstractItemModel *model, QXmlStreamWriter &w) :
- TreeModelVisitor(model), m_modelItemElement(QLatin1String(modelItemElementC)), m_writer(w)
+ToolTipWatchItem::ToolTipWatchItem(WatchItem *item)
{
+ name = item->displayName();
+ value = item->displayValue();
+ type = item->displayType();
+ iname = item->d.iname;
+ color = item->color();
+ expandable = item->d.hasChildren;
+ foreach (TreeItem *child, item->children())
+ appendChild(new ToolTipWatchItem(static_cast<WatchItem *>(child)));
}
-void XmlWriterTreeModelVisitor::run()
-{
- m_writer.writeStartElement(QLatin1String(modelElementC));
- const int columnCount = model()->columnCount();
- m_writer.writeAttribute(QLatin1String(modelColumnCountAttributeC), QString::number(columnCount));
- TreeModelVisitor::run();
- m_writer.writeEndElement();
-}
-
-void XmlWriterTreeModelVisitor::handleItem(const QModelIndex &m)
-{
- const QString value = m.data(Qt::DisplayRole).toString();
- if (value.isEmpty())
- m_writer.writeEmptyElement(m_modelItemElement);
- else
- m_writer.writeTextElement(m_modelItemElement, value);
-}
+/////////////////////////////////////////////////////////////////////////
+//
+// ToolTipModel
+//
+/////////////////////////////////////////////////////////////////////////
-// TreeModelVisitor for debugging/copying models
-class DumpTreeModelVisitor : public TreeModelVisitor
+class ToolTipModel : public TreeModel
{
public:
- enum Mode
+ ToolTipModel()
{
- DebugMode, // For debugging, "|'data'|"
- ClipboardMode // Tab-delimited "\tdata" for clipboard (see stack window)
- };
- explicit DumpTreeModelVisitor(const QAbstractItemModel *model, Mode m, QTextStream &s);
-
-protected:
- virtual void rowStarted();
- virtual void handleItem(const QModelIndex &m);
- virtual void rowEnded();
-
-private:
- const Mode m_mode;
-
- QTextStream &m_stream;
- int m_level;
- unsigned m_itemsInRow;
-};
-
-DumpTreeModelVisitor::DumpTreeModelVisitor(const QAbstractItemModel *model, Mode m, QTextStream &s) :
- TreeModelVisitor(model), m_mode(m), m_stream(s), m_level(0), m_itemsInRow(0)
-{
- if (m_mode == DebugMode)
- m_stream << model->metaObject()->className() << '/' << model->objectName();
-}
-
-void DumpTreeModelVisitor::rowStarted()
-{
- m_level++;
- if (m_itemsInRow) { // Nested row.
- m_stream << '\n';
- m_itemsInRow = 0;
- }
- switch (m_mode) {
- case DebugMode:
- m_stream << QString(2 * m_level, QLatin1Char(' '));
- break;
- case ClipboardMode:
- m_stream << QString(m_level, QLatin1Char('\t'));
- break;
+ QStringList headers;
+ headers.append(tr("Name"));
+ headers.append(tr("Value"));
+ headers.append(tr("Type"));
+ setHeader(headers);
+ m_enabled = true;
+ auto item = new ToolTipWatchItem;
+ item->expandable = true;
+ setRootItem(item);
}
-}
-void DumpTreeModelVisitor::handleItem(const QModelIndex &m)
-{
- const QString data = m.data().toString();
- switch (m_mode) {
- case DebugMode:
- if (m.column())
- m_stream << '|';
- m_stream << '\'' << data << '\'';
- break;
- case ClipboardMode:
- if (m.column())
- m_stream << '\t';
- m_stream << data;
- break;
+ void expandNode(const QModelIndex &idx)
+ {
+ m_expandedINames.insert(idx.data(LocalsINameRole).toByteArray());
+ if (canFetchMore(idx))
+ fetchMore(idx);
}
- m_itemsInRow++;
-}
-void DumpTreeModelVisitor::rowEnded()
-{
- if (m_itemsInRow) {
- m_stream << '\n';
- m_itemsInRow = 0;
+ void collapseNode(const QModelIndex &idx)
+ {
+ m_expandedINames.remove(idx.data(LocalsINameRole).toByteArray());
}
- m_level--;
-}
-/*
-static QDebug operator<<(QDebug d, const QAbstractItemModel &model)
-{
- QString s;
- QTextStream str(&s);
- Debugger::Internal::DumpTreeModelVisitor v(&model, Debugger::Internal::DumpTreeModelVisitor::DebugMode, str);
- v.run();
- qCDebug(tooltip).nospace() << s;
- return d;
-}
-*/
+ void fetchMore(const QModelIndex &idx)
+ {
+ if (!idx.isValid())
+ return;
+ auto item = dynamic_cast<ToolTipWatchItem *>(itemFromIndex(idx));
+ if (!item)
+ return;
+ QByteArray iname = item->iname;
+ if (!m_engine)
+ return;
-/*!
- \class Debugger::Internal::TooltipFilterModel
+ WatchItem *it = m_engine->watchHandler()->findItem(iname);
+ QTC_ASSERT(it, return);
+ it->fetchMore();
+ }
- \brief The TooltipFilterModel class is a model for tooltips filtering an
- item on the watchhandler matching its tree on the iname.
+ void restoreTreeModel(QXmlStreamReader &r);
- In addition, suppress the model's tooltip data to avoid a tooltip on a tooltip.
-*/
+ QPointer<DebuggerEngine> m_engine;
+ QSet<QByteArray> m_expandedINames;
+ bool m_enabled;
+};
-class TooltipFilterModel : public QSortFilterProxyModel
-{
-public:
- TooltipFilterModel() {}
+QVariant ToolTipWatchItem::data(int column, int role) const
+{
+ switch (role) {
+ case Qt::DisplayRole: {
+ switch (column) {
+ case 0:
+ return name;
+ case 1:
+ return value;
+ case 2:
+ return type;
+ }
+ }
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
- {
- return role == Qt::ToolTipRole
- ? QVariant() : QSortFilterProxyModel::data(index, role);
- }
+ case LocalsINameRole:
+ return iname;
- static bool isSubIname(const QByteArray &haystack, const QByteArray &needle)
- {
- return haystack.size() > needle.size()
- && haystack.startsWith(needle)
- && haystack.at(needle.size()) == '.';
- }
+ case Qt::ForegroundRole:
+ if (model() && static_cast<ToolTipModel *>(model())->m_enabled) {
+ if (column == 1)
+ return color;
+ return QVariant();
+ }
+ return QColor(140, 140, 140);
- bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
- {
- const QModelIndex nameIndex = sourceModel()->index(sourceRow, 0, sourceParent);
- const QByteArray iname = nameIndex.data(LocalsINameRole).toByteArray();
-// DEBUG("ACCEPTING FILTER" << iname
-// << (iname == m_iname || isSubIname(iname, m_iname) || isSubIname(m_iname, iname));
- return iname == m_iname || isSubIname(iname, m_iname) || isSubIname(m_iname, iname);
+ default:
+ break;
}
+ return QVariant();
+}
- QByteArray m_iname;
-};
-
-/////////////////////////////////////////////////////////////////////////
-//
-// TreeModelCopyVisitor builds a QStandardItem from a tree model (copy).
-//
-/////////////////////////////////////////////////////////////////////////
-
-class TreeModelCopyVisitor : public TreeModelVisitor
+void ToolTipModel::restoreTreeModel(QXmlStreamReader &r)
{
-public:
- TreeModelCopyVisitor(const QAbstractItemModel *source, QStandardItemModel *target) :
- TreeModelVisitor(source), m_builder(target)
- {}
-
-protected:
- virtual void rowStarted() { m_builder.startRow(); }
- virtual void handleItem(const QModelIndex &m) { m_builder.addItem(m.data().toString()); }
- virtual void rowEnded() { m_builder.endRow(); }
+ Q_UNUSED(r);
+#if 0
+// Helper for building a QStandardItemModel of a tree form (see TreeModelVisitor).
+// The recursion/building is based on the scheme: \code
+// <row><item1><item2>
+// <row><item11><item12></row>
+// </row>
+// \endcode
-private:
- StandardItemTreeModelBuilder m_builder;
-};
+ bool withinModel = true;
+ while (withinModel && !r.atEnd()) {
+ const QXmlStreamReader::TokenType token = r.readNext();
+ switch (token) {
+ case QXmlStreamReader::StartElement: {
+ const QStringRef element = r.name();
+ // Root model element with column count.
+ if (element == QLatin1String(modelElementC)) {
+ if (const int cc = r.attributes().value(QLatin1String(modelColumnCountAttributeC)).toString().toInt())
+ columnCount = cc;
+ m->setColumnCount(columnCount);
+ } else if (element == QLatin1String(modelRowElementC)) {
+ builder.startRow();
+ } else if (element == QLatin1String(modelItemElementC)) {
+ builder.addItem(r.readElementText());
+ }
+ }
+ break; // StartElement
+ case QXmlStreamReader::EndElement: {
+ const QStringRef element = r.name();
+ // Row closing: pop off parent.
+ if (element == QLatin1String(modelRowElementC))
+ builder.endRow();
+ else if (element == QLatin1String(modelElementC))
+ withinModel = false;
+ }
+ break; // EndElement
+ default:
+ break;
+ } // switch
+ } // while
+#endif
+}
/*!
\class Debugger::Internal::DebuggerToolTipTreeView
@@ -491,16 +369,24 @@ public:
void computeSize();
+ void setEngine(DebuggerEngine *engine);
private:
- void expandNode(const QModelIndex &idx);
- void collapseNode(const QModelIndex &idx);
int computeHeight(const QModelIndex &index) const;
+ WatchHandler *watchHandler() const
+ {
+ return m_model.m_engine->watchHandler();
+ }
+
QSize m_size;
+
+public:
+ ToolTipModel m_model;
+ void reexpand(const QModelIndex &idx);
};
-DebuggerToolTipTreeView::DebuggerToolTipTreeView(QWidget *parent) :
- QTreeView(parent)
+DebuggerToolTipTreeView::DebuggerToolTipTreeView(QWidget *parent)
+ : QTreeView(parent)
{
setHeaderHidden(true);
setEditTriggers(NoEditTriggers);
@@ -509,25 +395,20 @@ DebuggerToolTipTreeView::DebuggerToolTipTreeView(QWidget *parent) :
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
+ setModel(&m_model);
+
connect(this, &QTreeView::collapsed, this, &DebuggerToolTipTreeView::computeSize,
Qt::QueuedConnection);
connect(this, &QTreeView::expanded, this, &DebuggerToolTipTreeView::computeSize,
Qt::QueuedConnection);
- connect(this, &QTreeView::expanded,
- this, &DebuggerToolTipTreeView::expandNode);
- connect(this, &QTreeView::collapsed,
- this, &DebuggerToolTipTreeView::collapseNode);
+ connect(this, &QTreeView::expanded, &m_model, &ToolTipModel::expandNode);
+ connect(this, &QTreeView::collapsed, &m_model, &ToolTipModel::collapseNode);
}
-void DebuggerToolTipTreeView::expandNode(const QModelIndex &idx)
+void DebuggerToolTipTreeView::setEngine(DebuggerEngine *engine)
{
- model()->setData(idx, true, LocalsExpandedRole);
-}
-
-void DebuggerToolTipTreeView::collapseNode(const QModelIndex &idx)
-{
- model()->setData(idx, false, LocalsExpandedRole);
+ m_model.m_engine = engine;
}
int DebuggerToolTipTreeView::computeHeight(const QModelIndex &index) const
@@ -539,6 +420,26 @@ int DebuggerToolTipTreeView::computeHeight(const QModelIndex &index) const
return s;
}
+void DebuggerToolTipTreeView::reexpand(const QModelIndex &idx)
+{
+ TreeItem *item = m_model.itemFromIndex(idx);
+ QTC_ASSERT(item, return);
+ QByteArray iname = item->data(0, LocalsINameRole).toByteArray();
+ bool shouldExpand = m_model.m_expandedINames.contains(iname);
+ if (shouldExpand) {
+ if (!isExpanded(idx)) {
+ expand(idx);
+ for (int i = 0, n = model()->rowCount(idx); i != n; ++i) {
+ QModelIndex idx1 = model()->index(i, 0, idx);
+ reexpand(idx1);
+ }
+ }
+ } else {
+ if (isExpanded(idx))
+ collapse(idx);
+ }
+}
+
void DebuggerToolTipTreeView::computeSize()
{
int columns = 30; // Decoration
@@ -546,13 +447,14 @@ void DebuggerToolTipTreeView::computeSize()
bool rootDecorated = false;
if (QAbstractItemModel *m = model()) {
- WatchTreeView::reexpand(this, m->index(0, 0));
+ reexpand(m->index(0, 0));
const int columnCount = m->columnCount();
rootDecorated = m->rowCount() > 0;
- if (rootDecorated)
- for (int i = 0; i < columnCount; ++i) {
- resizeColumnToContents(i);
- columns += sizeHintForColumn(i);
+ if (rootDecorated) {
+ for (int i = 0; i < columnCount; ++i) {
+ resizeColumnToContents(i);
+ columns += sizeHintForColumn(i);
+ }
}
if (columns < 100)
columns = 100; // Prevent toolbar from shrinking when displaying 'Previous'
@@ -592,17 +494,6 @@ void DebuggerToolTipTreeView::computeSize()
setRootIsDecorated(rootDecorated);
}
-QString DebuggerToolTipManager::treeModelClipboardContents(const QAbstractItemModel *model)
-{
- QString rc;
- QTC_ASSERT(model, return rc);
- QTextStream str(&rc);
- DumpTreeModelVisitor v(model, DumpTreeModelVisitor::ClipboardMode, str);
- v.run();
- return rc;
-}
-
-
/////////////////////////////////////////////////////////////////////////
//
// DebuggerToolTipWidget
@@ -612,49 +503,7 @@ QString DebuggerToolTipManager::treeModelClipboardContents(const QAbstractItemMo
class DebuggerToolTipWidget : public QWidget
{
public:
- DebuggerToolTipWidget()
- {
- setAttribute(Qt::WA_DeleteOnClose);
-
- isPinned = false;
- const QIcon pinIcon(QLatin1String(":/debugger/images/pin.xpm"));
-
- pinButton = new QToolButton;
- pinButton->setIcon(pinIcon);
-
- auto copyButton = new QToolButton;
- copyButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
-
- titleLabel = new DraggableLabel(this);
- titleLabel->setMinimumWidth(40); // Ensure a draggable area even if text is empty.
- titleLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
-
- auto toolBar = new QToolBar(this);
- toolBar->setProperty("_q_custom_style_disabled", QVariant(true));
- const QList<QSize> pinIconSizes = pinIcon.availableSizes();
- if (!pinIconSizes.isEmpty())
- toolBar->setIconSize(pinIconSizes.front());
- toolBar->addWidget(pinButton);
- toolBar->addWidget(copyButton);
- toolBar->addWidget(titleLabel);
-
- treeView = new DebuggerToolTipTreeView(this);
- treeView->setFocusPolicy(Qt::NoFocus);
-
- auto mainLayout = new QVBoxLayout(this);
- mainLayout->setSizeConstraint(QLayout::SetFixedSize);
- mainLayout->setContentsMargins(0, 0, 0, 0);
- mainLayout->addWidget(toolBar);
- mainLayout->addWidget(treeView);
-
- connect(copyButton, &QAbstractButton::clicked, [this] {
- QString clipboardText = DebuggerToolTipManager::treeModelClipboardContents(treeView->model());
- QClipboard *clipboard = QApplication::clipboard();
- clipboard->setText(clipboardText, QClipboard::Selection);
- clipboard->setText(clipboardText, QClipboard::Clipboard);
- });
- DEBUG("CREATE DEBUGGERTOOLTIP WIDGET");
- }
+ DebuggerToolTipWidget();
~DebuggerToolTipWidget()
{
@@ -688,7 +537,7 @@ public:
if (parentWidget()) {
// We are currently within a text editor tooltip:
// Rip out of parent widget and re-show as a tooltip
- Utils::WidgetContent::pinToolTip(this, ICore::mainWindow());
+ ToolTip::pinToolTip(this, ICore::mainWindow());
} else {
// We have just be restored from session data.
setWindowFlags(Qt::ToolTip);
@@ -703,6 +552,58 @@ public:
DebuggerToolTipTreeView *treeView;
};
+DebuggerToolTipWidget::DebuggerToolTipWidget()
+{
+ setAttribute(Qt::WA_DeleteOnClose);
+
+ isPinned = false;
+ const QIcon pinIcon(QLatin1String(":/debugger/images/pin.xpm"));
+
+ pinButton = new QToolButton;
+ pinButton->setIcon(pinIcon);
+
+ auto copyButton = new QToolButton;
+ copyButton->setToolTip(DebuggerToolTipManager::tr("Copy Contents to Clipboard"));
+ copyButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
+
+ titleLabel = new DraggableLabel(this);
+ titleLabel->setMinimumWidth(40); // Ensure a draggable area even if text is empty.
+ titleLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);
+
+ auto toolBar = new QToolBar(this);
+ toolBar->setProperty("_q_custom_style_disabled", QVariant(true));
+ const QList<QSize> pinIconSizes = pinIcon.availableSizes();
+ if (!pinIconSizes.isEmpty())
+ toolBar->setIconSize(pinIconSizes.front());
+ toolBar->addWidget(pinButton);
+ toolBar->addWidget(copyButton);
+ toolBar->addWidget(titleLabel);
+
+ treeView = new DebuggerToolTipTreeView(this);
+ treeView->setFocusPolicy(Qt::NoFocus);
+
+ auto mainLayout = new QVBoxLayout(this);
+ mainLayout->setSizeConstraint(QLayout::SetFixedSize);
+ mainLayout->setContentsMargins(0, 0, 0, 0);
+ mainLayout->addWidget(toolBar);
+ mainLayout->addWidget(treeView);
+
+ connect(copyButton, &QAbstractButton::clicked, [this] {
+ QString text;
+ QTextStream str(&text);
+ treeView->m_model.rootItem()->walkTree([&str](TreeItem *item) {
+ auto titem = static_cast<ToolTipWatchItem *>(item);
+ str << QString(item->level(), QLatin1Char('\t'))
+ << titem->name << '\t' << titem->value << '\t' << titem->type << '\n';
+ });
+ QClipboard *clipboard = QApplication::clipboard();
+ clipboard->setText(text, QClipboard::Selection);
+ clipboard->setText(text, QClipboard::Clipboard);
+ });
+ DEBUG("CREATE DEBUGGERTOOLTIP WIDGET");
+}
+
+
/////////////////////////////////////////////////////////////////////////
//
// DebuggerToolTipHolder
@@ -724,7 +625,7 @@ public:
DebuggerToolTipHolder(const DebuggerToolTipContext &context);
~DebuggerToolTipHolder();
- void acquireEngine();
+ void acquireEngine(DebuggerEngine *engine);
void releaseEngine();
void saveSessionData(QXmlStreamWriter &w) const;
@@ -732,19 +633,15 @@ public:
void positionShow(const TextEditorWidget *editorWidget);
- void handleItemIsExpanded(const QModelIndex &sourceIdx);
- void updateTooltip(const StackFrame &frame);
+ void updateTooltip(DebuggerEngine *engine);
void setState(DebuggerTootipState newState);
void destroy();
public:
QPointer<DebuggerToolTipWidget> widget;
- QPointer<DebuggerEngine> engine;
QDate creationDate;
DebuggerToolTipContext context;
- TooltipFilterModel filterModel; //!< Pointing to a valid watchModel
- QStandardItemModel defaultModel;
DebuggerTootipState state;
};
@@ -756,15 +653,6 @@ static void hideAllToolTips()
tooltip->widget->hide();
}
-void DebuggerToolTipHolder::handleItemIsExpanded(const QModelIndex &sourceIdx)
-{
- QTC_ASSERT(filterModel.sourceModel() == sourceIdx.model(), return);
- QModelIndex mappedIdx = filterModel.mapFromSource(sourceIdx);
- QTC_ASSERT(widget.data(), return);
- if (!widget->treeView->isExpanded(mappedIdx))
- widget->treeView->expand(mappedIdx);
-}
-
/*!
\class Debugger::Internal::DebuggerToolTipContext
@@ -803,6 +691,12 @@ bool DebuggerToolTipContext::isSame(const DebuggerToolTipContext &other) const
&& iname == other.iname;
}
+QString DebuggerToolTipContext::toolTip() const
+{
+ return DebuggerToolTipManager::tr("Expression %1 in function %2 from line %3 to %4")
+ .arg(expression).arg(function).arg(scopeFromLine).arg(scopeToLine);
+}
+
QDebug operator<<(QDebug d, const DebuggerToolTipContext &c)
{
QDebug nsp = d.nospace();
@@ -859,14 +753,11 @@ DebuggerToolTipHolder::DebuggerToolTipHolder(const DebuggerToolTipContext &conte
state = New;
- filterModel.m_iname = context.iname;
-
QObject::connect(widget->pinButton, &QAbstractButton::clicked, [this] {
- if (widget->isPinned) {
+ if (widget->isPinned)
widget->close();
- } else {
+ else
widget->pin();
- }
});
DEBUG("CREATE DEBUGGERTOOLTIPHOLDER" << context.iname);
}
@@ -885,39 +776,35 @@ DebuggerToolTipHolder::~DebuggerToolTipHolder()
// If we are in "Acquired" or "Released", this is an update
// after normal WatchModel update.
-void DebuggerToolTipHolder::updateTooltip(const StackFrame &frame)
+void DebuggerToolTipHolder::updateTooltip(DebuggerEngine *engine)
{
+ widget->treeView->setEngine(engine);
+
+ if (!engine) {
+ setState(Released);
+ return;
+ }
+
+ StackFrame frame = engine->stackHandler()->currentFrame();
+
const bool sameFrame = context.matchesFrame(frame);
DEBUG("UPDATE TOOLTIP: STATE " << state << context.iname
<< "PINNED: " << widget->isPinned
<< "SHOW NEEDED: " << widget->isPinned
<< "SAME FRAME: " << sameFrame);
+
if (state == PendingUnshown) {
- const Utils::WidgetContent widgetContent(widget, true);
- Utils::ToolTip::show(context.mousePosition, widgetContent, Internal::mainWindow());
+ ToolTip::show(context.mousePosition, widget, Internal::mainWindow());
setState(PendingShown);
}
- if (state == PendingShown) {
- acquireEngine();
- Utils::ToolTip::move(context.mousePosition, Internal::mainWindow());
- } else if (state == Acquired && !sameFrame) {
+ if (sameFrame) {
+ acquireEngine(engine);
+ } else {
releaseEngine();
- } else if (state == Released && sameFrame) {
- acquireEngine();
- }
-
- if (state == Acquired) {
- // Save data to stream and restore to the backup m_defaultModel.
- // Doing it on releaseEngine() is too later.
- defaultModel.removeRows(0, defaultModel.rowCount());
- TreeModelCopyVisitor v(&filterModel, &defaultModel);
- v.run();
-
- widget->treeView->expand(filterModel.index(0, 0));
- WatchTreeView::reexpand(widget->treeView, filterModel.index(0, 0));
}
+ widget->titleLabel->setToolTip(context.toolTip());
}
void DebuggerToolTipHolder::setState(DebuggerTootipState newState)
@@ -948,29 +835,38 @@ void DebuggerToolTipHolder::destroy()
}
}
-void DebuggerToolTipHolder::acquireEngine()
+void DebuggerToolTipHolder::acquireEngine(DebuggerEngine *engine)
{
DEBUG("ACQUIRE ENGINE: STATE " << state);
setState(Acquired);
QTC_ASSERT(widget, return);
widget->titleLabel->setText(context.expression);
- widget->treeView->setModel(&filterModel);
- widget->treeView->setRootIndex(filterModel.index(0, 0));
- widget->treeView->expand(filterModel.index(0, 0));
- WatchTreeView::reexpand(widget->treeView, filterModel.index(0, 0));
+ //widget->treeView->setEnabled(true);
+ widget->treeView->m_model.m_enabled = true;
+
+ WatchItem *item = engine->watchHandler()->findItem(context.iname);
+ if (item) {
+ auto clone = new ToolTipWatchItem(item);
+ widget->treeView->m_model.rootItem()->removeChildren();
+ widget->treeView->m_model.rootItem()->appendChild(clone);
+ }
+ WatchTreeView::reexpand(widget->treeView, QModelIndex());
+ widget->treeView->computeSize();
}
void DebuggerToolTipHolder::releaseEngine()
{
+ if (state == Released)
+ return;
DEBUG("RELEASE ENGINE: STATE " << state);
setState(Released);
QTC_ASSERT(widget, return);
+ widget->treeView->m_model.m_enabled = false;
+ widget->treeView->m_model.layoutChanged();
widget->titleLabel->setText(DebuggerToolTipManager::tr("%1 (Previous)").arg(context.expression));
- widget->treeView->setModel(&defaultModel);
- widget->treeView->setRootIndex(defaultModel.index(0, 0));
- widget->treeView->expandAll();
+// widget->treeView->setEnabled(false);
}
void DebuggerToolTipHolder::positionShow(const TextEditorWidget *editorWidget)
@@ -1023,44 +919,7 @@ static DebuggerToolTipHolder *findOrCreateTooltip(const DebuggerToolTipContext &
return newTooltip;
}
-static void restoreTreeModel(QXmlStreamReader &r, QStandardItemModel *m)
-{
- StandardItemTreeModelBuilder builder(m);
- int columnCount = 1;
- bool withinModel = true;
- while (withinModel && !r.atEnd()) {
- const QXmlStreamReader::TokenType token = r.readNext();
- switch (token) {
- case QXmlStreamReader::StartElement: {
- const QStringRef element = r.name();
- // Root model element with column count.
- if (element == QLatin1String(modelElementC)) {
- if (const int cc = r.attributes().value(QLatin1String(modelColumnCountAttributeC)).toString().toInt())
- columnCount = cc;
- m->setColumnCount(columnCount);
- } else if (element == QLatin1String(modelRowElementC)) {
- builder.startRow();
- } else if (element == QLatin1String(modelItemElementC)) {
- builder.addItem(r.readElementText());
- }
- }
- break; // StartElement
- case QXmlStreamReader::EndElement: {
- const QStringRef element = r.name();
- // Row closing: pop off parent.
- if (element == QLatin1String(modelRowElementC))
- builder.endRow();
- else if (element == QLatin1String(modelElementC))
- withinModel = false;
- }
- break; // EndElement
- default:
- break;
- } // switch
- } // while
-}
-
-// Parse a 'yyyyMMdd' date
+//// Parse a 'yyyyMMdd' date
static QDate dateFromString(const QString &date)
{
return date.size() == 8 ?
@@ -1068,56 +927,6 @@ static QDate dateFromString(const QString &date)
QDate();
}
-static void loadSessionDataHelper(QXmlStreamReader &r)
-{
- if (!readStartElement(r, toolTipElementC))
- return;
- const QXmlStreamAttributes attributes = r.attributes();
- DebuggerToolTipContext context;
- context.fileName = attributes.value(QLatin1String(fileNameAttributeC)).toString();
- context.position = attributes.value(QLatin1String(textPositionAttributeC)).toString().toInt();
- context.line = attributes.value(QLatin1String(textLineAttributeC)).toString().toInt();
- context.column = attributes.value(QLatin1String(textColumnAttributeC)).toString().toInt();
- context.function = attributes.value(QLatin1String(functionAttributeC)).toString();
- QPoint offset;
- const QString offsetXAttribute = QLatin1String(offsetXAttributeC);
- const QString offsetYAttribute = QLatin1String(offsetYAttributeC);
- if (attributes.hasAttribute(offsetXAttribute))
- offset.setX(attributes.value(offsetXAttribute).toString().toInt());
- if (attributes.hasAttribute(offsetYAttribute))
- offset.setY(attributes.value(offsetYAttribute).toString().toInt());
- context.mousePosition = offset;
-
- context.iname = attributes.value(QLatin1String(treeInameAttributeC)).toString().toLatin1();
- context.expression = attributes.value(QLatin1String(treeExpressionAttributeC)).toString();
-
-// const QStringRef className = attributes.value(QLatin1String(toolTipClassAttributeC));
- context.engineType = attributes.value(QLatin1String(engineTypeAttributeC)).toString();
- context.creationDate = dateFromString(attributes.value(QLatin1String(dateAttributeC)).toString());
- bool readTree = context.isValid();
- if (!context.creationDate.isValid() || context.creationDate.daysTo(QDate::currentDate()) > toolTipsExpiryDays) {
- // DEBUG("Expiring tooltip " << context.fileName << '@' << context.position << " from " << creationDate)
- //readTree = false;
- } else { //if (className != QLatin1String("Debugger::Internal::DebuggerToolTipWidget")) {
- //qWarning("Unable to create debugger tool tip widget of class %s", qPrintable(className.toString()));
- //readTree = false;
- }
-
- if (readTree) {
- DebuggerToolTipHolder *tw = findOrCreateTooltip(context);
- restoreTreeModel(r, &tw->defaultModel);
- tw->widget->pin();
- tw->widget->titleLabel->setText(DebuggerToolTipManager::tr("%1 (Restored").arg(context.expression));
- tw->widget->treeView->setModel(&tw->defaultModel);
- tw->widget->treeView->setRootIndex(tw->defaultModel.index(0, 0));
- tw->widget->treeView->expandAll();
- } else {
- r.readElementText(QXmlStreamReader::SkipChildElements); // Skip
- }
-
- r.readNext(); // Skip </tree>
-}
-
void DebuggerToolTipHolder::saveSessionData(QXmlStreamWriter &w) const
{
w.writeStartElement(QLatin1String(toolTipElementC));
@@ -1140,10 +949,18 @@ void DebuggerToolTipHolder::saveSessionData(QXmlStreamWriter &w) const
attributes.append(QLatin1String(treeInameAttributeC), QLatin1String(context.iname));
w.writeAttributes(attributes);
- w.writeStartElement(QLatin1String(treeElementC));
- XmlWriterTreeModelVisitor v(&filterModel, w);
- v.run();
- w.writeEndElement();
+ w.writeStartElement(QLatin1String(treeElementC));
+ widget->treeView->m_model.rootItem()->walkTree([&w](TreeItem *item) {
+ const QString modelItemElement = QLatin1String(modelItemElementC);
+ for (int i = 0; i < 3; ++i) {
+ const QString value = item->data(i, Qt::DisplayRole).toString();
+ if (value.isEmpty())
+ w.writeEmptyElement(modelItemElement);
+ else
+ w.writeTextElement(modelItemElement, value);
+ }
+ });
+ w.writeEndElement();
w.writeEndElement();
}
@@ -1191,7 +1008,7 @@ void DebuggerToolTipManager::slotUpdateVisibleToolTips()
return;
}
- const QString fileName = toolTipEditor->textDocument()->filePath();
+ const QString fileName = toolTipEditor->textDocument()->filePath().toString();
if (fileName.isEmpty()) {
hideAllToolTips();
return;
@@ -1206,21 +1023,6 @@ void DebuggerToolTipManager::slotUpdateVisibleToolTips()
}
}
-void DebuggerToolTipManager::slotItemIsExpanded(const QModelIndex &idx)
-{
- foreach (DebuggerToolTipHolder *tooltip, m_tooltips)
- tooltip->handleItemIsExpanded(idx);
-}
-
-void DebuggerToolTipManager::slotColumnAdjustmentRequested()
-{
- foreach (DebuggerToolTipHolder *tooltip, m_tooltips) {
- QTC_ASSERT(tooltip, continue);
- QTC_ASSERT(tooltip->widget, continue);
- tooltip->widget->treeView->computeSize();
- }
-}
-
void DebuggerToolTipManager::updateEngine(DebuggerEngine *engine)
{
QTC_ASSERT(engine, return);
@@ -1230,21 +1032,15 @@ void DebuggerToolTipManager::updateEngine(DebuggerEngine *engine)
// Stack frame changed: All tooltips of that file acquire the engine,
// all others release (arguable, this could be more precise?)
- StackFrame frame = engine->stackHandler()->currentFrame();
foreach (DebuggerToolTipHolder *tooltip, m_tooltips)
- tooltip->updateTooltip(frame);
+ tooltip->updateTooltip(engine);
slotUpdateVisibleToolTips(); // Move tooltip when stepping in same file.
}
-
void DebuggerToolTipManager::registerEngine(DebuggerEngine *engine)
{
+ Q_UNUSED(engine)
DEBUG("REGISTER ENGINE");
- WatchModelBase *watchModel = engine->watchHandler()->model();
- connect(watchModel, &WatchModelBase::itemIsExpanded,
- m_instance, &DebuggerToolTipManager::slotItemIsExpanded);
- connect(watchModel, &WatchModelBase::columnAdjustmentRequested,
- m_instance, &DebuggerToolTipManager::slotColumnAdjustmentRequested);
}
void DebuggerToolTipManager::deregisterEngine(DebuggerEngine *engine)
@@ -1252,22 +1048,18 @@ void DebuggerToolTipManager::deregisterEngine(DebuggerEngine *engine)
DEBUG("DEREGISTER ENGINE");
QTC_ASSERT(engine, return);
- // FIXME: For now remove all.
purgeClosedToolTips();
- foreach (DebuggerToolTipHolder *tooltip, m_tooltips)
- tooltip->destroy();
- purgeClosedToolTips();
- return;
- WatchModelBase *watchModel = engine->watchHandler()->model();
- disconnect(watchModel, &WatchModelBase::itemIsExpanded,
- m_instance, &DebuggerToolTipManager::slotItemIsExpanded);
- disconnect(watchModel, &WatchModelBase::columnAdjustmentRequested,
- m_instance, &DebuggerToolTipManager::slotColumnAdjustmentRequested);
foreach (DebuggerToolTipHolder *tooltip, m_tooltips)
if (tooltip->context.engineType == engine->objectName())
tooltip->releaseEngine();
+
saveSessionData();
+
+ // FIXME: For now remove all.
+ foreach (DebuggerToolTipHolder *tooltip, m_tooltips)
+ tooltip->destroy();
+ purgeClosedToolTips();
}
bool DebuggerToolTipManager::hasToolTips()
@@ -1282,20 +1074,61 @@ void DebuggerToolTipManager::sessionAboutToChange()
void DebuggerToolTipManager::loadSessionData()
{
- return; // FIXME
-
const QString data = sessionValue(sessionSettingsKeyC).toString();
QXmlStreamReader r(data);
r.readNextStartElement();
- if (r.tokenType() == QXmlStreamReader::StartElement && r.name() == QLatin1String(sessionDocumentC))
- while (!r.atEnd())
- loadSessionDataHelper(r);
+ if (r.tokenType() == QXmlStreamReader::StartElement && r.name() == QLatin1String(sessionDocumentC)) {
+ while (!r.atEnd()) {
+ if (readStartElement(r, toolTipElementC)) {
+ const QXmlStreamAttributes attributes = r.attributes();
+ DebuggerToolTipContext context;
+ context.fileName = attributes.value(QLatin1String(fileNameAttributeC)).toString();
+ context.position = attributes.value(QLatin1String(textPositionAttributeC)).toString().toInt();
+ context.line = attributes.value(QLatin1String(textLineAttributeC)).toString().toInt();
+ context.column = attributes.value(QLatin1String(textColumnAttributeC)).toString().toInt();
+ context.function = attributes.value(QLatin1String(functionAttributeC)).toString();
+ QPoint offset;
+ const QString offsetXAttribute = QLatin1String(offsetXAttributeC);
+ const QString offsetYAttribute = QLatin1String(offsetYAttributeC);
+ if (attributes.hasAttribute(offsetXAttribute))
+ offset.setX(attributes.value(offsetXAttribute).toString().toInt());
+ if (attributes.hasAttribute(offsetYAttribute))
+ offset.setY(attributes.value(offsetYAttribute).toString().toInt());
+ context.mousePosition = offset;
+
+ context.iname = attributes.value(QLatin1String(treeInameAttributeC)).toString().toLatin1();
+ context.expression = attributes.value(QLatin1String(treeExpressionAttributeC)).toString();
+
+ // const QStringRef className = attributes.value(QLatin1String(toolTipClassAttributeC));
+ context.engineType = attributes.value(QLatin1String(engineTypeAttributeC)).toString();
+ context.creationDate = dateFromString(attributes.value(QLatin1String(dateAttributeC)).toString());
+ bool readTree = context.isValid();
+ if (!context.creationDate.isValid() || context.creationDate.daysTo(QDate::currentDate()) > toolTipsExpiryDays) {
+ // DEBUG("Expiring tooltip " << context.fileName << '@' << context.position << " from " << creationDate)
+ //readTree = false;
+ } else { //if (className != QLatin1String("Debugger::Internal::DebuggerToolTipWidget")) {
+ //qWarning("Unable to create debugger tool tip widget of class %s", qPrintable(className.toString()));
+ //readTree = false;
+ }
+
+ if (readTree) {
+ DebuggerToolTipHolder *tw = findOrCreateTooltip(context);
+ tw->widget->treeView->m_model.restoreTreeModel(r);
+ tw->widget->pin();
+ tw->widget->titleLabel->setText(DebuggerToolTipManager::tr("%1 (Restored)").arg(context.expression));
+ tw->widget->treeView->expandAll();
+ } else {
+ r.readElementText(QXmlStreamReader::SkipChildElements); // Skip
+ }
+
+ r.readNext(); // Skip </tree>
+ }
+ }
+ }
}
void DebuggerToolTipManager::saveSessionData()
{
- return; // FIXME
-
QString data;
purgeClosedToolTips();
@@ -1308,6 +1141,7 @@ void DebuggerToolTipManager::saveSessionData()
tooltip->saveSessionData(w);
w.writeEndDocument();
+ return; // FIXME
setSessionValue(sessionSettingsKeyC, QVariant(data));
}
@@ -1341,7 +1175,7 @@ static void slotTooltipOverrideRequested
DebuggerToolTipContext context;
context.engineType = engine->objectName();
- context.fileName = editorWidget->textDocument()->filePath();
+ context.fileName = editorWidget->textDocument()->filePath().toString();
context.position = pos;
editorWidget->convertPosition(pos, &context.line, &context.column);
QString raw = cppExpressionAt(editorWidget, context.position, &context.line, &context.column,
@@ -1349,8 +1183,8 @@ static void slotTooltipOverrideRequested
context.expression = fixCppExpression(raw);
if (context.expression.isEmpty()) {
- const Utils::TextContent text(DebuggerToolTipManager::tr("No valid expression"));
- Utils::ToolTip::show(point, text, Internal::mainWindow());
+ ToolTip::show(point, DebuggerToolTipManager::tr("No valid expression"),
+ Internal::mainWindow());
*handled = true;
return;
}
@@ -1375,21 +1209,17 @@ static void slotTooltipOverrideRequested
return;
}
- tooltip->filterModel.setSourceModel(engine->watchHandler()->model());
-
if (localVariable) {
DEBUG("SYNC IN STATE" << tooltip->state);
if (tooltip->state == New) {
tooltip->setState(PendingUnshown);
tooltip->setState(PendingShown);
- tooltip->acquireEngine();
- const Utils::WidgetContent widgetContent(tooltip->widget, true);
- Utils::ToolTip::show(point, widgetContent, Internal::mainWindow());
+ ToolTip::show(point, tooltip->widget, Internal::mainWindow());
} else {
- tooltip->acquireEngine();
- Utils::ToolTip::move(point, Internal::mainWindow());
+ ToolTip::move(point, Internal::mainWindow());
}
*handled = true;
+ tooltip->updateTooltip(engine);
} else {
DEBUG("ASYNC TIP IN STATE" << tooltip->state);
if (tooltip->state == New)
@@ -1400,8 +1230,8 @@ static void slotTooltipOverrideRequested
QTC_CHECK(false);
*handled = engine->setToolTipExpression(editorWidget, context);
if (!*handled) {
- const Utils::TextContent text(DebuggerToolTipManager::tr("Expression too complex"));
- Utils::ToolTip::show(point, text, Internal::mainWindow());
+ ToolTip::show(point, DebuggerToolTipManager::tr("Expression too complex"),
+ Internal::mainWindow());
tooltip->destroy();
}
}
@@ -1512,5 +1342,6 @@ static void purgeClosedToolTips()
}
}
+
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/debuggertooltipmanager.h b/src/plugins/debugger/debuggertooltipmanager.h
index f45df7df0ec..0538c8089a6 100644
--- a/src/plugins/debugger/debuggertooltipmanager.h
+++ b/src/plugins/debugger/debuggertooltipmanager.h
@@ -42,11 +42,9 @@ class QAbstractItemModel;
QT_END_NAMESPACE
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
+class DebuggerEngine;
class StackFrame;
class DebuggerToolTipContext
@@ -56,6 +54,7 @@ public:
bool isValid() const { return !expression.isEmpty(); }
bool matchesFrame(const StackFrame &frame) const;
bool isSame(const DebuggerToolTipContext &other) const;
+ QString toolTip() const;
QString fileName;
int position;
@@ -91,8 +90,6 @@ public:
virtual bool eventFilter(QObject *, QEvent *);
- static QString treeModelClipboardContents(const QAbstractItemModel *model);
-
void debugModeEntered();
void leavingDebugMode();
void sessionAboutToChange();
@@ -103,8 +100,6 @@ public:
public slots:
static void slotUpdateVisibleToolTips();
- void slotItemIsExpanded(const QModelIndex &idx);
- void slotColumnAdjustmentRequested();
};
} // namespace Internal
diff --git a/src/plugins/debugger/disassembleragent.cpp b/src/plugins/debugger/disassembleragent.cpp
index eef3a9281b0..f7a96c3ca57 100644
--- a/src/plugins/debugger/disassembleragent.cpp
+++ b/src/plugins/debugger/disassembleragent.cpp
@@ -332,25 +332,24 @@ void DisassemblerAgent::updateBreakpointMarkers()
if (!d->document)
return;
- BreakHandler *handler = breakHandler();
- BreakpointModelIds ids = handler->engineBreakpointIds(d->engine);
- if (ids.isEmpty())
+ Breakpoints bps = breakHandler()->engineBreakpoints(d->engine);
+ if (bps.isEmpty())
return;
const DisassemblerLines contents = d->contentsAtCurrentLocation();
- foreach (TextEditor::TextMark *marker, d->breakpointMarks)
+ foreach (TextMark *marker, d->breakpointMarks)
d->document->removeMark(marker);
qDeleteAll(d->breakpointMarks);
d->breakpointMarks.clear();
- foreach (BreakpointModelId id, ids) {
- const quint64 address = handler->response(id).address;
+ foreach (Breakpoint bp, bps) {
+ const quint64 address = bp.response().address;
if (!address)
continue;
const int lineNumber = contents.lineForAddress(address);
if (!lineNumber)
continue;
TextMark *marker = new TextMark(QString(), lineNumber);
- marker->setIcon(handler->icon(id));
+ marker->setIcon(bp.icon());
marker->setPriority(TextMark::NormalPriority);
d->breakpointMarks.append(marker);
d->document->addMark(marker);
diff --git a/src/plugins/debugger/disassembleragent.h b/src/plugins/debugger/disassembleragent.h
index cb6c02f53fa..d99714cec08 100644
--- a/src/plugins/debugger/disassembleragent.h
+++ b/src/plugins/debugger/disassembleragent.h
@@ -34,13 +34,12 @@
#include <QObject>
namespace Debugger {
+namespace Internal {
class DebuggerEngine;
-
-namespace Internal {
+class DisassemblerAgentPrivate;
class DisassemblerLines;
class Location;
-class DisassemblerAgentPrivate;
class DisassemblerAgent : public QObject
{
diff --git a/src/plugins/debugger/gdb/attachgdbadapter.cpp b/src/plugins/debugger/gdb/attachgdbadapter.cpp
index 84e5fdfeae5..aef3139c49c 100644
--- a/src/plugins/debugger/gdb/attachgdbadapter.cpp
+++ b/src/plugins/debugger/gdb/attachgdbadapter.cpp
@@ -36,14 +36,9 @@
#include <utils/qtcassert.h>
-
namespace Debugger {
namespace Internal {
-#define CB(callback) \
- static_cast<GdbEngine::GdbCommandCallback>(&GdbAttachEngine::callback), \
- STRINGIFY(callback)
-
///////////////////////////////////////////////////////////////////////
//
// AttachGdbAdapter
@@ -72,7 +67,8 @@ void GdbAttachEngine::setupInferior()
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
const qint64 pid = startParameters().attachPID;
- postCommand("attach " + QByteArray::number(pid), CB(handleAttach));
+ postCommand("attach " + QByteArray::number(pid), NoFlags,
+ [this](const DebuggerResponse &r) { handleAttach(r); });
// Task 254674 does not want to remove them
//qq->breakHandler()->removeAllBreakpoints();
}
@@ -85,17 +81,17 @@ void GdbAttachEngine::runEngine()
handleStop1(GdbMi());
}
-void GdbAttachEngine::handleAttach(const GdbResponse &response)
+void GdbAttachEngine::handleAttach(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
switch (response.resultClass) {
- case GdbResultDone:
- case GdbResultRunning:
+ case ResultDone:
+ case ResultRunning:
showMessage(_("INFERIOR ATTACHED"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
handleInferiorPrepared();
break;
- case GdbResultError:
+ case ResultError:
if (response.data["msg"].data() == "ptrace: Operation not permitted.") {
notifyInferiorSetupFailed(msgPtraceError(startParameters().startMode));
break;
diff --git a/src/plugins/debugger/gdb/attachgdbadapter.h b/src/plugins/debugger/gdb/attachgdbadapter.h
index d67d70404e8..6d03609ef23 100644
--- a/src/plugins/debugger/gdb/attachgdbadapter.h
+++ b/src/plugins/debugger/gdb/attachgdbadapter.h
@@ -57,7 +57,7 @@ private:
void interruptInferior2();
void shutdownEngine();
- void handleAttach(const GdbResponse &response);
+ void handleAttach(const DebuggerResponse &response);
};
} // namespace Internal
diff --git a/src/plugins/debugger/gdb/coregdbadapter.cpp b/src/plugins/debugger/gdb/coregdbadapter.cpp
index cfddb8aff79..aeb404a06ac 100644
--- a/src/plugins/debugger/gdb/coregdbadapter.cpp
+++ b/src/plugins/debugger/gdb/coregdbadapter.cpp
@@ -30,6 +30,8 @@
#include "coregdbadapter.h"
+#include <coreplugin/messagebox.h>
+
#include <debugger/debuggercore.h>
#include <debugger/debuggerprotocol.h>
#include <debugger/debuggerstartparameters.h>
@@ -39,7 +41,6 @@
#include <utils/qtcassert.h>
#include <QDir>
-#include <QMessageBox>
#include <QTemporaryFile>
using namespace Utils;
@@ -47,9 +48,7 @@ using namespace Utils;
namespace Debugger {
namespace Internal {
-#define CB(callback) \
- static_cast<GdbEngine::GdbCommandCallback>(&GdbCoreEngine::callback), \
- STRINGIFY(callback)
+#define CB(callback) [this](const DebuggerResponse &r) { callback(r); }
///////////////////////////////////////////////////////////////////////
//
@@ -185,7 +184,7 @@ void GdbCoreEngine::continueSetupEngine()
if (cinfo.isCore) {
m_executable = cinfo.foundExecutableName;
if (m_executable.isEmpty()) {
- showMessageBox(QMessageBox::Warning,
+ Core::AsynchronousMessageBox::warning(
tr("Error Loading Symbols"),
tr("No executable to load symbols from specified core."));
notifyEngineSetupFailed();
@@ -196,7 +195,7 @@ void GdbCoreEngine::continueSetupEngine()
if (isCore) {
startGdb();
} else {
- showMessageBox(QMessageBox::Warning,
+ Core::AsynchronousMessageBox::warning(
tr("Error Loading Core File"),
tr("The specified file does not appear to be a core file."));
notifyEngineSetupFailed();
@@ -214,17 +213,17 @@ void GdbCoreEngine::setupInferior()
// Do that first, otherwise no symbols are loaded.
QFileInfo fi(m_executable);
QByteArray path = fi.absoluteFilePath().toLocal8Bit();
- postCommand("-file-exec-and-symbols \"" + path + '"',
+ postCommand("-file-exec-and-symbols \"" + path + '"', NoFlags,
CB(handleFileExecAndSymbols));
}
-void GdbCoreEngine::handleFileExecAndSymbols(const GdbResponse &response)
+void GdbCoreEngine::handleFileExecAndSymbols(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
QString core = coreFileName();
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
showMessage(tr("Symbols found."), StatusBar);
- postCommand("target core " + core.toLocal8Bit(),
+ postCommand("target core " + core.toLocal8Bit(), NoFlags,
CB(handleTargetCore));
return;
}
@@ -239,17 +238,17 @@ void GdbCoreEngine::handleFileExecAndSymbols(const GdbResponse &response)
notifyInferiorSetupFailed(msg);
}
-void GdbCoreEngine::handleTargetCore(const GdbResponse &response)
+void GdbCoreEngine::handleTargetCore(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
showMessage(tr("Attached to core."), StatusBar);
handleInferiorPrepared();
// Due to the auto-solib-add off setting, we don't have any
// symbols yet. Load them in order of importance.
- reloadStack(true);
+ reloadStack();
reloadModulesInternal();
- postCommand("p 5", CB(handleRoundTrip));
+ postCommand("p 5", NoFlags, CB(handleRoundTrip));
return;
}
QString msg = tr("Attach to core \"%1\" failed:")
@@ -259,7 +258,7 @@ void GdbCoreEngine::handleTargetCore(const GdbResponse &response)
notifyInferiorSetupFailed(msg);
}
-void GdbCoreEngine::handleRoundTrip(const GdbResponse &response)
+void GdbCoreEngine::handleRoundTrip(const DebuggerResponse &response)
{
Q_UNUSED(response);
loadSymbolsForStack();
@@ -303,7 +302,8 @@ void GdbCoreEngine::unpackCoreIfNeeded()
m_coreUnpackProcess = new QProcess(this);
m_coreUnpackProcess->setWorkingDirectory(QDir::tempPath());
m_coreUnpackProcess->start(QLatin1String("lzop"), arguments);
- connect(m_coreUnpackProcess, SIGNAL(finished(int)), SLOT(continueSetupEngine()));
+ connect(m_coreUnpackProcess, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
+ this, &GdbCoreEngine::continueSetupEngine);
} else if (m_coreName.endsWith(QLatin1String(".gz"))) {
m_tempCoreName = tempCoreFilename();
showMessage(msg.arg(m_tempCoreName));
@@ -313,8 +313,9 @@ void GdbCoreEngine::unpackCoreIfNeeded()
m_coreUnpackProcess = new QProcess(this);
m_coreUnpackProcess->setWorkingDirectory(QDir::tempPath());
m_coreUnpackProcess->start(QLatin1String("gzip"), arguments);
- connect(m_coreUnpackProcess, SIGNAL(readyRead()), SLOT(writeCoreChunk()));
- connect(m_coreUnpackProcess, SIGNAL(finished(int)), SLOT(continueSetupEngine()));
+ connect(m_coreUnpackProcess, &QProcess::readyRead, this, &GdbCoreEngine::writeCoreChunk);
+ connect(m_coreUnpackProcess, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
+ this, &GdbCoreEngine::continueSetupEngine);
} else {
continueSetupEngine();
}
diff --git a/src/plugins/debugger/gdb/coregdbadapter.h b/src/plugins/debugger/gdb/coregdbadapter.h
index 4522789c540..965a8bcd1f6 100644
--- a/src/plugins/debugger/gdb/coregdbadapter.h
+++ b/src/plugins/debugger/gdb/coregdbadapter.h
@@ -59,6 +59,7 @@ public:
bool isCore;
};
static CoreInfo readExecutableNameFromCore(const QString &debuggerCmd, const QString &coreFile);
+
private:
void setupEngine();
void setupInferior();
@@ -66,9 +67,9 @@ private:
void interruptInferior();
void shutdownEngine();
- void handleFileExecAndSymbols(const GdbResponse &response);
- void handleTargetCore(const GdbResponse &response);
- void handleRoundTrip(const GdbResponse &response);
+ void handleFileExecAndSymbols(const DebuggerResponse &response);
+ void handleTargetCore(const DebuggerResponse &response);
+ void handleRoundTrip(const DebuggerResponse &response);
void unpackCoreIfNeeded();
QString coreFileName() const;
QString coreName() const;
diff --git a/src/plugins/debugger/gdb/gdbengine.cpp b/src/plugins/debugger/gdb/gdbengine.cpp
index 8072f737edc..56ae99126ca 100644
--- a/src/plugins/debugger/gdb/gdbengine.cpp
+++ b/src/plugins/debugger/gdb/gdbengine.cpp
@@ -52,6 +52,7 @@
#include <debugger/disassembleragent.h>
#include <debugger/memoryagent.h>
#include <debugger/sourceutils.h>
+#include <debugger/terminal.h>
#include <debugger/breakhandler.h>
#include <debugger/moduleshandler.h>
@@ -65,6 +66,7 @@
#include <debugger/shared/hostutils.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <projectexplorer/devicesupport/deviceprocess.h>
#include <projectexplorer/itaskhandler.h>
#include <projectexplorer/taskhub.h>
@@ -77,11 +79,11 @@
#include <utils/qtcprocess.h>
#include <utils/savedaction.h>
+#include <QBuffer>
#include <QDirIterator>
-#include <QTemporaryFile>
-
#include <QMessageBox>
#include <QPushButton>
+#include <QTemporaryFile>
using namespace Core;
using namespace ProjectExplorer;
@@ -94,8 +96,7 @@ enum { debugPending = 0 };
#define PENDING_DEBUG(s) do { if (debugPending) qDebug() << s; } while (0)
-#define CB(callback) &GdbEngine::callback, STRINGIFY(callback)
-
+#define CB(callback) [this](const DebuggerResponse &r) { callback(r); }
QByteArray GdbEngine::tooltipIName(const QString &exp)
{
@@ -141,7 +142,7 @@ static int &currentToken()
return token;
}
-static QByteArray parsePlainConsoleStream(const GdbResponse &response)
+static QByteArray parsePlainConsoleStream(const DebuggerResponse &response)
{
QByteArray out = response.consoleStreamOutput;
// FIXME: proper decoding needed
@@ -221,7 +222,6 @@ GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters)
m_pendingBreakpointRequests = 0;
m_commandsDoneCallback = 0;
m_stackNeeded = false;
- m_preparedForQmlBreak = false;
m_terminalTrap = startParameters.useTerminal;
m_fullStartDone = false;
m_systemDumpersLoaded = false;
@@ -231,16 +231,17 @@ GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters)
//ExtensionSystem::PluginManager::addObject(m_debugInfoTaskHandler);
m_commandTimer.setSingleShot(true);
- connect(&m_commandTimer, SIGNAL(timeout()), SLOT(commandTimeout()));
+ connect(&m_commandTimer, &QTimer::timeout,
+ this, &GdbEngine::commandTimeout);
- connect(action(AutoDerefPointers), SIGNAL(valueChanged(QVariant)),
- SLOT(reloadLocals()));
- connect(action(CreateFullBacktrace), SIGNAL(triggered()),
- SLOT(createFullBacktrace()));
- connect(action(UseDebuggingHelpers), SIGNAL(valueChanged(QVariant)),
- SLOT(reloadLocals()));
- connect(action(UseDynamicType), SIGNAL(valueChanged(QVariant)),
- SLOT(reloadLocals()));
+ connect(action(AutoDerefPointers), &SavedAction::valueChanged,
+ this, &GdbEngine::reloadLocals);
+ connect(action(CreateFullBacktrace), &QAction::triggered,
+ this, &GdbEngine::createFullBacktrace);
+ connect(action(UseDebuggingHelpers), &SavedAction::valueChanged,
+ this, &GdbEngine::reloadLocals);
+ connect(action(UseDynamicType), &SavedAction::valueChanged,
+ this, &GdbEngine::reloadLocals);
}
GdbEngine::~GdbEngine()
@@ -534,7 +535,7 @@ void GdbEngine::handleResponse(const QByteArray &buff)
result = GdbMi();
result.fromString(ba);
BreakHandler *handler = breakHandler();
- BreakpointModelId id;
+ Breakpoint bp;
BreakpointResponse br;
foreach (const GdbMi &bkpt, result.children()) {
const QByteArray nr = bkpt["number"].data();
@@ -546,17 +547,15 @@ void GdbEngine::handleResponse(const QByteArray &buff)
updateResponse(sub, bkpt);
sub.id = rid;
sub.type = br.type;
- handler->insertSubBreakpoint(id, sub);
+ bp.insertSubBreakpoint(sub);
} else {
// A primary breakpoint.
- id = handler->findBreakpointByResponseId(rid);
+ bp = handler->findBreakpointByResponseId(rid);
//qDebug() << "NR: " << nr << "RID: " << rid
- // << "ID: " << id;
- //BreakpointModelId id =
- // handler->findBreakpointByResponseId(rid);
- br = handler->response(id);
+ // << "ID: " << bp.id();
+ br = bp.response();
updateResponse(br, bkpt);
- handler->setResponse(id, br);
+ bp.setResponse(br);
}
}
}
@@ -576,16 +575,14 @@ void GdbEngine::handleResponse(const QByteArray &buff)
} else if (asyncClass == "breakpoint-deleted") {
// "breakpoint-deleted" "{id="1"}"
// New in FSF gdb since 2011-04-27.
- BreakHandler *handler = breakHandler();
QByteArray nr = result["id"].data();
BreakpointResponseId rid(nr);
- BreakpointModelId id = handler->findBreakpointByResponseId(rid);
- if (id.isValid()) {
+ if (Breakpoint bp = breakHandler()->findBreakpointByResponseId(rid)) {
// This also triggers when a temporary breakpoint is hit.
// We do not really want that, as this loses all information.
// FIXME: Use a special marker for this case?
- if (!handler->isOneShot(id))
- handler->removeAlienBreakpoint(id);
+ if (!bp.isOneShot())
+ bp.removeAlienBreakpoint();
}
} else if (asyncClass == "cmd-param-changed") {
// New since 2012-08-09
@@ -641,15 +638,6 @@ void GdbEngine::handleResponse(const QByteArray &buff)
const Task::TaskType type = isFatalWinException(exCode) ? Task::Error : Task::Warning;
TaskHub::addTask(type, m_lastWinException, Constants::TASK_CATEGORY_DEBUGGER_RUNTIME);
}
-
- if (data.startsWith("QMLBP:")) {
- int pos1 = 6;
- int pos2 = data.indexOf(' ', pos1);
- m_qmlBreakpointResponseId2 = BreakpointResponseId(data.mid(pos1, pos2 - pos1));
- //qDebug() << "FOUND QMLBP: " << m_qmlBreakpointNumbers[2];
- //qDebug() << "CURRENT: " << m_qmlBreakpointNumbers;
- }
-
break;
}
@@ -696,7 +684,7 @@ void GdbEngine::handleResponse(const QByteArray &buff)
}
case '^': {
- GdbResponse response;
+ DebuggerResponse response;
response.token = token;
@@ -706,17 +694,17 @@ void GdbEngine::handleResponse(const QByteArray &buff)
QByteArray resultClass = QByteArray::fromRawData(from, inner - from);
if (resultClass == "done")
- response.resultClass = GdbResultDone;
+ response.resultClass = ResultDone;
else if (resultClass == "running")
- response.resultClass = GdbResultRunning;
+ response.resultClass = ResultRunning;
else if (resultClass == "connected")
- response.resultClass = GdbResultConnected;
+ response.resultClass = ResultConnected;
else if (resultClass == "error")
- response.resultClass = GdbResultError;
+ response.resultClass = ResultError;
else if (resultClass == "exit")
- response.resultClass = GdbResultExit;
+ response.resultClass = ResultExit;
else
- response.resultClass = GdbResultUnknown;
+ response.resultClass = ResultUnknown;
from = inner;
if (from != to) {
@@ -803,6 +791,9 @@ void GdbEngine::interruptInferior()
QTC_ASSERT(state() == InferiorStopRequested,
qDebug() << "INTERRUPT INFERIOR: " << state(); return);
+ if (terminal()->sendInterrupt())
+ return;
+
if (usesExecInterrupt()) {
postCommand("-exec-interrupt", Immediate);
} else {
@@ -839,7 +830,7 @@ void GdbEngine::handleInterruptDeviceInferior(const QString &error)
void GdbEngine::interruptInferiorTemporarily()
{
- foreach (const GdbCommand &cmd, m_commandsToRunOnTemporaryBreak) {
+ foreach (const DebuggerCommand &cmd, m_commandsToRunOnTemporaryBreak) {
if (cmd.flags & LosesChild) {
notifyInferiorIll();
return;
@@ -862,40 +853,33 @@ void GdbEngine::maybeHandleInferiorPidChanged(const QString &pid0)
notifyInferiorPid(pid);
}
-void GdbEngine::postCommand(const QByteArray &command, GdbCommandCallback callback,
- const char *callbackName, const QVariant &cookie)
+void GdbEngine::runCommand(const DebuggerCommand &command)
{
- postCommand(command, NoFlags, callback, callbackName, cookie);
+ QByteArray cmd = command.function + "({" + command.args + "})";
+ postCommand("python theDumper." + cmd, command.flags, command.callback);
}
-void GdbEngine::postCommand(const QByteArray &command, GdbCommandFlags flags,
- GdbCommandCallback callback, const char *callbackName,
- const QVariant &cookie)
+void GdbEngine::postCommand(const QByteArray &command, int flags,
+ DebuggerCommand::Callback callback)
{
- GdbCommand cmd;
- cmd.command = command;
+ DebuggerCommand cmd;
+ cmd.function = command;
cmd.flags = flags;
cmd.callback = callback;
- cmd.callbackName = callbackName;
- cmd.cookie = cookie;
- postCommandHelper(cmd);
-}
-void GdbEngine::postCommandHelper(const GdbCommand &cmd)
-{
if (!stateAcceptsGdbCommands(state())) {
- PENDING_DEBUG(_("NO GDB PROCESS RUNNING, CMD IGNORED: " + cmd.command));
+ PENDING_DEBUG(_("NO GDB PROCESS RUNNING, CMD IGNORED: " + cmd.function));
showMessage(_("NO GDB PROCESS RUNNING, CMD IGNORED: %1 %2")
- .arg(_(cmd.command)).arg(state()));
+ .arg(_(cmd.function)).arg(state()));
return;
}
if (cmd.flags & RebuildBreakpointModel) {
++m_pendingBreakpointRequests;
- PENDING_DEBUG(" BRWAKPOINT MODEL:" << cmd.command << "=>" << cmd.callbackName
+ PENDING_DEBUG(" BRWAKPOINT MODEL:" << cmd.function
<< "INCREMENTS PENDING TO" << m_pendingBreakpointRequests);
} else {
- PENDING_DEBUG(" OTHER (IN):" << cmd.command << "=>" << cmd.callbackName
+ PENDING_DEBUG(" OTHER (IN):" << cmd.function
<< "LEAVES PENDING WATCH AT" << m_uncompleted.size()
<< "LEAVES PENDING BREAKPOINT AT" << m_pendingBreakpointRequests);
}
@@ -916,7 +900,7 @@ void GdbEngine::postCommandHelper(const GdbCommand &cmd)
flushCommand(cmd);
} else {
// Queue the commands that we cannot send at once.
- showMessage(_("QUEUING COMMAND " + cmd.command));
+ showMessage(_("QUEUING COMMAND " + cmd.function));
m_commandsToRunOnTemporaryBreak.append(cmd);
if (state() == InferiorStopRequested) {
if (cmd.flags & LosesChild)
@@ -929,10 +913,10 @@ void GdbEngine::postCommandHelper(const GdbCommand &cmd)
interruptInferiorTemporarily();
} else {
qDebug() << "ATTEMPTING TO QUEUE COMMAND "
- << cmd.command << "IN INAPPROPRIATE STATE" << state();
+ << cmd.function << "IN INAPPROPRIATE STATE" << state();
}
}
- } else if (!cmd.command.isEmpty()) {
+ } else if (!cmd.function.isEmpty()) {
flushCommand(cmd);
}
}
@@ -941,17 +925,16 @@ void GdbEngine::flushQueuedCommands()
{
showStatusMessage(tr("Processing queued commands"), 1000);
while (!m_commandsToRunOnTemporaryBreak.isEmpty()) {
- GdbCommand cmd = m_commandsToRunOnTemporaryBreak.takeFirst();
- showMessage(_("RUNNING QUEUED COMMAND " + cmd.command + ' '
- + (cmd.callbackName ? cmd.callbackName : "<unnamed callback>")));
+ DebuggerCommand cmd = m_commandsToRunOnTemporaryBreak.takeFirst();
+ showMessage(_("RUNNING QUEUED COMMAND " + cmd.function));
flushCommand(cmd);
}
}
-void GdbEngine::flushCommand(const GdbCommand &cmd0)
+void GdbEngine::flushCommand(const DebuggerCommand &cmd0)
{
if (!stateAcceptsGdbCommands(state())) {
- showMessage(_(cmd0.command), LogInput);
+ showMessage(_(cmd0.function), LogInput);
showMessage(_("GDB PROCESS ACCEPTS NO CMD IN STATE %1 ").arg(state()));
return;
}
@@ -960,13 +943,13 @@ void GdbEngine::flushCommand(const GdbCommand &cmd0)
const int token = ++currentToken();
- GdbCommand cmd = cmd0;
+ DebuggerCommand cmd = cmd0;
cmd.postTime = QTime::currentTime();
- m_cookieForToken[token] = cmd;
+ m_commandForToken[token] = cmd;
if (cmd.flags & ConsoleCommand)
- cmd.command = "-interpreter-exec console \"" + cmd.command + '"';
- cmd.command = QByteArray::number(token) + cmd.command;
- showMessage(_(cmd.command), LogInput);
+ cmd.function = "-interpreter-exec console \"" + cmd.function + '"';
+ cmd.function = QByteArray::number(token) + cmd.function;
+ showMessage(_(cmd.function), LogInput);
if (m_scheduledTestResponses.contains(token)) {
// Fake response for test cases.
@@ -978,7 +961,7 @@ void GdbEngine::flushCommand(const GdbCommand &cmd0)
QMetaObject::invokeMethod(this, "handleResponse",
Q_ARG(QByteArray, buffer));
} else {
- write(cmd.command + "\r\n");
+ write(cmd.function + "\r\n");
// Start Watchdog.
if (m_commandTimer.interval() <= 20000)
@@ -987,7 +970,7 @@ void GdbEngine::flushCommand(const GdbCommand &cmd0)
// sent and a response could be retrieved. We don't want the watchdog
// to bark in that case since the only possible outcome is a dead
// process anyway.
- if (!cmd.command.endsWith("-gdb-exit"))
+ if (!cmd.function.endsWith("-gdb-exit"))
m_commandTimer.start();
//if (cmd.flags & LosesChild)
@@ -1003,23 +986,20 @@ int GdbEngine::commandTimeoutTime() const
void GdbEngine::commandTimeout()
{
- QList<int> keys = m_cookieForToken.keys();
+ QList<int> keys = m_commandForToken.keys();
Utils::sort(keys);
bool killIt = false;
foreach (int key, keys) {
- const GdbCommand &cmd = m_cookieForToken.value(key);
+ const DebuggerCommand &cmd = m_commandForToken.value(key);
if (!(cmd.flags & NonCriticalResponse))
killIt = true;
- QByteArray msg = QByteArray::number(key);
- msg += ": " + cmd.command + " => ";
- msg += cmd.callbackName ? cmd.callbackName : "<unnamed callback>";
- showMessage(_(msg));
+ showMessage(_(QByteArray::number(key) + ": " + cmd.function));
}
if (killIt) {
QStringList commands;
- foreach (const GdbCommand &cookie, m_cookieForToken)
+ foreach (const DebuggerCommand &cmd, m_commandForToken)
commands << QString(_("\"%1\"")).arg(
- QString::fromLatin1(cookie.command));
+ QString::fromLatin1(cmd.function));
showMessage(_("TIMED OUT WAITING FOR GDB REPLY. "
"COMMANDS STILL IN PROGRESS: ") + commands.join(_(", ")));
int timeOut = m_commandTimer.interval();
@@ -1047,7 +1027,7 @@ void GdbEngine::commandTimeout()
}
}
-void GdbEngine::handleResultRecord(GdbResponse *response)
+void GdbEngine::handleResultRecord(DebuggerResponse *response)
{
//qDebug() << "TOKEN:" << response->token
// << " ACCEPTABLE:" << m_oldestAcceptableToken;
@@ -1057,7 +1037,7 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
if (token == -1)
return;
- if (!m_cookieForToken.contains(token)) {
+ if (!m_commandForToken.contains(token)) {
// In theory this should not happen (rather the error should be
// reported in the "first" response to the command) in practice it
// does. We try to handle a few situations we are aware of gracefully.
@@ -1065,14 +1045,14 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
showMessage(_("COOKIE FOR TOKEN %1 ALREADY EATEN (%2). "
"TWO RESPONSES FOR ONE COMMAND?").arg(token).
arg(QString::fromLatin1(stateName(state()))));
- if (response->resultClass == GdbResultError) {
+ if (response->resultClass == ResultError) {
QByteArray msg = response->data["msg"].data();
if (msg == "Cannot find new threads: generic error") {
// Handle a case known to occur on Linux/gdb 6.8 when debugging moc
// with helpers enabled. In this case we get a second response with
// msg="Cannot find new threads: generic error"
showMessage(_("APPLYING WORKAROUND #1"));
- showMessageBox(QMessageBox::Critical,
+ AsynchronousMessageBox::critical(
tr("Executable failed"), QString::fromLocal8Bit(msg));
showStatusMessage(tr("Process failed to start"));
//shutdown();
@@ -1098,7 +1078,7 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
//showStatusMessage(tr("Executable failed: %1")
// .arg(QString::fromLocal8Bit(msg)));
//shutdown();
- //showMessageBox(QMessageBox::Critical,
+ //Core::AsynchronousMessageBox::critical(
// tr("Executable failed"), QString::fromLocal8Bit(msg));
} else if (msg.contains("Cannot insert breakpoint")) {
// For breakpoints set by address to non-existent addresses we
@@ -1112,7 +1092,7 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
// long as the breakpoints are enabled.
// FIXME: Should we silently disable the offending breakpoints?
showMessage(_("APPLYING WORKAROUND #5"));
- showMessageBox(QMessageBox::Critical,
+ AsynchronousMessageBox::critical(
tr("Setting breakpoints failed"), QString::fromLocal8Bit(msg));
QTC_CHECK(state() == InferiorRunOk);
notifyInferiorSpontaneousStop();
@@ -1128,17 +1108,17 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
if (!m_lastWinException.isEmpty())
logMsg = m_lastWinException + QLatin1Char('\n');
logMsg += QString::fromLocal8Bit(msg);
- showMessageBox(QMessageBox::Critical, tr("Executable Failed"), logMsg);
+ AsynchronousMessageBox::critical(tr("Executable Failed"), logMsg);
showStatusMessage(tr("Executable failed: %1").arg(logMsg));
}
}
return;
}
- GdbCommand cmd = m_cookieForToken.take(token);
+ DebuggerCommand cmd = m_commandForToken.take(token);
if (boolSetting(LogTimeStamps)) {
showMessage(_("Response time: %1: %2 s")
- .arg(_(cmd.command))
+ .arg(_(cmd.function))
.arg(cmd.postTime.msecsTo(QTime::currentTime()) / 1000.),
LogTime);
}
@@ -1148,33 +1128,31 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
return;
}
- response->cookie = cmd.cookie;
-
bool isExpectedResult =
- (response->resultClass == GdbResultError) // Can always happen.
- || (response->resultClass == GdbResultRunning && (cmd.flags & RunRequest))
- || (response->resultClass == GdbResultExit && (cmd.flags & ExitRequest))
- || (response->resultClass == GdbResultDone);
- // GdbResultDone can almost "always" happen. Known examples are:
- // (response->resultClass == GdbResultDone && cmd.command == "continue")
+ (response->resultClass == ResultError) // Can always happen.
+ || (response->resultClass == ResultRunning && (cmd.flags & RunRequest))
+ || (response->resultClass == ResultExit && (cmd.flags & ExitRequest))
+ || (response->resultClass == ResultDone);
+ // ResultDone can almost "always" happen. Known examples are:
+ // (response->resultClass == ResultDone && cmd.function == "continue")
// Happens with some incarnations of gdb 6.8 for "jump to line"
- // (response->resultClass == GdbResultDone && cmd.command.startsWith("jump"))
- // (response->resultClass == GdbResultDone && cmd.command.startsWith("detach"))
+ // (response->resultClass == ResultDone && cmd.function.startsWith("jump"))
+ // (response->resultClass == ResultDone && cmd.function.startsWith("detach"))
// Happens when stepping finishes very quickly and issues *stopped and ^done
// instead of ^running and *stopped
- // (response->resultClass == GdbResultDone && (cmd.flags & RunRequest));
+ // (response->resultClass == ResultDone && (cmd.flags & RunRequest));
if (!isExpectedResult) {
const DebuggerStartParameters &sp = startParameters();
Abi abi = sp.toolChainAbi;
if (abi.os() == Abi::WindowsOS
- && cmd.command.startsWith("attach")
+ && cmd.function.startsWith("attach")
&& (sp.startMode == AttachExternal || sp.useTerminal))
{
// Ignore spurious 'running' responses to 'attach'.
} else {
- QByteArray rsp = GdbResponse::stringFromResultClass(response->resultClass);
- rsp = "UNEXPECTED RESPONSE '" + rsp + "' TO COMMAND '" + cmd.command + "'";
+ QByteArray rsp = DebuggerResponse::stringFromResultClass(response->resultClass);
+ rsp = "UNEXPECTED RESPONSE '" + rsp + "' TO COMMAND '" + cmd.function + "'";
qWarning() << rsp << " AT " __FILE__ ":" STRINGIFY(__LINE__);
showMessage(_(rsp));
}
@@ -1184,18 +1162,18 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
--m_nonDiscardableCount;
if (cmd.callback)
- (this->*cmd.callback)(*response);
+ cmd.callback(*response);
if (cmd.flags & RebuildBreakpointModel) {
--m_pendingBreakpointRequests;
- PENDING_DEBUG(" BREAKPOINT" << cmd.command << "=>" << cmd.callbackName
+ PENDING_DEBUG(" BREAKPOINT" << cmd.function
<< "DECREMENTS PENDING TO" << m_uncompleted.size());
if (m_pendingBreakpointRequests <= 0) {
PENDING_DEBUG("\n\n ... AND TRIGGERS BREAKPOINT MODEL UPDATE\n");
attemptBreakpointSynchronization();
}
} else {
- PENDING_DEBUG(" OTHER (OUT):" << cmd.command << "=>" << cmd.callbackName
+ PENDING_DEBUG(" OTHER (OUT):" << cmd.function
<< "LEAVES PENDING WATCH AT" << m_uncompleted.size()
<< "LEAVES PENDING BREAKPOINT AT" << m_pendingBreakpointRequests);
}
@@ -1213,17 +1191,17 @@ void GdbEngine::handleResultRecord(GdbResponse *response)
// An optimization would be requesting the continue immediately when the
// event loop is entered, and let individual commands have a flag to suppress
// that behavior.
- if (m_commandsDoneCallback && m_cookieForToken.isEmpty()) {
+ if (m_commandsDoneCallback && m_commandForToken.isEmpty()) {
showMessage(_("ALL COMMANDS DONE; INVOKING CALLBACK"));
CommandsDoneCallback cont = m_commandsDoneCallback;
m_commandsDoneCallback = 0;
- if (response->resultClass != GdbResultRunning) //only start if the thing is not already running
+ if (response->resultClass != ResultRunning) //only start if the thing is not already running
(this->*cont)();
} else {
- PENDING_DEBUG("MISSING TOKENS: " << m_cookieForToken.keys());
+ PENDING_DEBUG("MISSING TOKENS: " << m_commandForToken.keys());
}
- if (m_cookieForToken.isEmpty())
+ if (m_commandForToken.isEmpty())
m_commandTimer.stop();
}
@@ -1239,8 +1217,8 @@ void GdbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages
if (!(languages & CppLanguage))
return;
QTC_CHECK(acceptsDebuggerCommands());
- GdbCommand cmd;
- cmd.command = command.toLatin1();
+ DebuggerCommand cmd;
+ cmd.function = command.toLatin1();
flushCommand(cmd);
}
@@ -1250,18 +1228,20 @@ void GdbEngine::updateAll()
//PENDING_DEBUG("UPDATING ALL\n");
QTC_CHECK(state() == InferiorUnrunnable || state() == InferiorStopOk);
reloadModulesInternal();
- postCommand("-stack-list-frames", CB(handleStackListFrames),
- QVariant::fromValue<StackCookie>(StackCookie(false, true)));
+ DebuggerCommand cmd = stackCommand(action(MaximalStackDepth)->value().toInt());
+ cmd.flags = NoFlags;
+ cmd.callback = [this](const DebuggerResponse &r) { handleStackListFrames(r, false); };
+ runCommand(cmd);
stackHandler()->setCurrentIndex(0);
- postCommand("-thread-info", CB(handleThreadInfo), 0);
+ postCommand("-thread-info", NoFlags, CB(handleThreadInfo));
reloadRegisters();
updateLocals();
}
-void GdbEngine::handleQuerySources(const GdbResponse &response)
+void GdbEngine::handleQuerySources(const DebuggerResponse &response)
{
m_sourcesListUpdating = false;
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
QMap<QString, QString> oldShortToFull = m_shortToFullName;
m_shortToFullName.clear();
m_fullToShortName.clear();
@@ -1286,13 +1266,13 @@ void GdbEngine::handleQuerySources(const GdbResponse &response)
}
}
-void GdbEngine::handleExecuteJumpToLine(const GdbResponse &response)
+void GdbEngine::handleExecuteJumpToLine(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultRunning) {
+ if (response.resultClass == ResultRunning) {
// All is fine. Waiting for a *running
// and the temporary breakpoint to be hit.
notifyInferiorRunOk(); // Only needed for gdb < 7.0.
- } else if (response.resultClass == GdbResultError) {
+ } else if (response.resultClass == ResultError) {
// Could be "Unreasonable jump request" or similar.
QString out = tr("Cannot jump. Stopped");
QByteArray msg = response.data["msg"].data();
@@ -1300,20 +1280,20 @@ void GdbEngine::handleExecuteJumpToLine(const GdbResponse &response)
out += QString::fromLatin1(". " + msg);
showStatusMessage(out);
notifyInferiorRunFailed();
- } else if (response.resultClass == GdbResultDone) {
+ } else if (response.resultClass == ResultDone) {
// This happens on old gdb. Trigger the effect of a '*stopped'.
showStatusMessage(tr("Jumped. Stopped"));
notifyInferiorSpontaneousStop();
- handleStop2(response);
+ handleStop2(response.data);
}
}
-void GdbEngine::handleExecuteRunToLine(const GdbResponse &response)
+void GdbEngine::handleExecuteRunToLine(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultRunning) {
+ if (response.resultClass == ResultRunning) {
// All is fine. Waiting for a *running
// and the temporary breakpoint to be hit.
- } else if (response.resultClass == GdbResultDone) {
+ } else if (response.resultClass == ResultDone) {
// This happens on old gdb (Mac). gdb is not stopped yet,
// but merely accepted the continue.
// >&"continue\n"
@@ -1382,7 +1362,7 @@ void GdbEngine::handleStopResponse(const GdbMi &data)
if (!m_fullStartDone) {
m_fullStartDone = true;
postCommand("sharedlibrary .*");
- postCommand("p 3", CB(handleStop1));
+ postCommand("p 3", NoFlags, [this, data](const DebuggerResponse &) { handleStop1(data); });
gotoHandleStop1 = false;
}
@@ -1391,8 +1371,10 @@ void GdbEngine::handleStopResponse(const GdbMi &data)
int lineNumber = 0;
QString fullName;
+ QByteArray function;
if (frame.isValid()) {
const GdbMi lineNumberG = frame["line"];
+ function = frame["func"].data();
if (lineNumberG.isValid()) {
lineNumber = lineNumberG.toInt();
fullName = cleanupFullName(QString::fromLocal8Bit(frame["fullname"].data()));
@@ -1403,31 +1385,28 @@ void GdbEngine::handleStopResponse(const GdbMi &data)
showMessage(_("INVALID STOPPED REASON"), LogWarning);
}
- if (rid.isValid() && frame.isValid()
- && !isQmlStepBreakpoint(rid)
- && !isQFatalBreakpoint(rid)) {
+ if (rid.isValid() && frame.isValid() && !isQFatalBreakpoint(rid)) {
// Use opportunity to update the breakpoint marker position.
- BreakHandler *handler = breakHandler();
//qDebug() << " PROBLEM: " << m_qmlBreakpointNumbers << rid
// << isQmlStepBreakpoint1(rid)
// << isQmlStepBreakpoint2(rid)
- BreakpointModelId id = handler->findBreakpointByResponseId(rid);
- const BreakpointResponse &response = handler->response(id);
+ Breakpoint bp = breakHandler()->findBreakpointByResponseId(rid);
+ const BreakpointResponse &response = bp.response();
QString fileName = response.fileName;
if (fileName.isEmpty())
- fileName = handler->fileName(id);
+ fileName = bp.fileName();
if (fileName.isEmpty())
fileName = fullName;
if (!fileName.isEmpty())
- handler->setMarkerFileAndLine(id, fileName, lineNumber);
+ bp.setMarkerFileAndLine(fileName, lineNumber);
}
//qDebug() << "BP " << rid << data.toString();
// Quickly set the location marker.
if (lineNumber && !boolSetting(OperateByInstruction)
&& QFileInfo::exists(fullName)
- && !isQmlStepBreakpoint(rid)
- && !isQFatalBreakpoint(rid))
+ && !isQFatalBreakpoint(rid)
+ && function != "qt_v4TriggeredBreakpointHook")
gotoLocation(Location(fullName, lineNumber));
if (!m_commandsToRunOnTemporaryBreak.isEmpty()) {
@@ -1469,9 +1448,6 @@ void GdbEngine::handleStopResponse(const GdbMi &data)
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- if (isQmlStepBreakpoint1(rid))
- return;
-
if (gotoHandleStop1)
handleStop1(data);
}
@@ -1481,11 +1457,6 @@ static QByteArray stopSignal(const Abi &abi)
return (abi.os() == Abi::WindowsOS) ? QByteArray("SIGTRAP") : QByteArray("SIGINT");
}
-void GdbEngine::handleStop1(const GdbResponse &response)
-{
- handleStop1(response.cookie.value<GdbMi>());
-}
-
void GdbEngine::handleStop1(const GdbMi &data)
{
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
@@ -1550,17 +1521,14 @@ void GdbEngine::handleStop1(const GdbMi &data)
if (!m_systemDumpersLoaded) {
m_systemDumpersLoaded = true;
if (m_gdbVersion >= 70400 && boolSetting(LoadGdbDumpers))
- postCommand("importPlainDumpers");
+ postCommand("importPlainDumpers on");
+ else
+ postCommand("importPlainDumpers off");
}
handleStop2(data);
}
-void GdbEngine::handleStop2(const GdbResponse &response)
-{
- handleStop2(response.cookie.value<GdbMi>());
-}
-
void GdbEngine::handleStop2(const GdbMi &data)
{
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
@@ -1628,14 +1596,13 @@ void GdbEngine::handleStop2(const GdbMi &data)
// thread-id="1",stopped-threads="all",core="2"
const GdbMi wpt = data["wpt"];
const BreakpointResponseId rid(wpt["number"].data());
- const BreakpointModelId id = breakHandler()->findBreakpointByResponseId(rid);
+ const Breakpoint bp = breakHandler()->findBreakpointByResponseId(rid);
const quint64 bpAddress = wpt["exp"].data().mid(1).toULongLong(0, 0);
QString msg;
- if (id && breakHandler()->type(id) == WatchpointAtExpression)
- msg = msgWatchpointByExpressionTriggered(id, rid.majorPart(),
- breakHandler()->expression(id));
- if (id && breakHandler()->type(id) == WatchpointAtAddress)
- msg = msgWatchpointByAddressTriggered(id, rid.majorPart(), bpAddress);
+ if (bp.type() == WatchpointAtExpression)
+ msg = bp.msgWatchpointByExpressionTriggered(rid.majorPart(), bp.expression());
+ if (bp.type() == WatchpointAtAddress)
+ msg = bp.msgWatchpointByAddressTriggered(rid.majorPart(), bpAddress);
GdbMi value = data["value"];
GdbMi oldValue = value["old"];
GdbMi newValue = value["new"];
@@ -1651,8 +1618,8 @@ void GdbEngine::handleStop2(const GdbMi &data)
gNumber = data["number"];
const BreakpointResponseId rid(gNumber.data());
const QByteArray threadId = data["thread-id"].data();
- const BreakpointModelId id = breakHandler()->findBreakpointByResponseId(rid);
- showStatusMessage(msgBreakpointTriggered(id, rid.majorPart(), _(threadId)));
+ const Breakpoint bp = breakHandler()->findBreakpointByResponseId(rid);
+ showStatusMessage(bp.msgBreakpointTriggered(rid.majorPart(), _(threadId)));
m_currentThread = threadId;
} else {
QString reasontr = msgStopped(_(reason));
@@ -1661,7 +1628,7 @@ void GdbEngine::handleStop2(const GdbMi &data)
QByteArray meaning = data["signal-meaning"].data();
// Ignore these as they are showing up regularly when
// stopping debugging.
- if (name == stopSignal(sp.toolChainAbi)) {
+ if (name == stopSignal(sp.toolChainAbi) || sp.expectedSignals.contains(name)) {
showMessage(_(name + " CONSIDERED HARMLESS. CONTINUING."));
} else {
showMessage(_("HANDLING SIGNAL " + name));
@@ -1692,9 +1659,9 @@ void GdbEngine::handleStop2()
postCommand("-thread-info", Discardable, CB(handleThreadInfo));
}
-void GdbEngine::handleInfoProc(const GdbResponse &response)
+void GdbEngine::handleInfoProc(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
static QRegExp re(_("\\bprocess ([0-9]+)\n"));
QTC_ASSERT(re.isValid(), return);
if (re.indexIn(_(response.consoleStreamOutput)) != -1)
@@ -1702,10 +1669,10 @@ void GdbEngine::handleInfoProc(const GdbResponse &response)
}
}
-void GdbEngine::handleShowVersion(const GdbResponse &response)
+void GdbEngine::handleShowVersion(const DebuggerResponse &response)
{
showMessage(_("PARSING VERSION: " + response.toString()));
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
bool isMacGdb = false;
int gdbBuildVersion = -1;
m_gdbVersion = 100;
@@ -1737,52 +1704,18 @@ void GdbEngine::handleShowVersion(const GdbResponse &response)
}
}
-void GdbEngine::handleListFeatures(const GdbResponse &response)
+void GdbEngine::handleListFeatures(const DebuggerResponse &response)
{
showMessage(_("FEATURES: " + response.toString()));
}
-void GdbEngine::handlePythonSetup(const GdbResponse &response)
+void GdbEngine::handlePythonSetup(const DebuggerResponse &response)
{
QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
- bool needSetup = false;
-
- const QString path = stringSetting(ExtraDumperFile);
- if (!path.isEmpty()) {
- QFileInfo fi(path);
- postCommand("python sys.path.insert(1, '" + fi.absolutePath().toUtf8() + "')");
- postCommand("python from " + fi.baseName().toUtf8() + " import *");
- needSetup = true;
- }
-
- const QString commands = stringSetting(ExtraDumperCommands);
- if (!commands.isEmpty()) {
- postCommand(commands.toLocal8Bit());
- needSetup = true;
- }
-
- if (needSetup)
- postCommand("bbsetup");
-
+ if (response.resultClass == ResultDone) {
GdbMi data;
data.fromStringMultiple(response.consoleStreamOutput);
- const GdbMi dumpers = data["dumpers"];
- foreach (const GdbMi &dumper, dumpers.children()) {
- QByteArray type = dumper["type"].data();
- QStringList formats(tr("Raw structure"));
- foreach (const QByteArray &format,
- dumper["formats"].data().split(',')) {
- if (format == "Normal")
- formats.append(tr("Normal"));
- else if (format == "Displayed")
- formats.append(tr("Displayed"));
- else if (!format.isEmpty())
- formats.append(_(format));
- }
- watchHandler()->addTypeFormats(type, formats);
- }
-
+ watchHandler()->addDumpers(data["dumpers"]);
loadInitScript();
QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
showMessage(_("ENGINE SUCCESSFULLY STARTED"));
@@ -1793,7 +1726,7 @@ void GdbEngine::handlePythonSetup(const GdbResponse &response)
QString out1 = _("The selected build of GDB does not support Python scripting.");
QString out2 = _("It cannot be used in Qt Creator.");
showStatusMessage(out1 + QLatin1Char(' ') + out2);
- showMessageBox(QMessageBox::Critical, tr("Execution Error"), out1 + _("<br>") + out2);
+ AsynchronousMessageBox::critical(tr("Execution Error"), out1 + _("<br>") + out2);
}
notifyEngineSetupFailed();
}
@@ -1801,14 +1734,14 @@ void GdbEngine::handlePythonSetup(const GdbResponse &response)
void GdbEngine::showExecutionError(const QString &message)
{
- showMessageBox(QMessageBox::Critical, tr("Execution Error"),
+ AsynchronousMessageBox::critical(tr("Execution Error"),
tr("Cannot continue debugged process:") + QLatin1Char('\n') + message);
}
-void GdbEngine::handleExecuteContinue(const GdbResponse &response)
+void GdbEngine::handleExecuteContinue(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorRunRequested, qDebug() << state());
- if (response.resultClass == GdbResultRunning) {
+ if (response.resultClass == ResultRunning) {
// All is fine. Waiting for a *running.
notifyInferiorRunOk(); // Only needed for gdb < 7.0.
return;
@@ -1822,7 +1755,7 @@ void GdbEngine::handleExecuteContinue(const GdbResponse &response)
flushQueuedCommands();
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
showStatusMessage(tr("Stopped."), 5000);
- reloadStack(true);
+ reloadStack();
} else if (msg.startsWith("Cannot access memory at address")) {
// Happens on single step on ARM prolog and epilogs.
} else if (msg.startsWith("\"finish\" not meaningful in the outermost frame")) {
@@ -1890,7 +1823,7 @@ QString GdbEngine::cleanupFullName(const QString &fileName)
}
cleanFilePath.clear();
- const QString base = QFileInfo(fileName).fileName();
+ const QString base = FileName::fromString(fileName).fileName();
QMap<QString, QString>::const_iterator jt = m_baseNameToFullName.find(base);
while (jt != m_baseNameToFullName.end() && jt.key() == base) {
@@ -1918,10 +1851,10 @@ void GdbEngine::shutdownInferior()
QTC_ASSERT(false, notifyInferiorShutdownFailed());
}
-void GdbEngine::handleInferiorShutdown(const GdbResponse &response)
+void GdbEngine::handleInferiorShutdown(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
notifyInferiorShutdownOk();
return;
}
@@ -1933,7 +1866,7 @@ void GdbEngine::handleInferiorShutdown(const GdbResponse &response)
notifyInferiorShutdownOk();
return;
}
- showMessageBox(QMessageBox::Critical,
+ AsynchronousMessageBox::critical(
tr("Failed to shut down application"),
msgInferiorStopFailed(QString::fromLocal8Bit(ba)));
notifyInferiorShutdownFailed();
@@ -1953,11 +1886,15 @@ void GdbEngine::notifyAdapterShutdownOk()
.arg(lastGoodState()).arg(m_gdbProc->state()));
m_commandsDoneCallback = 0;
switch (m_gdbProc->state()) {
- case QProcess::Running:
+ case QProcess::Running: {
if (startParameters().closeMode == KillAndExitMonitorAtClose)
postCommand("monitor exit");
- postCommand("-gdb-exit", GdbEngine::ExitRequest, CB(handleGdbExit));
+ DebuggerCommand cmd("exitGdb");
+ cmd.flags = GdbEngine::ExitRequest;
+ cmd.callback = CB(handleGdbExit);
+ runCommand(cmd);
break;
+ }
case QProcess::NotRunning:
// Cannot find executable.
notifyEngineShutdownOk();
@@ -1970,9 +1907,9 @@ void GdbEngine::notifyAdapterShutdownOk()
}
}
-void GdbEngine::handleGdbExit(const GdbResponse &response)
+void GdbEngine::handleGdbExit(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultExit) {
+ if (response.resultClass == ResultExit) {
showMessage(_("GDB CLAIMS EXIT; WAITING"));
// Don't set state here, this will be handled in handleGdbFinished()
//notifyEngineShutdownOk();
@@ -1993,7 +1930,7 @@ void GdbEngine::detachDebugger()
postCommand("detach", GdbEngine::ExitRequest, CB(handleDetach));
}
-void GdbEngine::handleDetach(const GdbResponse &response)
+void GdbEngine::handleDetach(const DebuggerResponse &response)
{
Q_UNUSED(response);
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
@@ -2054,6 +1991,7 @@ bool GdbEngine::hasCapability(unsigned cap) const
| WatchComplexExpressionsCapability
| MemoryAddressCapability
| AdditionalQmlStackCapability
+ | NativeMixedCapability
| ResetInferiorCapability))
return true;
@@ -2097,22 +2035,27 @@ void GdbEngine::executeStep()
setTokenBarrier();
notifyInferiorRunRequested();
showStatusMessage(tr("Step requested..."), 5000);
+ if (isNativeMixedActive()) {
+ runCommand("prepareQmlStep");
+ postCommand("-exec-continue", RunRequest, CB(handleExecuteContinue));
+ return;
+ }
if (isReverseDebugging())
postCommand("reverse-step", RunRequest, CB(handleExecuteStep));
else
postCommand("-exec-step", RunRequest, CB(handleExecuteStep));
}
-void GdbEngine::handleExecuteStep(const GdbResponse &response)
+void GdbEngine::handleExecuteStep(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// Step was finishing too quick, and a '*stopped' messages should
// have preceded it, so just ignore this result.
QTC_CHECK(state() == InferiorStopOk);
return;
}
QTC_ASSERT(state() == InferiorRunRequested, qDebug() << state());
- if (response.resultClass == GdbResultRunning) {
+ if (response.resultClass == ResultRunning) {
// All is fine. Waiting for a *running.
notifyInferiorRunOk(); // Only needed for gdb < 7.0.
return;
@@ -2169,6 +2112,11 @@ void GdbEngine::executeNext()
setTokenBarrier();
notifyInferiorRunRequested();
showStatusMessage(tr("Step next requested..."), 5000);
+ if (isNativeMixedActive()) {
+ runCommand("prepareQmlStep");
+ postCommand("-exec-continue", RunRequest, CB(handleExecuteContinue));
+ return;
+ }
if (isReverseDebugging()) {
postCommand("reverse-next", RunRequest, CB(handleExecuteNext));
} else {
@@ -2179,16 +2127,16 @@ void GdbEngine::executeNext()
}
}
-void GdbEngine::handleExecuteNext(const GdbResponse &response)
+void GdbEngine::handleExecuteNext(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// Step was finishing too quick, and a '*stopped' messages should
// have preceded it, so just ignore this result.
QTC_CHECK(state() == InferiorStopOk);
return;
}
QTC_ASSERT(state() == InferiorRunRequested, qDebug() << state());
- if (response.resultClass == GdbResultRunning) {
+ if (response.resultClass == ResultRunning) {
// All is fine. Waiting for a *running.
notifyInferiorRunOk(); // Only needed for gdb < 7.0.
return;
@@ -2206,7 +2154,7 @@ void GdbEngine::handleExecuteNext(const GdbResponse &response)
showExecutionError(QString::fromLocal8Bit(msg));
notifyInferiorRunFailed();
} else {
- showMessageBox(QMessageBox::Critical, tr("Execution Error"),
+ AsynchronousMessageBox::critical(tr("Execution Error"),
tr("Cannot continue debugged process:") + QLatin1Char('\n') + QString::fromLocal8Bit(msg));
notifyInferiorIll();
}
@@ -2293,9 +2241,9 @@ void GdbEngine::executeReturn()
postCommand("-exec-finish", RunRequest, CB(handleExecuteReturn));
}
-void GdbEngine::handleExecuteReturn(const GdbResponse &response)
+void GdbEngine::handleExecuteReturn(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
notifyInferiorStopOk();
updateAll();
return;
@@ -2315,14 +2263,12 @@ void GdbEngine::setTokenBarrier()
{
//QTC_ASSERT(m_nonDiscardableCount == 0, /**/);
bool good = true;
- QHashIterator<int, GdbCommand> it(m_cookieForToken);
+ QHashIterator<int, DebuggerCommand> it(m_commandForToken);
while (it.hasNext()) {
it.next();
if (!(it.value().flags & Discardable)) {
- qDebug() << "TOKEN: " << it.key()
- << "CMD:" << it.value().command
- << " FLAGS:" << it.value().flags
- << " CALLBACK:" << it.value().callbackName;
+ qDebug() << "TOKEN: " << it.key() << "CMD:" << it.value().function
+ << " FLAGS:" << it.value().flags;
good = false;
}
}
@@ -2457,14 +2403,12 @@ QString GdbEngine::breakLocation(const QString &file) const
{
QString where = m_fullToShortName.value(file);
if (where.isEmpty())
- return QFileInfo(file).fileName();
+ return FileName::fromString(file).fileName();
return where;
}
-QByteArray GdbEngine::breakpointLocation(BreakpointModelId id)
+QByteArray GdbEngine::breakpointLocation(const BreakpointParameters &data)
{
- BreakHandler *handler = breakHandler();
- const BreakpointParameters &data = handler->breakpointData(id);
QTC_ASSERT(data.type != UnknownBreakpointType, return QByteArray());
// FIXME: Non-GCC-runtime
if (data.type == BreakpointAtThrow)
@@ -2492,12 +2436,8 @@ QByteArray GdbEngine::breakpointLocation(BreakpointModelId id)
+ QByteArray::number(data.lineNumber) + '"';
}
-QByteArray GdbEngine::breakpointLocation2(BreakpointModelId id)
+QByteArray GdbEngine::breakpointLocation2(const BreakpointParameters &data)
{
- BreakHandler *handler = breakHandler();
-
- const BreakpointParameters &data = handler->breakpointData(id);
-
BreakpointPathUsage usage = data.pathUsage;
if (usage == BreakpointPathUsageEngineDefault)
usage = BreakpointUseShortPath;
@@ -2508,12 +2448,10 @@ QByteArray GdbEngine::breakpointLocation2(BreakpointModelId id)
+ QByteArray::number(data.lineNumber);
}
-void GdbEngine::handleWatchInsert(const GdbResponse &response)
+void GdbEngine::handleWatchInsert(const DebuggerResponse &response, Breakpoint bp)
{
- BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- if (response.resultClass == GdbResultDone) {
- BreakHandler *handler = breakHandler();
- BreakpointResponse br = handler->response(id);
+ if (bp && response.resultClass == ResultDone) {
+ BreakpointResponse br = bp.response();
// "Hardware watchpoint 2: *0xbfffed40\n"
QByteArray ba = response.consoleStreamOutput;
GdbMi wpt = response.data["wpt"];
@@ -2524,9 +2462,9 @@ void GdbEngine::handleWatchInsert(const GdbResponse &response)
QByteArray exp = wpt["exp"].data();
if (exp.startsWith('*'))
br.address = exp.mid(1).toULongLong(0, 0);
- handler->setResponse(id, br);
- QTC_CHECK(!handler->needsChange(id));
- handler->notifyBreakpointInsertOk(id);
+ bp.setResponse(br);
+ QTC_CHECK(!bp.needsChange());
+ bp.notifyBreakpointInsertOk();
} else if (ba.startsWith("Hardware watchpoint ")
|| ba.startsWith("Watchpoint ")) {
// Non-Mac: "Hardware watchpoint 2: *0xbfffed40\n"
@@ -2536,27 +2474,25 @@ void GdbEngine::handleWatchInsert(const GdbResponse &response)
br.id = BreakpointResponseId(ba.mid(begin, end - begin));
if (address.startsWith('*'))
br.address = address.mid(1).toULongLong(0, 0);
- handler->setResponse(id, br);
- QTC_CHECK(!handler->needsChange(id));
- handler->notifyBreakpointInsertOk(id);
+ bp.setResponse(br);
+ QTC_CHECK(!bp.needsChange());
+ bp.notifyBreakpointInsertOk();
} else {
showMessage(_("CANNOT PARSE WATCHPOINT FROM " + ba));
}
}
}
-void GdbEngine::handleCatchInsert(const GdbResponse &response)
+void GdbEngine::handleCatchInsert(const DebuggerResponse &response, Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- if (response.resultClass == GdbResultDone)
- handler->notifyBreakpointInsertOk(id);
+ if (bp && response.resultClass == ResultDone)
+ bp.notifyBreakpointInsertOk();
}
-void GdbEngine::handleBkpt(const GdbMi &bkpt, const BreakpointModelId &id)
+void GdbEngine::handleBkpt(const GdbMi &bkpt, Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- BreakpointResponse br = handler->response(id);
+ BreakpointResponse br = bp.response();
+ QTC_ASSERT(bp, return);
const QByteArray nr = bkpt["number"].data();
const BreakpointResponseId rid(nr);
QTC_ASSERT(rid.isValid(), return);
@@ -2565,8 +2501,8 @@ void GdbEngine::handleBkpt(const GdbMi &bkpt, const BreakpointModelId &id)
BreakpointResponse sub;
updateResponse(sub, bkpt);
sub.id = rid;
- sub.type = br.type;
- handler->insertSubBreakpoint(id, sub);
+ sub.type = bp.type();
+ bp.insertSubBreakpoint(sub);
return;
}
@@ -2582,33 +2518,31 @@ void GdbEngine::handleBkpt(const GdbMi &bkpt, const BreakpointModelId &id)
updateResponse(sub, loc);
sub.id = subrid;
sub.type = br.type;
- handler->insertSubBreakpoint(id, sub);
+ bp.insertSubBreakpoint(sub);
}
}
// A (the?) primary breakpoint.
updateResponse(br, bkpt);
br.id = rid;
- handler->setResponse(id, br);
+ bp.setResponse(br);
}
-void GdbEngine::handleBreakInsert1(const GdbResponse &response)
+void GdbEngine::handleBreakInsert1(const DebuggerResponse &response, Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- if (handler->state(id) == BreakpointRemoveRequested) {
- if (response.resultClass == GdbResultDone) {
+ if (bp.state() == BreakpointRemoveRequested) {
+ if (response.resultClass == ResultDone) {
// This delete was deferred. Act now.
const GdbMi mainbkpt = response.data["bkpt"];
- handler->notifyBreakpointRemoveProceeding(id);
+ bp.notifyBreakpointRemoveProceeding();
QByteArray nr = mainbkpt["number"].data();
postCommand("-break-delete " + nr,
NeedsStop | RebuildBreakpointModel);
- handler->notifyBreakpointRemoveOk(id);
+ bp.notifyBreakpointRemoveOk();
return;
}
}
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// The result is a list with the first entry marked "bkpt"
// and "unmarked" rest. The "bkpt" one seems to always be
// the "main" entry. Use the "main" entry to retrieve the
@@ -2619,19 +2553,19 @@ void GdbEngine::handleBreakInsert1(const GdbResponse &response)
const BreakpointResponseId mainrid(mainnr);
if (!isHiddenBreakpoint(mainrid)) {
foreach (const GdbMi &bkpt, response.data.children())
- handleBkpt(bkpt, id);
- if (handler->needsChange(id)) {
- handler->notifyBreakpointChangeAfterInsertNeeded(id);
- changeBreakpoint(id);
+ handleBkpt(bkpt, bp);
+ if (bp.needsChange()) {
+ bp.notifyBreakpointChangeAfterInsertNeeded();
+ changeBreakpoint(bp);
} else {
- handler->notifyBreakpointInsertOk(id);
+ bp.notifyBreakpointInsertOk();
}
}
} else if (response.data["msg"].data().contains("Unknown option")) {
// Older version of gdb don't know the -a option to set tracepoints
// ^error,msg="mi_cmd_break_insert: Unknown option ``a''"
- const QString fileName = handler->fileName(id);
- const int lineNumber = handler->lineNumber(id);
+ const QString fileName = bp.fileName();
+ const int lineNumber = bp.lineNumber();
QByteArray cmd = "trace "
"\"" + GdbMi::escapeCString(fileName.toLocal8Bit()) + "\":"
+ QByteArray::number(lineNumber);
@@ -2640,18 +2574,17 @@ void GdbEngine::handleBreakInsert1(const GdbResponse &response)
// Some versions of gdb like "GNU gdb (GDB) SUSE (6.8.91.20090930-2.4)"
// know how to do pending breakpoints using CLI but not MI. So try
// again with MI.
- QByteArray cmd = "break " + breakpointLocation2(id);
- QVariant vid = QVariant::fromValue(id);
+ QByteArray cmd = "break " + breakpointLocation2(bp.parameters());
postCommand(cmd, NeedsStop | RebuildBreakpointModel,
- CB(handleBreakInsert2), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakInsert2(r, bp); });
}
}
-void GdbEngine::handleBreakInsert2(const GdbResponse &response)
+void GdbEngine::handleBreakInsert2(const DebuggerResponse &response, Breakpoint bp)
{
- if (response.resultClass == GdbResultDone) {
- BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- breakHandler()->notifyBreakpointInsertOk(id);
+ if (response.resultClass == ResultDone) {
+ QTC_ASSERT(bp, return);
+ bp.notifyBreakpointInsertOk();
} else {
// Note: gdb < 60800 doesn't "do" pending breakpoints.
// Not much we can do about it except implementing the
@@ -2660,57 +2593,57 @@ void GdbEngine::handleBreakInsert2(const GdbResponse &response)
}
}
-void GdbEngine::handleBreakDisable(const GdbResponse &response)
+void GdbEngine::handleBreakDelete(const DebuggerResponse &response, Breakpoint bp)
{
- QTC_CHECK(response.resultClass == GdbResultDone);
- const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- BreakHandler *handler = breakHandler();
+ if (response.resultClass == ResultDone)
+ bp.notifyBreakpointRemoveOk();
+ else
+ bp.notifyBreakpointRemoveFailed();
+}
+
+void GdbEngine::handleBreakDisable(const DebuggerResponse &response, Breakpoint bp)
+{
+ QTC_CHECK(response.resultClass == ResultDone);
// This should only be the requested state.
- QTC_ASSERT(!handler->isEnabled(id), /* Prevent later recursion */);
- BreakpointResponse br = handler->response(id);
+ QTC_ASSERT(!bp.isEnabled(), /* Prevent later recursion */);
+ BreakpointResponse br = bp.response();
br.enabled = false;
- handler->setResponse(id, br);
- changeBreakpoint(id); // Maybe there's more to do.
+ bp.setResponse(br);
+ changeBreakpoint(bp); // Maybe there's more to do.
}
-void GdbEngine::handleBreakEnable(const GdbResponse &response)
+void GdbEngine::handleBreakEnable(const DebuggerResponse &response, Breakpoint bp)
{
- QTC_CHECK(response.resultClass == GdbResultDone);
- const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- BreakHandler *handler = breakHandler();
+ QTC_CHECK(response.resultClass == ResultDone);
// This should only be the requested state.
- QTC_ASSERT(handler->isEnabled(id), /* Prevent later recursion */);
- BreakpointResponse br = handler->response(id);
+ QTC_ASSERT(bp.isEnabled(), /* Prevent later recursion */);
+ BreakpointResponse br = bp.response();
br.enabled = true;
- handler->setResponse(id, br);
- changeBreakpoint(id); // Maybe there's more to do.
+ bp.setResponse(br);
+ changeBreakpoint(bp); // Maybe there's more to do.
}
-void GdbEngine::handleBreakThreadSpec(const GdbResponse &response)
+void GdbEngine::handleBreakThreadSpec(const DebuggerResponse &response, Breakpoint bp)
{
- QTC_CHECK(response.resultClass == GdbResultDone);
- const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- BreakHandler *handler = breakHandler();
- BreakpointResponse br = handler->response(id);
- br.threadSpec = handler->threadSpec(id);
- handler->setResponse(id, br);
- handler->notifyBreakpointNeedsReinsertion(id);
- insertBreakpoint(id);
+ QTC_CHECK(response.resultClass == ResultDone);
+ BreakpointResponse br = bp.response();
+ br.threadSpec = bp.threadSpec();
+ bp.setResponse(br);
+ bp.notifyBreakpointNeedsReinsertion();
+ insertBreakpoint(bp);
}
-void GdbEngine::handleBreakLineNumber(const GdbResponse &response)
+void GdbEngine::handleBreakLineNumber(const DebuggerResponse &response, Breakpoint bp)
{
- QTC_CHECK(response.resultClass == GdbResultDone);
- const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- BreakHandler *handler = breakHandler();
- BreakpointResponse br = handler->response(id);
- br.lineNumber = handler->lineNumber(id);
- handler->setResponse(id, br);
- handler->notifyBreakpointNeedsReinsertion(id);
- insertBreakpoint(id);
+ QTC_CHECK(response.resultClass == ResultDone);
+ BreakpointResponse br = bp.response();
+ br.lineNumber = bp.lineNumber();
+ bp.setResponse(br);
+ bp.notifyBreakpointNeedsReinsertion();
+ insertBreakpoint(bp);
}
-void GdbEngine::handleBreakIgnore(const GdbResponse &response)
+void GdbEngine::handleBreakIgnore(const DebuggerResponse &response, Breakpoint bp)
{
// gdb 6.8:
// ignore 2 0:
@@ -2722,39 +2655,35 @@ void GdbEngine::handleBreakIgnore(const GdbResponse &response)
// 29^done
//
// gdb 6.3 does not produce any console output
- QTC_CHECK(response.resultClass == GdbResultDone);
+ QTC_CHECK(response.resultClass == ResultDone);
//QString msg = _(response.consoleStreamOutput);
- BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- BreakHandler *handler = breakHandler();
- BreakpointResponse br = handler->response(id);
+ BreakpointResponse br = bp.response();
//if (msg.contains(__("Will stop next time breakpoint")))
// response.ignoreCount = _("0");
//else if (msg.contains(__("Will ignore next")))
// response.ignoreCount = data->ignoreCount;
// FIXME: this assumes it is doing the right thing...
- const BreakpointParameters &parameters = handler->breakpointData(id);
+ const BreakpointParameters &parameters = bp.parameters();
br.ignoreCount = parameters.ignoreCount;
br.command = parameters.command;
- handler->setResponse(id, br);
- changeBreakpoint(id); // Maybe there's more to do.
+ bp.setResponse(br);
+ changeBreakpoint(bp); // Maybe there's more to do.
}
-void GdbEngine::handleBreakCondition(const GdbResponse &response)
+void GdbEngine::handleBreakCondition(const DebuggerResponse &, Breakpoint bp)
{
// Can happen at invalid condition strings.
- //QTC_CHECK(response.resultClass == GdbResultDone)
- const BreakpointModelId id = response.cookie.value<BreakpointModelId>();
- BreakHandler *handler = breakHandler();
+ //QTC_CHECK(response.resultClass == ResultDone)
// We just assume it was successful. Otherwise we had to parse
// the output stream data.
// The following happens on Mac:
// QByteArray msg = response.data.findChild("msg").data();
// if (msg.startsWith("Error parsing breakpoint condition. "
// " Will try again when we hit the breakpoint."))
- BreakpointResponse br = handler->response(id);
- br.condition = handler->condition(id);
- handler->setResponse(id, br);
- changeBreakpoint(id); // Maybe there's more to do.
+ BreakpointResponse br = bp.response();
+ br.condition = bp.condition();
+ bp.setResponse(br);
+ changeBreakpoint(bp); // Maybe there's more to do.
}
bool GdbEngine::stateAcceptsBreakpointChanges() const
@@ -2771,40 +2700,53 @@ bool GdbEngine::stateAcceptsBreakpointChanges() const
}
}
-bool GdbEngine::acceptsBreakpoint(BreakpointModelId id) const
+bool GdbEngine::acceptsBreakpoint(Breakpoint bp) const
{
- return breakHandler()->breakpointData(id).isCppBreakpoint()
- && startParameters().startMode != AttachCore;
+ if (startParameters().startMode == AttachCore)
+ return false;
+ // We handle QML breakpoint unless specifically
+ if (isNativeMixedEnabled() && !(startParameters().languages & QmlLanguage))
+ return true;
+ return bp.parameters().isCppBreakpoint();
}
-void GdbEngine::insertBreakpoint(BreakpointModelId id)
+void GdbEngine::insertBreakpoint(Breakpoint bp)
{
// Set up fallback in case of pending breakpoints which aren't handled
// by the MI interface.
- BreakHandler *handler = breakHandler();
- QTC_CHECK(handler->state(id) == BreakpointInsertRequested);
- handler->notifyBreakpointInsertProceeding(id);
- BreakpointType type = handler->type(id);
- QVariant vid = QVariant::fromValue(id);
+ QTC_CHECK(bp.state() == BreakpointInsertRequested);
+ bp.notifyBreakpointInsertProceeding();
+
+ const BreakpointParameters &data = bp.parameters();
+
+ if (!data.isCppBreakpoint()) {
+ DebuggerCommand cmd("insertQmlBreakpoint");
+ bp.addToCommand(&cmd);
+ runCommand(cmd);
+ bp.notifyBreakpointInsertOk();
+ return;
+ }
+
+ BreakpointType type = bp.type();
if (type == WatchpointAtAddress) {
- postCommand("watch " + addressSpec(handler->address(id)),
+ postCommand("watch " + addressSpec(bp.address()),
NeedsStop | RebuildBreakpointModel | ConsoleCommand,
- CB(handleWatchInsert), vid);
+ [this, bp](const DebuggerResponse &r) { handleWatchInsert(r, bp); });
return;
}
if (type == WatchpointAtExpression) {
- postCommand("watch " + handler->expression(id).toLocal8Bit(),
+ postCommand("watch " + bp.expression().toLocal8Bit(),
NeedsStop | RebuildBreakpointModel | ConsoleCommand,
- CB(handleWatchInsert), vid);
+ [this, bp](const DebuggerResponse &r) { handleWatchInsert(r, bp); });
return;
}
if (type == BreakpointAtFork) {
postCommand("catch fork",
NeedsStop | RebuildBreakpointModel | ConsoleCommand,
- CB(handleCatchInsert), vid);
+ [this, bp](const DebuggerResponse &r) { handleCatchInsert(r, bp); });
postCommand("catch vfork",
NeedsStop | RebuildBreakpointModel | ConsoleCommand,
- CB(handleCatchInsert), vid);
+ [this, bp](const DebuggerResponse &r) { handleCatchInsert(r, bp); });
return;
}
//if (type == BreakpointAtVFork) {
@@ -2815,72 +2757,70 @@ void GdbEngine::insertBreakpoint(BreakpointModelId id)
if (type == BreakpointAtExec) {
postCommand("catch exec",
NeedsStop | RebuildBreakpointModel | ConsoleCommand,
- CB(handleCatchInsert), vid);
+ [this, bp](const DebuggerResponse &r) { handleCatchInsert(r, bp); });
return;
}
if (type == BreakpointAtSysCall) {
postCommand("catch syscall",
NeedsStop | RebuildBreakpointModel | ConsoleCommand,
- CB(handleCatchInsert), vid);
+ [this, bp](const DebuggerResponse &r) { handleCatchInsert(r, bp); });
return;
}
QByteArray cmd;
- if (handler->isTracepoint(id)) {
+ if (bp.isTracepoint()) {
cmd = "-break-insert -a -f ";
} else {
- int spec = handler->threadSpec(id);
+ int spec = bp.threadSpec();
cmd = "-break-insert ";
if (spec >= 0)
cmd += "-p " + QByteArray::number(spec);
cmd += " -f ";
}
- if (handler->isOneShot(id))
+ if (bp.isOneShot())
cmd += "-t ";
- if (!handler->isEnabled(id))
+ if (!bp.isEnabled())
cmd += "-d ";
- if (int ignoreCount = handler->ignoreCount(id))
+ if (int ignoreCount = bp.ignoreCount())
cmd += "-i " + QByteArray::number(ignoreCount) + ' ';
- QByteArray condition = handler->condition(id);
+ QByteArray condition = bp.condition();
if (!condition.isEmpty())
cmd += " -c \"" + condition + "\" ";
- cmd += breakpointLocation(id);
+ cmd += breakpointLocation(bp.parameters());
postCommand(cmd, NeedsStop | RebuildBreakpointModel,
- CB(handleBreakInsert1), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakInsert1(r, bp); });
}
-void GdbEngine::changeBreakpoint(BreakpointModelId id)
+void GdbEngine::changeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- const BreakpointParameters &data = handler->breakpointData(id);
+ const BreakpointParameters &data = bp.parameters();
QTC_ASSERT(data.type != UnknownBreakpointType, return);
- const BreakpointResponse &response = handler->response(id);
+ const BreakpointResponse &response = bp.response();
QTC_ASSERT(response.id.isValid(), return);
const QByteArray bpnr = response.id.toByteArray();
- const BreakpointState state = handler->state(id);
+ const BreakpointState state = bp.state();
if (state == BreakpointChangeRequested)
- handler->notifyBreakpointChangeProceeding(id);
- const BreakpointState state2 = handler->state(id);
+ bp.notifyBreakpointChangeProceeding();
+ const BreakpointState state2 = bp.state();
QTC_ASSERT(state2 == BreakpointChangeProceeding, qDebug() << state2);
- QVariant vid = QVariant::fromValue(id);
if (!response.pending && data.threadSpec != response.threadSpec) {
// The only way to change this seems to be to re-set the bp completely.
postCommand("-break-delete " + bpnr,
NeedsStop | RebuildBreakpointModel,
- CB(handleBreakThreadSpec), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakThreadSpec(r, bp); });
return;
}
if (!response.pending && data.lineNumber != response.lineNumber) {
// The only way to change this seems to be to re-set the bp completely.
postCommand("-break-delete " + bpnr,
NeedsStop | RebuildBreakpointModel,
- CB(handleBreakLineNumber), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakLineNumber(r, bp); });
return;
}
if (data.command != response.command) {
@@ -2893,51 +2833,57 @@ void GdbEngine::changeBreakpoint(BreakpointModelId id)
}
}
postCommand(breakCommand, NeedsStop | RebuildBreakpointModel,
- CB(handleBreakIgnore), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakIgnore(r, bp); });
return;
}
if (!data.conditionsMatch(response.condition)) {
postCommand("condition " + bpnr + ' ' + data.condition,
NeedsStop | RebuildBreakpointModel,
- CB(handleBreakCondition), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakCondition(r, bp); });
return;
}
if (data.ignoreCount != response.ignoreCount) {
postCommand("ignore " + bpnr + ' ' + QByteArray::number(data.ignoreCount),
NeedsStop | RebuildBreakpointModel,
- CB(handleBreakIgnore), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakIgnore(r, bp); });
return;
}
if (!data.enabled && response.enabled) {
postCommand("-break-disable " + bpnr,
NeedsStop | RebuildBreakpointModel,
- CB(handleBreakDisable), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakDisable(r, bp); });
return;
}
if (data.enabled && !response.enabled) {
postCommand("-break-enable " + bpnr,
NeedsStop | RebuildBreakpointModel,
- CB(handleBreakEnable), vid);
+ [this, bp](const DebuggerResponse &r) { handleBreakEnable(r, bp); });
return;
}
- handler->notifyBreakpointChangeOk(id);
+ bp.notifyBreakpointChangeOk();
}
-void GdbEngine::removeBreakpoint(BreakpointModelId id)
+void GdbEngine::removeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- QTC_CHECK(handler->state(id) == BreakpointRemoveRequested);
- BreakpointResponse br = handler->response(id);
+ QTC_CHECK(bp.state() == BreakpointRemoveRequested);
+ BreakpointResponse br = bp.response();
+
+ const BreakpointParameters &data = bp.parameters();
+ if (!data.isCppBreakpoint()) {
+ DebuggerCommand cmd("removeQmlBreakpoint");
+ bp.addToCommand(&cmd);
+ runCommand(cmd);
+ bp.notifyBreakpointRemoveOk();
+ return;
+ }
+
if (br.id.isValid()) {
// We already have a fully inserted breakpoint.
- handler->notifyBreakpointRemoveProceeding(id);
- showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString())
- .arg(handler->fileName(id)));
+ bp.notifyBreakpointRemoveProceeding();
+ showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString()).arg(bp.fileName()));
postCommand("-break-delete " + br.id.toByteArray(),
- NeedsStop | RebuildBreakpointModel);
- // Pretend it succeeds without waiting for response. Feels better.
- // FIXME: Really?
- handler->notifyBreakpointRemoveOk(id);
+ NeedsStop | RebuildBreakpointModel,
+ [this, bp](const DebuggerResponse &r) { handleBreakDelete(r, bp); });
} else {
// Breakpoint was scheduled to be inserted, but we haven't had
// an answer so far. Postpone activity by doing nothing.
@@ -2956,7 +2902,7 @@ void GdbEngine::loadSymbols(const QString &modulePath)
// FIXME: gdb does not understand quoted names here (tested with 6.8)
postCommand("sharedlibrary " + dotEscape(modulePath.toLocal8Bit()));
reloadModulesInternal();
- reloadStack(true);
+ reloadStack();
updateLocals();
}
@@ -2964,7 +2910,7 @@ void GdbEngine::loadAllSymbols()
{
postCommand("sharedlibrary .*");
reloadModulesInternal();
- reloadStack(true);
+ reloadStack();
updateLocals();
}
@@ -2987,30 +2933,15 @@ void GdbEngine::loadSymbolsForStack()
}
if (needUpdate) {
//reloadModulesInternal();
- reloadStack(true);
+ reloadStack();
updateLocals();
}
}
-void GdbEngine::requestModuleSymbols(const QString &modulePath)
+static void handleShowModuleSymbols(const DebuggerResponse &response,
+ const QString &modulePath, const QString &fileName)
{
- QTemporaryFile tf(QDir::tempPath() + _("/gdbsymbols"));
- if (!tf.open())
- return;
- QString fileName = tf.fileName();
- tf.close();
- postCommand("maint print msymbols \"" + fileName.toLocal8Bit()
- + "\" " + modulePath.toLocal8Bit(),
- NeedsStop, CB(handleShowModuleSymbols),
- QVariant(modulePath + QLatin1Char('@') + fileName));
-}
-
-void GdbEngine::handleShowModuleSymbols(const GdbResponse &response)
-{
- const QString cookie = response.cookie.toString();
- const QString modulePath = cookie.section(QLatin1Char('@'), 0, 0);
- const QString fileName = cookie.section(QLatin1Char('@'), 1, 1);
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
Symbols symbols;
QFile file(fileName);
file.open(QIODevice::ReadOnly);
@@ -3061,24 +2992,38 @@ void GdbEngine::handleShowModuleSymbols(const GdbResponse &response)
file.remove();
Internal::showModuleSymbols(modulePath, symbols);
} else {
- showMessageBox(QMessageBox::Critical, tr("Cannot Read Symbols"),
- tr("Cannot read symbols for module \"%1\".").arg(fileName));
+ AsynchronousMessageBox::critical(GdbEngine::tr("Cannot Read Symbols"),
+ GdbEngine::tr("Cannot read symbols for module \"%1\".").arg(fileName));
}
}
+void GdbEngine::requestModuleSymbols(const QString &modulePath)
+{
+ QTemporaryFile tf(QDir::tempPath() + _("/gdbsymbols"));
+ if (!tf.open())
+ return;
+ QString fileName = tf.fileName();
+ tf.close();
+ postCommand("maint print msymbols \"" + fileName.toLocal8Bit()
+ + "\" " + modulePath.toLocal8Bit(), NeedsStop,
+ [modulePath, fileName](const DebuggerResponse &r) {
+ handleShowModuleSymbols(r, modulePath, fileName); });
+}
+
void GdbEngine::requestModuleSections(const QString &moduleName)
{
// There seems to be no way to get the symbols from a single .so.
- postCommand("maint info section ALLOBJ",
- NeedsStop, CB(handleShowModuleSections), moduleName);
+ postCommand("maint info section ALLOBJ", NeedsStop,
+ [this, moduleName](const DebuggerResponse &r) {
+ handleShowModuleSections(r, moduleName); });
}
-void GdbEngine::handleShowModuleSections(const GdbResponse &response)
+void GdbEngine::handleShowModuleSections(const DebuggerResponse &response,
+ const QString &moduleName)
{
// ~" Object file: /usr/lib/i386-linux-gnu/libffi.so.6\n"
// ~" 0xb44a6114->0xb44a6138 at 0x00000114: .note.gnu.build-id ALLOC LOAD READONLY DATA HAS_CONTENTS\n"
- if (response.resultClass == GdbResultDone) {
- const QString moduleName = response.cookie.toString();
+ if (response.resultClass == ResultDone) {
const QStringList lines = QString::fromLocal8Bit(response.consoleStreamOutput).split(QLatin1Char('\n'));
const QString prefix = QLatin1String(" Object file: ");
const QString needle = prefix + moduleName;
@@ -3127,9 +3072,9 @@ static QString nameFromPath(const QString &path)
return QFileInfo(path).baseName();
}
-void GdbEngine::handleModulesList(const GdbResponse &response)
+void GdbEngine::handleModulesList(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
ModulesHandler *handler = modulesHandler();
Module module;
// That's console-based output, likely Linux or Windows,
@@ -3227,11 +3172,11 @@ void GdbEngine::selectThread(ThreadId threadId)
CB(handleStackSelectThread));
}
-void GdbEngine::handleStackSelectThread(const GdbResponse &)
+void GdbEngine::handleStackSelectThread(const DebuggerResponse &)
{
QTC_CHECK(state() == InferiorUnrunnable || state() == InferiorStopOk);
showStatusMessage(tr("Retrieving data for stack view..."), 3000);
- reloadStack(true); // Will reload registers.
+ reloadStack(); // Will reload registers.
updateLocals();
}
@@ -3239,8 +3184,10 @@ void GdbEngine::reloadFullStack()
{
PENDING_DEBUG("RELOAD FULL STACK");
resetLocation();
- postCommand("-stack-list-frames", Discardable, CB(handleStackListFrames),
- QVariant::fromValue<StackCookie>(StackCookie(true, true)));
+ DebuggerCommand cmd = stackCommand(-1);
+ cmd.flags = Discardable;
+ cmd.callback = [this](const DebuggerResponse &r) { handleStackListFrames(r, true); };
+ runCommand(cmd);
}
void GdbEngine::loadAdditionalQmlStack()
@@ -3277,7 +3224,7 @@ static QString msgCannotLoadQmlStack(const QString &why)
return _("Unable to load QML stack: ") + why;
}
-void GdbEngine::handleQmlStackFrameArguments(const GdbResponse &response)
+void GdbEngine::handleQmlStackFrameArguments(const DebuggerResponse &response)
{
if (!response.data.isValid()) {
showMessage(msgCannotLoadQmlStack(_("No stack obtained.")), LogError);
@@ -3292,10 +3239,10 @@ void GdbEngine::handleQmlStackFrameArguments(const GdbResponse &response)
QByteArray command = "-data-evaluate-expression \"qt_v4StackTrace((QV4::ExecutionContext *)0x";
command += QByteArray::number(contextAddress, 16);
command += ")\"";
- postCommand(command, CB(handleQmlStackTrace));
+ postCommand(command, NoFlags, CB(handleQmlStackTrace));
}
-void GdbEngine::handleQmlStackTrace(const GdbResponse &response)
+void GdbEngine::handleQmlStackTrace(const DebuggerResponse &response)
{
if (!response.data.isValid()) {
showMessage(msgCannotLoadQmlStack(_("No result obtained.")), LogError);
@@ -3327,15 +3274,21 @@ void GdbEngine::handleQmlStackTrace(const GdbResponse &response)
stackHandler()->prependFrames(qmlFrames);
}
-void GdbEngine::reloadStack(bool forceGotoLocation)
+DebuggerCommand GdbEngine::stackCommand(int depth)
+{
+ DebuggerCommand cmd("stackListFrames");
+ cmd.arg("limit", depth);
+ cmd.arg("options", isNativeMixedActive() ? "nativemixed" : "");
+ return cmd;
+}
+
+void GdbEngine::reloadStack()
{
PENDING_DEBUG("RELOAD STACK");
- QByteArray cmd = "-stack-list-frames";
- int stackDepth = action(MaximalStackDepth)->value().toInt();
- if (stackDepth)
- cmd += " 0 " + QByteArray::number(stackDepth);
- postCommand(cmd, Discardable, CB(handleStackListFrames),
- QVariant::fromValue<StackCookie>(StackCookie(false, forceGotoLocation)));
+ DebuggerCommand cmd = stackCommand(action(MaximalStackDepth)->value().toInt());
+ cmd.flags = Discardable;
+ cmd.callback = [this](const DebuggerResponse &r) { handleStackListFrames(r, false); };
+ runCommand(cmd);
}
StackFrame GdbEngine::parseStackFrame(const GdbMi &frameMi, int level)
@@ -3352,15 +3305,24 @@ StackFrame GdbEngine::parseStackFrame(const GdbMi &frameMi, int level)
frame.from = _(frameMi["from"].data());
frame.line = frameMi["line"].toInt();
frame.address = frameMi["addr"].toAddress();
- frame.usable = QFileInfo(frame.file).isReadable();
- if (frameMi["language"].data() == "js")
+ GdbMi usable = frameMi["usable"];
+ if (usable.isValid())
+ frame.usable = usable.data().toInt();
+ else
+ frame.usable = QFileInfo(frame.file).isReadable();
+ if (frameMi["language"].data() == "js"
+ || frame.file.endsWith(QLatin1String(".js"))
+ || frame.file.endsWith(QLatin1String(".qml"))) {
+ frame.file = QFile::decodeName(frameMi["file"].data());
frame.language = QmlLanguage;
+ frame.fixQmlFrame(startParameters());
+ }
return frame;
}
-void GdbEngine::handleStackListFrames(const GdbResponse &response)
+void GdbEngine::handleStackListFrames(const DebuggerResponse &response, bool isFull)
{
- if (response.resultClass != GdbResultDone) {
+ if (response.resultClass != ResultDone) {
// That always happens on symbian gdb with
// ^error,data={msg="Previous frame identical to this frame (corrupt stack?)"
// logStreamOutput: "Previous frame identical to this frame (corrupt stack?)\n"
@@ -3369,10 +3331,12 @@ void GdbEngine::handleStackListFrames(const GdbResponse &response)
return;
}
- StackCookie cookie = response.cookie.value<StackCookie>();
QList<StackFrame> stackFrames;
- GdbMi stack = response.data["stack"];
+ GdbMi stack = response.data["stack"]; // C++
+ if (!stack.isValid() || stack.childCount() == 0) // Mixed.
+ stack.fromStringMultiple(response.consoleStreamOutput);
+
if (!stack.isValid()) {
qDebug() << "FIXME: stack:" << stack.toString();
return;
@@ -3391,8 +3355,7 @@ void GdbEngine::handleStackListFrames(const GdbResponse &response)
targetFrame = i;
}
- bool canExpand = !cookie.isFull
- && (n >= action(MaximalStackDepth)->value().toInt());
+ bool canExpand = !isFull && (n >= action(MaximalStackDepth)->value().toInt());
action(ExpandStack)->setEnabled(canExpand);
stackHandler()->setFrames(stackFrames, canExpand);
@@ -3429,34 +3392,28 @@ void GdbEngine::activateFrame(int frameIndex)
}
QTC_ASSERT(frameIndex < handler->stackSize(), return);
-
- if (handler->frameAt(frameIndex).language == QmlLanguage) {
- gotoLocation(handler->frameAt(frameIndex));
- return;
- }
- // Assuming the command always succeeds this saves a roundtrip.
- // Otherwise the lines below would need to get triggered
- // after a response to this -stack-select-frame here.
handler->setCurrentIndex(frameIndex);
- QByteArray cmd = "-stack-select-frame";
- //if (!m_currentThread.isEmpty())
- // cmd += " --thread " + m_currentThread;
- cmd += ' ';
- cmd += QByteArray::number(frameIndex);
- postCommand(cmd, Discardable, CB(handleStackSelectFrame));
gotoLocation(stackHandler()->currentFrame());
+
+ if (handler->frameAt(frameIndex).language != QmlLanguage) {
+ // Assuming the command always succeeds this saves a roundtrip.
+ // Otherwise the lines below would need to get triggered
+ // after a response to this -stack-select-frame here.
+ QByteArray cmd = "-stack-select-frame";
+ //if (!m_currentThread.isEmpty())
+ // cmd += " --thread " + m_currentThread;
+ cmd += ' ';
+ cmd += QByteArray::number(frameIndex);
+ postCommand(cmd, Discardable);
+ }
+
updateLocals();
reloadRegisters();
}
-void GdbEngine::handleStackSelectFrame(const GdbResponse &response)
+void GdbEngine::handleThreadInfo(const DebuggerResponse &response)
{
- Q_UNUSED(response);
-}
-
-void GdbEngine::handleThreadInfo(const GdbResponse &response)
-{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
ThreadsHandler *handler = threadsHandler();
handler->updateThreads(response.data);
// This is necessary as the current thread might not be in the list.
@@ -3471,7 +3428,7 @@ void GdbEngine::handleThreadInfo(const GdbResponse &response)
action(MaximalStackDepth)->value().toByteArray(),
Discardable, CB(handleThreadNames));
}
- reloadStack(false); // Will trigger register reload.
+ reloadStack(); // Will trigger register reload.
} else {
// Fall back for older versions: Try to get at least a list
// of running threads.
@@ -3479,7 +3436,7 @@ void GdbEngine::handleThreadInfo(const GdbResponse &response)
}
}
-void GdbEngine::handleThreadListIds(const GdbResponse &response)
+void GdbEngine::handleThreadListIds(const DebuggerResponse &response)
{
// "72^done,{thread-ids={thread-id="2",thread-id="1"},number-of-threads="2"}
// In gdb 7.1+ additionally: current-thread-id="1"
@@ -3490,12 +3447,12 @@ void GdbEngine::handleThreadListIds(const GdbResponse &response)
thread.id = ThreadId(items.at(index).toInt());
handler->updateThread(thread);
}
- reloadStack(false); // Will trigger register reload.
+ reloadStack(); // Will trigger register reload.
}
-void GdbEngine::handleThreadNames(const GdbResponse &response)
+void GdbEngine::handleThreadNames(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
ThreadsHandler *handler = threadsHandler();
GdbMi names;
names.fromString(response.consoleStreamOutput);
@@ -3525,20 +3482,20 @@ void GdbEngine::createSnapshot()
fileName = tf.fileName();
tf.close();
// This must not be quoted, it doesn't work otherwise.
- postCommand("gcore " + fileName.toLocal8Bit(),
- NeedsStop|ConsoleCommand, CB(handleMakeSnapshot), fileName);
+ postCommand("gcore " + fileName.toLocal8Bit(), NeedsStop|ConsoleCommand,
+ [this, fileName](const DebuggerResponse &r) { handleMakeSnapshot(r, fileName); });
} else {
- showMessageBox(QMessageBox::Critical, tr("Snapshot Creation Error"),
+ AsynchronousMessageBox::critical(tr("Snapshot Creation Error"),
tr("Cannot create snapshot file."));
}
}
-void GdbEngine::handleMakeSnapshot(const GdbResponse &response)
+void GdbEngine::handleMakeSnapshot(const DebuggerResponse &response, const QString &coreFile)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
DebuggerStartParameters sp = startParameters();
sp.startMode = AttachCore;
- sp.coreFile = response.cookie.toString();
+ sp.coreFile = coreFile;
//snapshot.setDate(QDateTime::currentDateTime());
StackFrames frames = stackHandler()->frames();
QString function = _("<unknown>");
@@ -3551,7 +3508,7 @@ void GdbEngine::handleMakeSnapshot(const GdbResponse &response)
DebuggerRunControlFactory::createAndScheduleRun(sp);
} else {
QByteArray msg = response.data["msg"].data();
- showMessageBox(QMessageBox::Critical, tr("Snapshot Creation Error"),
+ AsynchronousMessageBox::critical(tr("Snapshot Creation Error"),
tr("Cannot create snapshot:") + QLatin1Char('\n') + QString::fromLocal8Bit(msg));
}
}
@@ -3570,69 +3527,144 @@ void GdbEngine::reloadRegisters()
if (state() != InferiorStopOk && state() != InferiorUnrunnable)
return;
- if (!m_registerNamesListed) {
- postCommand("-data-list-register-names", CB(handleRegisterListNames));
- m_registerNamesListed = true;
+
+ if (true) {
+ if (!m_registerNamesListed) {
+ postCommand("-data-list-register-names", NoFlags, CB(handleRegisterListNames));
+ m_registerNamesListed = true;
+ }
+ // Can cause i386-linux-nat.c:571: internal-error: Got request
+ // for bad register number 41.\nA problem internal to GDB has been detected.
+ postCommand("-data-list-register-values r",
+ Discardable, CB(handleRegisterListValues));
+ } else {
+ postCommand("maintenance print cooked-registers", NoFlags, CB(handleMaintPrintRegisters));
}
+}
- postCommand("-data-list-register-values r",
- Discardable, CB(handleRegisterListValues));
+static QByteArray readWord(const QByteArray &ba, int *pos)
+{
+ const int n = ba.size();
+ while (*pos < n && ba.at(*pos) == ' ')
+ ++*pos;
+ const int start = *pos;
+ while (*pos < n && ba.at(*pos) != ' ' && ba.at(*pos) != '\n')
+ ++*pos;
+ return ba.mid(start, *pos - start);
}
-void GdbEngine::setRegisterValue(int nr, const QString &value)
+void GdbEngine::handleMaintPrintRegisters(const DebuggerResponse &response)
{
- Register reg = registerHandler()->registers().at(nr);
- postCommand("set $" + reg.name + "=" + value.toLatin1());
+ if (response.resultClass != ResultDone)
+ return;
+
+ const QByteArray &ba = response.consoleStreamOutput;
+ RegisterHandler *handler = registerHandler();
+ //0 1 2 3 4 5 6
+ //0123456789012345678901234567890123456789012345678901234567890
+ // Name Nr Rel Offset Size Type Raw value
+ // rax 0 0 0 8 int64_t 0x0000000000000000
+ // rip 16 16 128 8 *1 0x0000000000400dc9
+ // eflags 17 17 136 4 i386_eflags 0x00000246
+ // cs 18 18 140 4 int32_t 0x00000033
+ // xmm15 55 55 516 16 vec128 0x00000000000000000000000000000000
+ // mxcsr 56 56 532 4 i386_mxcsr 0x00001fa0
+ // ''
+ // st6 30 30 224 10 _i387_ext 0x00000000000000000000
+ // st7 31 31 234 10 _i387_ext 0x00000000000000000000
+ // fctrl 32 32 244 4 int 0x0000037f
+
+ const int n = ba.size();
+ int pos = 0;
+ while (true) {
+ // Skip first line, and until '\n' after each line finished.
+ while (pos < n && ba.at(pos) != '\n')
+ ++pos;
+ if (pos >= n)
+ break;
+ ++pos; // skip \n
+ Register reg;
+ reg.name = readWord(ba, &pos);
+ if (reg.name == "''" || reg.name == "*1:" || reg.name.isEmpty())
+ continue;
+ readWord(ba, &pos); // Nr
+ readWord(ba, &pos); // Rel
+ readWord(ba, &pos); // Offset
+ reg.size = readWord(ba, &pos).toInt();
+ reg.reportedType = readWord(ba, &pos);
+ reg.value = readWord(ba, &pos);
+ handler->updateRegister(reg);
+ }
+ handler->commitUpdates();
+}
+void GdbEngine::setRegisterValue(const QByteArray &name, const QString &value)
+{
+ postCommand("set $" + name + "=" + value.toLatin1());
reloadRegisters();
}
-void GdbEngine::handleRegisterListNames(const GdbResponse &response)
+void GdbEngine::handleRegisterListNames(const DebuggerResponse &response)
{
- if (response.resultClass != GdbResultDone) {
+ if (response.resultClass != ResultDone) {
m_registerNamesListed = false;
return;
}
- Registers registers;
- int gdbRegisterNumber = 0, internalIndex = 0;
-
- // This both handles explicitly having space for all the registers and
- // initializes all indices to 0, giving missing registers a sane default
- // in the event of something wacky.
GdbMi names = response.data["register-names"];
- m_registerNumbers.resize(names.childCount());
+ m_registerNames.clear();
+ int gdbRegisterNumber = 0;
foreach (const GdbMi &item, names.children()) {
- // Since we throw away missing registers to eliminate empty rows
- // we need to maintain a mapping of GDB register numbers to their
- // respective indices in the register list.
- if (!item.data().isEmpty()) {
- m_registerNumbers[gdbRegisterNumber] = internalIndex++;
- registers.append(Register(item.data()));
- }
- gdbRegisterNumber++;
+ if (!item.data().isEmpty())
+ m_registerNames[gdbRegisterNumber] = item.data();
+ ++gdbRegisterNumber;
}
-
- registerHandler()->setRegisters(registers);
}
-void GdbEngine::handleRegisterListValues(const GdbResponse &response)
+void GdbEngine::handleRegisterListValues(const DebuggerResponse &response)
{
- if (response.resultClass != GdbResultDone)
+ if (response.resultClass != ResultDone)
return;
- Registers registers = registerHandler()->registers();
- const int registerCount = registers.size();
- const int gdbRegisterCount = m_registerNumbers.size();
-
+ RegisterHandler *handler = registerHandler();
// 24^done,register-values=[{number="0",value="0xf423f"},...]
const GdbMi values = response.data["register-values"];
- QTC_ASSERT(registerCount == values.children().size(), return);
foreach (const GdbMi &item, values.children()) {
+ Register reg;
const int number = item["number"].toInt();
- if (number >= 0 && number < gdbRegisterCount)
- registers[m_registerNumbers[number]].value = item["value"].data();
+ reg.name = m_registerNames[number];
+ QByteArray data = item["value"].data();
+ if (data.startsWith("0x")) {
+ reg.value = data;
+ } else {
+ // This is what GDB considers machine readable output:
+ // value="{v4_float = {0x00000000, 0x00000000, 0x00000000, 0x00000000},
+ // v2_double = {0x0000000000000000, 0x0000000000000000},
+ // v16_int8 = {0x00 <repeats 16 times>},
+ // v8_int16 = {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000},
+ // v4_int32 = {0x00000000, 0x00000000, 0x00000000, 0x00000000},
+ // v2_int64 = {0x0000000000000000, 0x0000000000000000},
+ // uint128 = <error reading variable>}"}
+ // Try to make sense of it using the int32 chunks:
+ QByteArray result = "0x";
+ const int pos1 = data.indexOf("_int32");
+ const int pos2 = data.indexOf('{', pos1) + 1;
+ const int pos3 = data.indexOf('}', pos2);
+ QByteArray inner = data.mid(pos2, pos3 - pos2);
+ QList<QByteArray> list = inner.split(',');
+ for (int i = list.size(); --i >= 0; ) {
+ QByteArray chunk = list.at(i);
+ if (chunk.startsWith(' '))
+ chunk.remove(0, 1);
+ if (chunk.startsWith("0x"))
+ chunk.remove(0, 2);
+ QTC_ASSERT(chunk.size() == 8, continue);
+ result.append(chunk);
+ }
+ reg.value = result;
+ }
+ handler->updateRegister(reg);
}
- registerHandler()->setAndMarkRegisters(registers);
+ handler->commitUpdates();
}
@@ -3650,8 +3682,6 @@ bool GdbEngine::setToolTipExpression(TextEditor::TextEditorWidget *editor,
UpdateParameters params;
params.tryPartial = true;
- params.tooltipOnly = true;
- params.tooltipExpression = context.expression;
params.varList = context.iname;
updateLocalsPython(params);
return true;
@@ -3699,9 +3729,7 @@ void GdbEngine::updateWatchData(const WatchData &data, const WatchUpdateFlags &f
// << (m_pendingBreakpointRequests == 0);
UpdateParameters params;
- params.tooltipOnly = data.iname.startsWith("tooltip");
- params.tryPartial = flags.tryIncremental
- && m_pendingBreakpointRequests == 0;
+ params.tryPartial = flags.tryIncremental && m_pendingBreakpointRequests == 0;
params.varList = data.iname;
updateLocalsPython(params);
@@ -3722,7 +3750,7 @@ void GdbEngine::rebuildWatchModel()
DebuggerToolTipManager::updateEngine(this);
}
-void GdbEngine::handleVarAssign(const GdbResponse &)
+void GdbEngine::handleVarAssign(const DebuggerResponse &)
{
// Everything might have changed, force re-evaluation.
setTokenBarrier();
@@ -3757,17 +3785,13 @@ void GdbEngine::insertData(const WatchData &data)
void GdbEngine::assignValueInDebugger(const WatchData *data,
const QString &expression, const QVariant &value)
{
- if (!isIntOrFloatType(data->type)) {
- QByteArray cmd = "bbedit "
- + data->type.toHex() + ','
- + expression.toUtf8().toHex() + ','
- + value.toString().toUtf8().toHex();
- postCommand(cmd, Discardable, CB(handleVarAssign));
- } else {
- postCommand("set variable (" + expression.toLatin1() + ")="
- + GdbMi::escapeCString(value.toString().toLatin1()),
- Discardable, CB(handleVarAssign));
- }
+ DebuggerCommand cmd("assignValue");
+ cmd.arg("type", data->type.toHex());
+ cmd.arg("expr", expression.toLatin1().toHex());
+ cmd.arg("value", value.toString().toLatin1().toHex());
+ cmd.arg("simpleType", isIntOrFloatType(data->type));
+ cmd.callback = CB(handleVarAssign);
+ runCommand(cmd);
}
void GdbEngine::watchPoint(const QPoint &pnt)
@@ -3779,9 +3803,9 @@ void GdbEngine::watchPoint(const QPoint &pnt)
NeedsStop, CB(handleWatchPoint));
}
-void GdbEngine::handleWatchPoint(const GdbResponse &response)
+void GdbEngine::handleWatchPoint(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// "$5 = (void *) 0xbfa7ebfc\n"
const QByteArray ba = parsePlainConsoleStream(response);
const int pos0x = ba.indexOf("0x");
@@ -3832,10 +3856,10 @@ void GdbEngine::changeMemory(MemoryAgent *agent, QObject *token,
ac.token = token;
ac.base = addr;
ac.length = data.size();
- postCommand(cmd, NeedsStop, CB(handleChangeMemory), QVariant::fromValue(ac));
+ postCommand(cmd, NeedsStop, CB(handleChangeMemory));
}
-void GdbEngine::handleChangeMemory(const GdbResponse &response)
+void GdbEngine::handleChangeMemory(const DebuggerResponse &response)
{
Q_UNUSED(response);
}
@@ -3856,21 +3880,20 @@ void GdbEngine::fetchMemory(MemoryAgent *agent, QObject *token, quint64 addr,
void GdbEngine::fetchMemoryHelper(const MemoryAgentCookie &ac)
{
postCommand("-data-read-memory 0x" + QByteArray::number(ac.base + ac.offset, 16) + " x 1 1 "
- + QByteArray::number(ac.length),
- NeedsStop, CB(handleFetchMemory), QVariant::fromValue(ac));
+ + QByteArray::number(ac.length), NeedsStop,
+ [this, ac](const DebuggerResponse &r) { handleFetchMemory(r, ac); });
}
-void GdbEngine::handleFetchMemory(const GdbResponse &response)
+void GdbEngine::handleFetchMemory(const DebuggerResponse &response, MemoryAgentCookie ac)
{
// ^done,addr="0x08910c88",nr-bytes="16",total-bytes="16",
// next-row="0x08910c98",prev-row="0x08910c78",next-page="0x08910c98",
// prev-page="0x08910c78",memory=[{addr="0x08910c88",
// data=["1","0","0","0","5","0","0","0","0","0","0","0","0","0","0","0"]}]
- MemoryAgentCookie ac = response.cookie.value<MemoryAgentCookie>();
--*ac.pendingRequests;
showMessage(QString::fromLatin1("PENDING: %1").arg(*ac.pendingRequests));
QTC_ASSERT(ac.agent, return);
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
GdbMi memory = response.data["memory"];
QTC_ASSERT(memory.children().size() <= 1, return);
if (memory.children().isEmpty())
@@ -3946,25 +3969,34 @@ static inline QByteArray disassemblerCommand(const Location &location, bool mixe
return command;
}
-void GdbEngine::fetchDisassemblerByCliPointMixed(const DisassemblerAgentCookie &ac0)
+void GdbEngine::fetchDisassemblerByCliPointMixed(const DisassemblerAgentCookie &ac)
{
- DisassemblerAgentCookie ac = ac0;
QTC_ASSERT(ac.agent, return);
postCommand(disassemblerCommand(ac.agent->location(), true), Discardable|ConsoleCommand,
- CB(handleFetchDisassemblerByCliPointMixed),
- QVariant::fromValue(ac));
+ [this, ac](const DebuggerResponse &response) {
+ if (response.resultClass == ResultDone)
+ if (handleCliDisassemblerResult(response.consoleStreamOutput, ac.agent))
+ return;
+ // 'point, plain' can take far too long.
+ // Skip this feature and immediately fall back to the 'range' version:
+ fetchDisassemblerByCliRangeMixed(ac);
+ });
}
-void GdbEngine::fetchDisassemblerByCliRangeMixed(const DisassemblerAgentCookie &ac0)
+void GdbEngine::fetchDisassemblerByCliRangeMixed(const DisassemblerAgentCookie &ac)
{
- DisassemblerAgentCookie ac = ac0;
QTC_ASSERT(ac.agent, return);
const quint64 address = ac.agent->address();
QByteArray start = QByteArray::number(address - 20, 16);
QByteArray end = QByteArray::number(address + 100, 16);
QByteArray cmd = "disassemble /rm 0x" + start + ",0x" + end;
postCommand(cmd, Discardable|ConsoleCommand,
- CB(handleFetchDisassemblerByCliRangeMixed), QVariant::fromValue(ac));
+ [this, ac](const DebuggerResponse &response) {
+ if (response.resultClass == ResultDone)
+ if (handleCliDisassemblerResult(response.consoleStreamOutput, ac.agent))
+ return;
+ fetchDisassemblerByCliRangePlain(ac);
+ });
}
@@ -3977,7 +4009,18 @@ void GdbEngine::fetchDisassemblerByCliRangePlain(const DisassemblerAgentCookie &
QByteArray end = QByteArray::number(address + 100, 16);
QByteArray cmd = "disassemble /r 0x" + start + ",0x" + end;
postCommand(cmd, Discardable,
- CB(handleFetchDisassemblerByCliRangePlain), QVariant::fromValue(ac));
+ [this, ac](const DebuggerResponse &response) {
+ if (response.resultClass == ResultDone)
+ if (handleCliDisassemblerResult(response.consoleStreamOutput, ac.agent))
+ return;
+ // Finally, give up.
+ //76^error,msg="No function contains program counter for selected..."
+ //76^error,msg="No function contains specified address."
+ //>568^error,msg="Line number 0 out of range;
+ QByteArray msg = response.data["msg"].data();
+ showStatusMessage(tr("Disassembler failed: %1")
+ .arg(QString::fromLocal8Bit(msg)), 5000);
+ });
}
struct LineData
@@ -3990,6 +4033,7 @@ struct LineData
bool GdbEngine::handleCliDisassemblerResult(const QByteArray &output, DisassemblerAgent *agent)
{
+ QTC_ASSERT(agent, return true);
// First line is something like
// "Dump of assembler code from 0xb7ff598f to 0xb7ff5a07:"
DisassemblerLines dlines;
@@ -4033,50 +4077,6 @@ bool GdbEngine::handleCliDisassemblerResult(const QByteArray &output, Disassembl
return false;
}
-void GdbEngine::handleFetchDisassemblerByCliPointMixed(const GdbResponse &response)
-{
- DisassemblerAgentCookie ac = response.cookie.value<DisassemblerAgentCookie>();
- QTC_ASSERT(ac.agent, return);
-
- if (response.resultClass == GdbResultDone)
- if (handleCliDisassemblerResult(response.consoleStreamOutput, ac.agent))
- return;
-
- // 'point, plain' can take far too long.
- // Skip this feature and immediately fall back to the 'range' version:
- fetchDisassemblerByCliRangeMixed(ac);
-}
-
-void GdbEngine::handleFetchDisassemblerByCliRangeMixed(const GdbResponse &response)
-{
- DisassemblerAgentCookie ac = response.cookie.value<DisassemblerAgentCookie>();
- QTC_ASSERT(ac.agent, return);
-
- if (response.resultClass == GdbResultDone)
- if (handleCliDisassemblerResult(response.consoleStreamOutput, ac.agent))
- return;
-
- fetchDisassemblerByCliRangePlain(ac);
-}
-
-void GdbEngine::handleFetchDisassemblerByCliRangePlain(const GdbResponse &response)
-{
- DisassemblerAgentCookie ac = response.cookie.value<DisassemblerAgentCookie>();
- QTC_ASSERT(ac.agent, return);
-
- if (response.resultClass == GdbResultDone)
- if (handleCliDisassemblerResult(response.consoleStreamOutput, ac.agent))
- return;
-
- // Finally, give up.
- //76^error,msg="No function contains program counter for selected..."
- //76^error,msg="No function contains specified address."
- //>568^error,msg="Line number 0 out of range;
- QByteArray msg = response.data["msg"].data();
- showStatusMessage(tr("Disassembler failed: %1")
- .arg(QString::fromLocal8Bit(msg)), 5000);
-}
-
// Binary/configuration check logic.
static QString gdbBinary(const DebuggerStartParameters &sp)
@@ -4129,14 +4129,10 @@ void GdbEngine::startGdb(const QStringList &args)
gdbArgs << _("-n");
gdbArgs += args;
- connect(m_gdbProc, SIGNAL(error(QProcess::ProcessError)),
- SLOT(handleGdbError(QProcess::ProcessError)));
- connect(m_gdbProc, SIGNAL(finished(int,QProcess::ExitStatus)),
- SLOT(handleGdbFinished(int,QProcess::ExitStatus)));
- connect(m_gdbProc, SIGNAL(readyReadStandardOutput()),
- SLOT(readGdbStandardOutput()));
- connect(m_gdbProc, SIGNAL(readyReadStandardError()),
- SLOT(readGdbStandardError()));
+ connect(m_gdbProc, &GdbProcess::error, this, &GdbEngine::handleGdbError);
+ connect(m_gdbProc, &GdbProcess::finished, this, &GdbEngine::handleGdbFinished);
+ connect(m_gdbProc, &GdbProcess::readyReadStandardOutput, this, &GdbEngine::readGdbStandardOutput);
+ connect(m_gdbProc, &GdbProcess::readyReadStandardError, this, &GdbEngine::readGdbStandardError);
showMessage(_("STARTING ") + m_gdb + _(" ") + gdbArgs.join(QLatin1Char(' ')));
m_gdbProc->start(m_gdb, gdbArgs);
@@ -4149,9 +4145,9 @@ void GdbEngine::startGdb(const QStringList &args)
}
showMessage(_("GDB STARTED, INITIALIZING IT"));
- postCommand("show version", CB(handleShowVersion));
+ postCommand("show version", NoFlags, CB(handleShowVersion));
//postCommand("-list-features", CB(handleListFeatures));
- postCommand("show debug-file-directory", CB(handleDebugInfoLocation));
+ postCommand("show debug-file-directory", NoFlags, CB(handleDebugInfoLocation));
//postCommand("-enable-timings");
//postCommand("set print static-members off"); // Seemingly doesn't work.
@@ -4277,6 +4273,9 @@ void GdbEngine::startGdb(const QStringList &args)
const QByteArray dumperSourcePath =
ICore::resourcePath().toLocal8Bit() + "/debugger/";
+ if (terminal()->isUsable())
+ postCommand("set inferior-tty " + terminal()->slaveDevice());
+
const QFileInfo gdbBinaryFile(m_gdb);
const QByteArray uninstalledData = gdbBinaryFile.absolutePath().toLocal8Bit()
+ "/data-directory/python";
@@ -4284,14 +4283,26 @@ void GdbEngine::startGdb(const QStringList &args)
const GdbCommandFlags flags = ConsoleCommand | Immediate;
postCommand("python sys.path.insert(1, '" + dumperSourcePath + "')", flags);
postCommand("python sys.path.append('" + uninstalledData + "')", flags);
- postCommand("python from gdbbridge import *", flags, CB(handlePythonSetup));
+ postCommand("python from gdbbridge import *", flags);
+
+ const QString path = stringSetting(ExtraDumperFile);
+ if (!path.isEmpty()) {
+ DebuggerCommand cmd("addDumperModule");
+ cmd.arg("path", path.toUtf8());
+ runCommand(cmd);
+ }
+
+ const QString commands = stringSetting(ExtraDumperCommands);
+ if (!commands.isEmpty())
+ postCommand(commands.toLocal8Bit(), flags);
+
+ runCommand(DebuggerCommand("setupDumper", flags, CB(handlePythonSetup)));
}
void GdbEngine::handleGdbStartFailed()
{
}
-
void GdbEngine::loadInitScript()
{
const QString script = startParameters().overrideStartScript;
@@ -4299,7 +4310,7 @@ void GdbEngine::loadInitScript()
if (QFileInfo(script).isReadable()) {
postCommand("source " + script.toLocal8Bit());
} else {
- showMessageBox(QMessageBox::Warning,
+ AsynchronousMessageBox::warning(
tr("Cannot find debugger initialization script"),
tr("The debugger settings point to a script file at \"%1\" "
"which is not accessible. If a script file is not needed, "
@@ -4315,7 +4326,8 @@ void GdbEngine::loadInitScript()
void GdbEngine::reloadDebuggingHelpers()
{
- postCommand("bbsetup");
+ runCommand("reloadDumper");
+ reloadLocals();
}
void GdbEngine::handleGdbError(QProcess::ProcessError error)
@@ -4336,7 +4348,7 @@ void GdbEngine::handleGdbError(QProcess::ProcessError error)
default:
//m_gdbProc->kill();
//notifyEngineIll();
- showMessageBox(QMessageBox::Critical, tr("GDB I/O Error"), msg);
+ AsynchronousMessageBox::critical(tr("GDB I/O Error"), msg);
break;
}
}
@@ -4364,7 +4376,7 @@ void GdbEngine::handleGdbFinished(int code, QProcess::ExitStatus type)
const QString msg = type == QProcess::CrashExit ?
tr("The gdb process terminated.") :
tr("The gdb process terminated unexpectedly (code %1)").arg(code);
- showMessageBox(QMessageBox::Critical, tr("Unexpected GDB Exit"), msg);
+ AsynchronousMessageBox::critical(tr("Unexpected GDB Exit"), msg);
break;
}
}
@@ -4394,10 +4406,9 @@ void GdbEngine::resetInferior()
if (state() == InferiorStopOk) {
postCommand(command, ConsoleCommand|Immediate);
} else {
- GdbCommand gdbCmd;
- gdbCmd.command = command;
- gdbCmd.flags = ConsoleCommand;
- m_commandsToRunOnTemporaryBreak.append(gdbCmd);
+ DebuggerCommand cmd(command);
+ cmd.flags = ConsoleCommand;
+ m_commandsToRunOnTemporaryBreak.append(cmd);
}
}
}
@@ -4457,7 +4468,7 @@ void GdbEngine::handleInferiorPrepared()
attemptBreakpointSynchronization();
}
- if (m_cookieForToken.isEmpty()) {
+ if (m_commandForToken.isEmpty()) {
finishInferiorSetup();
} else {
QTC_CHECK(m_commandsDoneCallback == 0);
@@ -4479,19 +4490,19 @@ void GdbEngine::finishInferiorSetup()
postCommand("-break-insert -f '" + qtNamespace() + "QMessageLogger::warning'");
}
if (boolSetting(BreakOnFatal)) {
- postCommand("-break-insert -f '" + qtNamespace() + "qFatal'",
- CB(handleBreakOnQFatal), QVariant(false));
- postCommand("-break-insert -f '" + qtNamespace() + "QMessageLogger::fatal'",
- CB(handleBreakOnQFatal), QVariant(true));
+ postCommand("-break-insert -f '" + qtNamespace() + "qFatal'", NoFlags,
+ [this](const DebuggerResponse &r) { handleBreakOnQFatal(r, false); });
+ postCommand("-break-insert -f '" + qtNamespace() + "QMessageLogger::fatal'", NoFlags,
+ [this](const DebuggerResponse &r) { handleBreakOnQFatal(r, true); });
} else {
notifyInferiorSetupOk();
}
}
}
-void GdbEngine::handleDebugInfoLocation(const GdbResponse &response)
+void GdbEngine::handleDebugInfoLocation(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
const QByteArray debugInfoLocation = startParameters().debugInfoLocation.toLocal8Bit();
if (QFile::exists(QString::fromLocal8Bit(debugInfoLocation))) {
const QByteArray curDebugInfoLocations = response.consoleStreamOutput.split('"').value(1);
@@ -4506,9 +4517,9 @@ void GdbEngine::handleDebugInfoLocation(const GdbResponse &response)
}
}
-void GdbEngine::handleBreakOnQFatal(const GdbResponse &response)
+void GdbEngine::handleBreakOnQFatal(const DebuggerResponse &response, bool continueSetup)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
GdbMi bkpt = response.data["bkpt"];
GdbMi number = bkpt["number"];
BreakpointResponseId rid(number.data());
@@ -4519,7 +4530,7 @@ void GdbEngine::handleBreakOnQFatal(const GdbResponse &response)
}
// Continue setup.
- if (response.cookie.toBool())
+ if (continueSetup)
notifyInferiorSetupOk();
}
@@ -4531,7 +4542,7 @@ void GdbEngine::notifyInferiorSetupFailed(const QString &msg)
return; // Adapter crashed meanwhile, so this notification is meaningless.
}
showMessage(_("INFERIOR START FAILED"));
- showMessageBox(QMessageBox::Critical, tr("Failed to start application"), msg);
+ AsynchronousMessageBox::critical(tr("Failed to start application"), msg);
DebuggerEngine::notifyInferiorSetupFailed();
}
@@ -4553,7 +4564,7 @@ void GdbEngine::handleAdapterCrashed(const QString &msg)
m_gdbProc->kill();
if (!msg.isEmpty())
- showMessageBox(QMessageBox::Critical, tr("Adapter crashed"), msg);
+ AsynchronousMessageBox::critical(tr("Adapter crashed"), msg);
}
void GdbEngine::createFullBacktrace()
@@ -4562,9 +4573,9 @@ void GdbEngine::createFullBacktrace()
NeedsStop|ConsoleCommand, CB(handleCreateFullBacktrace));
}
-void GdbEngine::handleCreateFullBacktrace(const GdbResponse &response)
+void GdbEngine::handleCreateFullBacktrace(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
Internal::openTextEditor(_("Backtrace $"),
_(response.consoleStreamOutput + response.logStreamOutput));
}
@@ -4573,65 +4584,17 @@ void GdbEngine::handleCreateFullBacktrace(const GdbResponse &response)
void GdbEngine::resetCommandQueue()
{
m_commandTimer.stop();
- if (!m_cookieForToken.isEmpty()) {
+ if (!m_commandForToken.isEmpty()) {
QString msg;
QTextStream ts(&msg);
ts << "RESETING COMMAND QUEUE. LEFT OVER TOKENS: ";
- foreach (const GdbCommand &cookie, m_cookieForToken)
- ts << "CMD:" << cookie.command << cookie.callbackName;
- m_cookieForToken.clear();
+ foreach (const DebuggerCommand &cmd, m_commandForToken)
+ ts << "CMD:" << cmd.function;
+ m_commandForToken.clear();
showMessage(msg);
}
}
-bool GdbEngine::setupQmlStep(bool on)
-{
- QTC_ASSERT(isSlaveEngine(), return false);
- m_qmlBreakpointResponseId1 = BreakpointResponseId();
- m_qmlBreakpointResponseId2 = BreakpointResponseId();
- //qDebug() << "CLEAR: " << m_qmlBreakpointNumbers;
- postCommand("tbreak '" + qtNamespace() + "QScript::FunctionWrapper::proxyCall'\n"
- "commands\n"
- "set $d=(void*)((FunctionWrapper*)callee)->data->function\n"
- "tbreak *$d\nprintf \"QMLBP:%d \\n\",$bpnum\ncontinue\nend",
- NeedsStop, CB(handleSetQmlStepBreakpoint));
- m_preparedForQmlBreak = on;
- return true;
-}
-
-void GdbEngine::handleSetQmlStepBreakpoint(const GdbResponse &response)
-{
- //QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
- // logStreamOutput: "tbreak 'myns::QScript::FunctionWrapper::proxyCall'\n"
- // consoleStreamOutput: "Temporary breakpoint 1 at 0xf166e7:
- // file bridge/qscriptfunction.cpp, line 75.\n"}
- QByteArray ba = parsePlainConsoleStream(response);
- const int pos2 = ba.indexOf(" at 0x");
- const int pos1 = ba.lastIndexOf(" ", pos2 - 1) + 1;
- QByteArray mid = ba.mid(pos1, pos2 - pos1);
- m_qmlBreakpointResponseId1 = BreakpointResponseId(mid);
- //qDebug() << "SET: " << m_qmlBreakpointResponseId1;
- }
- QTC_ASSERT(masterEngine(), return);
- masterEngine()->readyToExecuteQmlStep();
-}
-
-bool GdbEngine::isQmlStepBreakpoint(const BreakpointResponseId &id) const
-{
- return isQmlStepBreakpoint1(id) || isQmlStepBreakpoint2(id);
-}
-
-bool GdbEngine::isQmlStepBreakpoint1(const BreakpointResponseId &id) const
-{
- return id.isValid() && m_qmlBreakpointResponseId1 == id;
-}
-
-bool GdbEngine::isQmlStepBreakpoint2(const BreakpointResponseId &id) const
-{
- return id.isValid() && m_qmlBreakpointResponseId2 == id;
-}
-
bool GdbEngine::isQFatalBreakpoint(const BreakpointResponseId &id) const
{
return id.isValid() && m_qFatalBreakpointResponseId == id;
@@ -4639,7 +4602,7 @@ bool GdbEngine::isQFatalBreakpoint(const BreakpointResponseId &id) const
bool GdbEngine::isHiddenBreakpoint(const BreakpointResponseId &id) const
{
- return isQFatalBreakpoint(id) || isQmlStepBreakpoint(id);
+ return isQFatalBreakpoint(id);
}
bool GdbEngine::usesExecInterrupt() const
@@ -4673,8 +4636,8 @@ bool GdbEngine::attemptQuickStart() const
// Don't try if there are breakpoints we might be able to handle.
BreakHandler *handler = breakHandler();
- foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
- if (acceptsBreakpoint(id))
+ foreach (Breakpoint bp, handler->unclaimedBreakpoints()) {
+ if (acceptsBreakpoint(bp))
return false;
}
@@ -4761,7 +4724,7 @@ QByteArray GdbEngine::dotEscape(QByteArray str)
void GdbEngine::debugLastCommand()
{
- postCommand(m_lastDebuggableCommand, Discardable);
+ runCommand(m_lastDebuggableCommand);
}
//
@@ -4791,79 +4754,67 @@ void addGdbOptionPages(QList<IOptionsPage *> *opts)
opts->push_back(new GdbOptionsPage2());
}
-
void GdbEngine::updateLocalsPython(const UpdateParameters &params)
{
//m_pendingWatchRequests = 0;
m_pendingBreakpointRequests = 0;
m_processedNames.clear();
- WatchHandler *handler = watchHandler();
- QByteArray expanded = "expanded:" + handler->expansionRequests() + ' ';
- expanded += "typeformats:" + handler->typeFormatRequests() + ' ';
- expanded += "formats:" + handler->individualFormatRequests();
+ DebuggerCommand cmd("showData");
+ watchHandler()->appendFormatRequests(&cmd);
- QByteArray cutOff = " stringcutoff:"
- + action(MaximalStringLength)->value().toByteArray()
- + " displaystringlimit:"
- + action(DisplayStringLimit)->value().toByteArray();
+ cmd.arg("stringcutoff", action(MaximalStringLength)->value().toByteArray());
+ cmd.arg("displaystringlimit", action(DisplayStringLimit)->value().toByteArray());
// Re-create tooltip items that are not filters on existing local variables in
// the tooltip model.
- QByteArray watchers;
+ cmd.beginList("watchers");
DebuggerToolTipContexts toolTips = DebuggerToolTipManager::pendingTooltips(this);
foreach (const DebuggerToolTipContext &p, toolTips) {
- if (!watchers.isEmpty())
- watchers += "##";
- watchers += p.expression.toLatin1();
- watchers += '#';
- watchers += p.iname;
+ cmd.beginGroup();
+ cmd.arg("iname", p.iname);
+ cmd.arg("exp", p.expression.toLatin1().toHex());
+ cmd.endGroup();
}
- QHash<QByteArray, int> watcherNames = handler->watcherNames();
- QHashIterator<QByteArray, int> it(watcherNames);
+ QHashIterator<QByteArray, int> it(WatchHandler::watcherNames());
while (it.hasNext()) {
it.next();
- if (!watchers.isEmpty())
- watchers += "##";
- watchers += it.key() + "#watch." + QByteArray::number(it.value());
+ cmd.beginGroup();
+ cmd.arg("iname", "watch." + QByteArray::number(it.value()));
+ cmd.arg("exp", it.key().toHex());
+ cmd.endGroup();
}
+ cmd.endList();
const static bool alwaysVerbose = !qgetenv("QTC_DEBUGGER_PYTHON_VERBOSE").isEmpty();
- QByteArray options;
- if (alwaysVerbose)
- options += "pe,";
- if (boolSetting(UseDebuggingHelpers))
- options += "fancy,";
- if (boolSetting(AutoDerefPointers))
- options += "autoderef,";
- if (boolSetting(UseDynamicType))
- options += "dyntype,";
- if (options.isEmpty())
- options += "defaults,";
- if (params.tryPartial)
- options += "partial,";
- if (params.tooltipOnly)
- options += "tooltiponly,";
- options.chop(1);
-
- QByteArray resultVar;
- if (!m_resultVarName.isEmpty())
- resultVar = "resultvarname:" + m_resultVarName + ' ';
-
- m_lastDebuggableCommand =
- "bb options:pe," + options + " vars:" + params.varList + ' '
- + expanded + " watchers:" + watchers.toHex() + cutOff;
-
- postCommand("bb options:" + options + " vars:" + params.varList + ' '
- + resultVar + expanded + " watchers:" + watchers.toHex() + cutOff,
- Discardable, CB(handleStackFramePython), QVariant(params.tryPartial));
-}
-
-void GdbEngine::handleStackFramePython(const GdbResponse &response)
-{
- if (response.resultClass == GdbResultDone) {
- const bool partial = response.cookie.toBool();
+
+ cmd.arg("passExceptions", alwaysVerbose);
+ cmd.arg("fancy", boolSetting(UseDebuggingHelpers));
+ cmd.arg("autoderef", boolSetting(AutoDerefPointers));
+ cmd.arg("dyntype", boolSetting(UseDynamicType));
+ cmd.arg("nativemixed", isNativeMixedActive());
+ cmd.arg("partial", params.tryPartial);
+
+ if (isNativeMixedActive()) {
+ StackFrame frame = stackHandler()->currentFrame();
+ if (frame.language == QmlLanguage)
+ cmd.arg("qmlcontext", "0x" + QByteArray::number(frame.address, 16));
+ }
+
+ cmd.arg("resultvarname", m_resultVarName);
+ cmd.arg("vars", params.varList);
+ cmd.flags = Discardable;
+ cmd.callback = [this, params](const DebuggerResponse &r) { handleStackFramePython(r, params.tryPartial); };
+ runCommand(cmd);
+
+ cmd.arg("passExceptions", true);
+ m_lastDebuggableCommand = cmd;
+}
+
+void GdbEngine::handleStackFramePython(const DebuggerResponse &response, bool partial)
+{
+ if (response.resultClass == ResultDone) {
QByteArray out = response.consoleStreamOutput;
while (out.endsWith(' ') || out.endsWith('\n'))
out.chop(1);
@@ -4884,27 +4835,7 @@ void GdbEngine::handleStackFramePython(const GdbResponse &response)
}
WatchHandler *handler = watchHandler();
- QList<WatchData> list;
-
- if (!partial) {
- list.append(*handler->findData("local"));
- list.append(*handler->findData("watch"));
- list.append(*handler->findData("return"));
- }
- foreach (const GdbMi &child, data.children()) {
- WatchData dummy;
- dummy.iname = child["iname"].data();
- GdbMi wname = child["wname"];
- if (wname.isValid()) {
- // Happens (only) for watched expressions.
- dummy.name = QString::fromUtf8(QByteArray::fromHex(wname.data()));
- dummy.exp = dummy.name.toUtf8();
- } else {
- dummy.name = _(child["name"].data());
- }
- parseWatchData(handler->expandedINames(), dummy, child, &list);
- }
const GdbMi typeInfo = all["typeinfo"];
if (typeInfo.type() == GdbMi::List) {
foreach (const GdbMi &s, typeInfo.children()) {
@@ -4915,13 +4846,24 @@ void GdbEngine::handleStackFramePython(const GdbResponse &response)
TypeInfo(size.data().toUInt()));
}
}
- for (int i = 0; i != list.size(); ++i) {
- const TypeInfo ti = m_typeInfoCache.value(list.at(i).type);
+
+ QSet<QByteArray> toDelete;
+ if (!partial) {
+ foreach (WatchItem *item, handler->model()->treeLevelItems<WatchItem *>(2))
+ toDelete.insert(item->d.iname);
+ }
+
+ foreach (const GdbMi &child, data.children()) {
+ WatchItem *item = new WatchItem(child);
+ const TypeInfo ti = m_typeInfoCache.value(item->d.type);
if (ti.size)
- list[i].size = ti.size;
+ item->d.size = ti.size;
+
+ handler->insertItem(item);
+ toDelete.remove(item->d.iname);
}
- handler->insertData(list);
+ handler->purgeOutdatedItems(toDelete);
//PENDING_DEBUG("AFTER handleStackFrame()");
// FIXME: This should only be used when updateLocals() was
@@ -4960,10 +4902,7 @@ QString GdbEngine::msgPtraceError(DebuggerStartMode sm)
"For more details, see /etc/sysctl.d/10-ptrace.conf\n");
}
-
} // namespace Internal
} // namespace Debugger
-Q_DECLARE_METATYPE(Debugger::Internal::MemoryAgentCookie)
-Q_DECLARE_METATYPE(Debugger::Internal::DisassemblerAgentCookie)
Q_DECLARE_METATYPE(Debugger::Internal::GdbMi)
diff --git a/src/plugins/debugger/gdb/gdbengine.h b/src/plugins/debugger/gdb/gdbengine.h
index f443ed68e33..eb48e45dfcd 100644
--- a/src/plugins/debugger/gdb/gdbengine.h
+++ b/src/plugins/debugger/gdb/gdbengine.h
@@ -33,6 +33,7 @@
#include <debugger/debuggerengine.h>
+#include <debugger/breakhandler.h>
#include <debugger/watchhandler.h>
#include <debugger/watchutils.h>
#include <debugger/debuggertooltipmanager.h>
@@ -52,15 +53,17 @@ namespace Internal {
class GdbProcess;
class DebugInfoTask;
class DebugInfoTaskHandler;
-class GdbResponse;
+class DebuggerResponse;
class GdbMi;
class MemoryAgentCookie;
+class BreakpointParameters;
+class BreakpointResponse;
class WatchData;
class DisassemblerAgentCookie;
class DisassemblerLines;
-class GdbEngine : public Debugger::DebuggerEngine
+class GdbEngine : public DebuggerEngine
{
Q_OBJECT
@@ -97,8 +100,8 @@ private: ////////// General State //////////
protected: ////////// Gdb Process Management //////////
void startGdb(const QStringList &args = QStringList());
- void handleInferiorShutdown(const GdbResponse &response);
- void handleGdbExit(const GdbResponse &response);
+ void handleInferiorShutdown(const DebuggerResponse &response);
+ void handleGdbExit(const DebuggerResponse &response);
void loadInitScript();
@@ -113,7 +116,7 @@ protected: ////////// Gdb Process Management //////////
// This notifies the base of a successful inferior setup.
void finishInferiorSetup();
- void handleDebugInfoLocation(const GdbResponse &response);
+ void handleDebugInfoLocation(const DebuggerResponse &response);
// The adapter is still running just fine, but it failed to acquire a debuggee.
void notifyInferiorSetupFailed(const QString &msg);
@@ -126,12 +129,13 @@ protected: ////////// Gdb Process Management //////////
void handleAdapterCrashed(const QString &msg);
private slots:
+ friend class GdbPlainEngine;
void handleInterruptDeviceInferior(const QString &error);
void handleGdbFinished(int, QProcess::ExitStatus status);
void handleGdbError(QProcess::ProcessError error);
+ void readDebugeeOutput(const QByteArray &data);
void readGdbStandardOutput();
void readGdbStandardError();
- void readDebugeeOutput(const QByteArray &data);
private:
QTextCodec *m_outputCodec;
@@ -155,9 +159,9 @@ private: ////////// Gdb Command Management //////////
Discardable = 2,
// We can live without receiving an answer.
NonCriticalResponse = 8,
- // Callback expects GdbResultRunning instead of GdbResultDone.
+ // Callback expects ResultRunning instead of ResultDone.
RunRequest = 16,
- // Callback expects GdbResultExit instead of GdbResultDone.
+ // Callback expects ResultExit instead of ResultDone.
ExitRequest = 32,
// Auto-set inferior shutdown related states.
LosesChild = 64,
@@ -170,40 +174,17 @@ private: ////////// Gdb Command Management //////////
};
Q_DECLARE_FLAGS(GdbCommandFlags, GdbCommandFlag)
- protected:
- typedef void (GdbEngine::*GdbCommandCallback)(const GdbResponse &response);
-
- struct GdbCommand
- {
- GdbCommand()
- : flags(0), callback(0), callbackName(0)
- {}
-
- int flags;
- GdbCommandCallback callback;
- const char *callbackName;
- QByteArray command;
- QVariant cookie;
- QTime postTime;
- };
-
// Type and cookie are sender-internal data, opaque for the "event
// queue". resultNeeded == true increments m_pendingResults on
// send and decrements on receipt, effectively preventing
// watch model updates before everything is finished.
- void flushCommand(const GdbCommand &cmd);
+ void flushCommand(const DebuggerCommand &cmd);
protected:
+ void runCommand(const DebuggerCommand &command);
void postCommand(const QByteArray &command,
- GdbCommandFlags flags,
- GdbCommandCallback callback = 0,
- const char *callbackName = 0,
- const QVariant &cookie = QVariant());
- void postCommand(const QByteArray &command,
- GdbCommandCallback callback = 0,
- const char *callbackName = 0,
- const QVariant &cookie = QVariant());
+ int flags = NoFlags,
+ DebuggerCommand::Callback callback = DebuggerCommand::Callback());
private:
- void postCommandHelper(const GdbCommand &cmd);
void flushQueuedCommands();
Q_SLOT void commandTimeout();
void setTokenBarrier();
@@ -211,7 +192,7 @@ private:
// Sets up an "unexpected result" for the following commeand.
void scheduleTestResponse(int testCase, const QByteArray &response);
- QHash<int, GdbCommand> m_cookieForToken;
+ QHash<int, DebuggerCommand> m_commandForToken;
int commandTimeoutTime() const;
QTimer m_commandTimer;
@@ -230,16 +211,14 @@ private:
// This function is called after all previous responses have been received.
CommandsDoneCallback m_commandsDoneCallback;
- QList<GdbCommand> m_commandsToRunOnTemporaryBreak;
+ QList<DebuggerCommand> m_commandsToRunOnTemporaryBreak;
private: ////////// Gdb Output, State & Capability Handling //////////
protected:
Q_SLOT void handleResponse(const QByteArray &buff);
void handleStopResponse(const GdbMi &data);
- void handleResultRecord(GdbResponse *response);
- void handleStop1(const GdbResponse &response);
+ void handleResultRecord(DebuggerResponse *response);
void handleStop1(const GdbMi &data);
- void handleStop2(const GdbResponse &response);
void handleStop2(const GdbMi &data);
Q_SLOT void handleStop2();
StackFrame parseStackFrame(const GdbMi &mi, int level);
@@ -248,9 +227,9 @@ protected:
bool isSynchronous() const { return true; }
// Gdb initialization sequence
- void handleShowVersion(const GdbResponse &response);
- void handleListFeatures(const GdbResponse &response);
- void handlePythonSetup(const GdbResponse &response);
+ void handleShowVersion(const DebuggerResponse &response);
+ void handleListFeatures(const DebuggerResponse &response);
+ void handlePythonSetup(const DebuggerResponse &response);
int m_gdbVersion; // 7.6.1 is 70601
bool m_isQnxGdb;
@@ -259,10 +238,10 @@ private: ////////// Inferior Management //////////
// This should be always the last call in a function.
bool stateAcceptsBreakpointChanges() const;
- bool acceptsBreakpoint(BreakpointModelId id) const;
- void insertBreakpoint(BreakpointModelId id);
- void removeBreakpoint(BreakpointModelId id);
- void changeBreakpoint(BreakpointModelId id);
+ bool acceptsBreakpoint(Breakpoint bp) const;
+ void insertBreakpoint(Breakpoint bp);
+ void removeBreakpoint(Breakpoint bp);
+ void changeBreakpoint(Breakpoint bp);
void executeStep();
void executeStepOut();
@@ -283,15 +262,15 @@ private: ////////// Inferior Management //////////
void executeJumpToLine(const ContextData &data);
void executeReturn();
- void handleExecuteContinue(const GdbResponse &response);
- void handleExecuteStep(const GdbResponse &response);
- void handleExecuteNext(const GdbResponse &response);
- void handleExecuteReturn(const GdbResponse &response);
- void handleExecuteJumpToLine(const GdbResponse &response);
- void handleExecuteRunToLine(const GdbResponse &response);
+ void handleExecuteContinue(const DebuggerResponse &response);
+ void handleExecuteStep(const DebuggerResponse &response);
+ void handleExecuteNext(const DebuggerResponse &response);
+ void handleExecuteReturn(const DebuggerResponse &response);
+ void handleExecuteJumpToLine(const DebuggerResponse &response);
+ void handleExecuteRunToLine(const DebuggerResponse &response);
void maybeHandleInferiorPidChanged(const QString &pid);
- void handleInfoProc(const GdbResponse &response);
+ void handleInfoProc(const DebuggerResponse &response);
QString msgPtraceError(DebuggerStartMode sm);
private: ////////// View & Data Stuff //////////
@@ -303,21 +282,21 @@ private: ////////// View & Data Stuff //////////
// Breakpoint specific stuff
//
void handleBreakModifications(const GdbMi &bkpts);
- void handleBreakIgnore(const GdbResponse &response);
- void handleBreakDisable(const GdbResponse &response);
- void handleBreakEnable(const GdbResponse &response);
- void handleBreakInsert1(const GdbResponse &response);
- void handleBreakInsert2(const GdbResponse &response);
- void handleTraceInsert2(const GdbResponse &response);
- void handleBreakCondition(const GdbResponse &response);
- void handleBreakThreadSpec(const GdbResponse &response);
- void handleBreakLineNumber(const GdbResponse &response);
- void handleWatchInsert(const GdbResponse &response);
- void handleCatchInsert(const GdbResponse &response);
- void handleBkpt(const GdbMi &bkpt, const BreakpointModelId &id);
+ void handleBreakIgnore(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakDisable(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakEnable(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakInsert1(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakInsert2(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakDelete(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakCondition(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakThreadSpec(const DebuggerResponse &response, Breakpoint bp);
+ void handleBreakLineNumber(const DebuggerResponse &response, Breakpoint bp);
+ void handleWatchInsert(const DebuggerResponse &response, Breakpoint bp);
+ void handleCatchInsert(const DebuggerResponse &response, Breakpoint bp);
+ void handleBkpt(const GdbMi &bkpt, Breakpoint bp);
void updateResponse(BreakpointResponse &response, const GdbMi &bkpt);
- QByteArray breakpointLocation(BreakpointModelId id); // For gdb/MI.
- QByteArray breakpointLocation2(BreakpointModelId id); // For gdb/CLI fallback.
+ QByteArray breakpointLocation(const BreakpointParameters &data); // For gdb/MI.
+ QByteArray breakpointLocation2(const BreakpointParameters &data); // For gdb/CLI fallback.
QString breakLocation(const QString &file) const;
//
@@ -333,24 +312,24 @@ private: ////////// View & Data Stuff //////////
void examineModules();
void reloadModulesInternal();
- void handleModulesList(const GdbResponse &response);
- void handleShowModuleSymbols(const GdbResponse &response);
- void handleShowModuleSections(const GdbResponse &response);
+ void handleModulesList(const DebuggerResponse &response);
+ void handleShowModuleSections(const DebuggerResponse &response, const QString &moduleName);
//
// Snapshot specific stuff
//
virtual void createSnapshot();
- void handleMakeSnapshot(const GdbResponse &response);
+ void handleMakeSnapshot(const DebuggerResponse &response, const QString &coreFile);
//
// Register specific stuff
//
Q_SLOT void reloadRegisters();
- void setRegisterValue(int nr, const QString &value);
- void handleRegisterListNames(const GdbResponse &response);
- void handleRegisterListValues(const GdbResponse &response);
- QVector<int> m_registerNumbers; // Map GDB register numbers to indices
+ void setRegisterValue(const QByteArray &name, const QString &value);
+ void handleRegisterListNames(const DebuggerResponse &response);
+ void handleRegisterListValues(const DebuggerResponse &response);
+ void handleMaintPrintRegisters(const DebuggerResponse &response);
+ QHash<int, QByteArray> m_registerNames; // Map GDB register numbers to indices
//
// Disassembler specific stuff
@@ -360,19 +339,16 @@ private: ////////// View & Data Stuff //////////
void fetchDisassemblerByCliPointMixed(const DisassemblerAgentCookie &ac);
void fetchDisassemblerByCliRangeMixed(const DisassemblerAgentCookie &ac);
void fetchDisassemblerByCliRangePlain(const DisassemblerAgentCookie &ac);
- void handleFetchDisassemblerByCliPointMixed(const GdbResponse &response);
- void handleFetchDisassemblerByCliRangeMixed(const GdbResponse &response);
- void handleFetchDisassemblerByCliRangePlain(const GdbResponse &response);
bool handleCliDisassemblerResult(const QByteArray &response, DisassemblerAgent *agent);
- void handleBreakOnQFatal(const GdbResponse &response);
+ void handleBreakOnQFatal(const DebuggerResponse &response, bool continueSetup);
//
// Source file specific stuff
//
void reloadSourceFiles();
void reloadSourceFilesInternal();
- void handleQuerySources(const GdbResponse &response);
+ void handleQuerySources(const DebuggerResponse &response);
QString fullName(const QString &fileName);
QString cleanupFullName(const QString &fileName);
@@ -389,17 +365,17 @@ private: ////////// View & Data Stuff //////////
//
protected:
void updateAll();
- void handleStackListFrames(const GdbResponse &response);
- void handleStackSelectThread(const GdbResponse &response);
- void handleStackSelectFrame(const GdbResponse &response);
- void handleThreadListIds(const GdbResponse &response);
- void handleThreadInfo(const GdbResponse &response);
- void handleThreadNames(const GdbResponse &response);
- Q_SLOT void reloadStack(bool forceGotoLocation);
+ void handleStackListFrames(const DebuggerResponse &response, bool isFull);
+ void handleStackSelectThread(const DebuggerResponse &response);
+ void handleThreadListIds(const DebuggerResponse &response);
+ void handleThreadInfo(const DebuggerResponse &response);
+ void handleThreadNames(const DebuggerResponse &response);
+ DebuggerCommand stackCommand(int depth);
+ Q_SLOT void reloadStack();
Q_SLOT virtual void reloadFullStack();
virtual void loadAdditionalQmlStack();
- void handleQmlStackFrameArguments(const GdbResponse &response);
- void handleQmlStackTrace(const GdbResponse &response);
+ void handleQmlStackFrameArguments(const DebuggerResponse &response);
+ void handleQmlStackTrace(const DebuggerResponse &response);
int currentFrame() const;
QList<GdbMi> m_currentFunctionArgs;
@@ -415,13 +391,13 @@ protected:
virtual void fetchMemory(MemoryAgent *agent, QObject *token,
quint64 addr, quint64 length);
void fetchMemoryHelper(const MemoryAgentCookie &cookie);
- void handleChangeMemory(const GdbResponse &response);
+ void handleChangeMemory(const DebuggerResponse &response);
virtual void changeMemory(MemoryAgent *agent, QObject *token,
quint64 addr, const QByteArray &data);
- void handleFetchMemory(const GdbResponse &response);
+ void handleFetchMemory(const DebuggerResponse &response, MemoryAgentCookie ac);
virtual void watchPoint(const QPoint &);
- void handleWatchPoint(const GdbResponse &response);
+ void handleWatchPoint(const DebuggerResponse &response);
void updateWatchData(const WatchData &data, const WatchUpdateFlags &flags);
void rebuildWatchModel();
@@ -429,17 +405,17 @@ protected:
void insertData(const WatchData &data);
- void handleVarAssign(const GdbResponse &response);
- void handleDetach(const GdbResponse &response);
+ void handleVarAssign(const DebuggerResponse &response);
+ void handleDetach(const DebuggerResponse &response);
void handleThreadGroupCreated(const GdbMi &result);
void handleThreadGroupExited(const GdbMi &result);
Q_SLOT void createFullBacktrace();
- void handleCreateFullBacktrace(const GdbResponse &response);
+ void handleCreateFullBacktrace(const DebuggerResponse &response);
void updateLocals();
void updateLocalsPython(const UpdateParameters &parameters);
- void handleStackFramePython(const GdbResponse &response);
+ void handleStackFramePython(const DebuggerResponse &response, bool partial);
void setLocals(const QList<GdbMi> &locals);
@@ -472,17 +448,6 @@ protected:
// For short-circuiting stack and thread list evaluation.
bool m_stackNeeded;
- //
- // Qml
- //
- BreakpointResponseId m_qmlBreakpointResponseId1;
- BreakpointResponseId m_qmlBreakpointResponseId2;
- bool m_preparedForQmlBreak;
- bool setupQmlStep(bool on);
- void handleSetQmlStepBreakpoint(const GdbResponse &response);
- bool isQmlStepBreakpoint(const BreakpointResponseId &id) const;
- bool isQmlStepBreakpoint1(const BreakpointResponseId &id) const;
- bool isQmlStepBreakpoint2(const BreakpointResponseId &id) const;
bool isQFatalBreakpoint(const BreakpointResponseId &id) const;
bool isHiddenBreakpoint(const BreakpointResponseId &id) const;
@@ -522,7 +487,7 @@ protected:
static QByteArray dotEscape(QByteArray str);
void debugLastCommand();
- QByteArray m_lastDebuggableCommand;
+ DebuggerCommand m_lastDebuggableCommand;
protected:
virtual void write(const QByteArray &data);
diff --git a/src/plugins/debugger/gdb/gdboptionspage.cpp b/src/plugins/debugger/gdb/gdboptionspage.cpp
index 545c0e8e051..259f7acefe6 100644
--- a/src/plugins/debugger/gdb/gdboptionspage.cpp
+++ b/src/plugins/debugger/gdb/gdboptionspage.cpp
@@ -311,7 +311,7 @@ QWidget *GdbOptionsPage::widget()
void GdbOptionsPage::apply()
{
if (m_widget)
- m_widget->group.apply(Core::ICore::settings());
+ m_widget->group.apply(ICore::settings());
}
void GdbOptionsPage::finish()
@@ -457,7 +457,7 @@ QWidget *GdbOptionsPage2::widget()
void GdbOptionsPage2::apply()
{
if (m_widget)
- m_widget->group.apply(Core::ICore::settings());
+ m_widget->group.apply(ICore::settings());
}
void GdbOptionsPage2::finish()
diff --git a/src/plugins/debugger/gdb/gdbplainengine.cpp b/src/plugins/debugger/gdb/gdbplainengine.cpp
index 4b955e60d93..c19bdde3a82 100644
--- a/src/plugins/debugger/gdb/gdbplainengine.cpp
+++ b/src/plugins/debugger/gdb/gdbplainengine.cpp
@@ -45,19 +45,16 @@
namespace Debugger {
namespace Internal {
-#define CB(callback) \
- static_cast<GdbEngine::GdbCommandCallback>(&GdbPlainEngine::callback), \
- STRINGIFY(callback)
+#define CB(callback) [this](const DebuggerResponse &r) { callback(r); }
GdbPlainEngine::GdbPlainEngine(const DebuggerStartParameters &startParameters)
: GdbEngine(startParameters)
{
// Output
- connect(&m_outputCollector, SIGNAL(byteDelivery(QByteArray)),
- this, SLOT(readDebugeeOutput(QByteArray)));
+ connect(&m_outputCollector, &OutputCollector::byteDelivery,
+ this, &GdbEngine::readDebugeeOutput);
}
-
void GdbPlainEngine::setupInferior()
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
@@ -66,13 +63,13 @@ void GdbPlainEngine::setupInferior()
postCommand("-exec-arguments " + toLocalEncoding(args));
}
postCommand("-file-exec-and-symbols \"" + execFilePath() + '"',
- CB(handleFileExecAndSymbols));
+ NoFlags, CB(handleFileExecAndSymbols));
}
-void GdbPlainEngine::handleFileExecAndSymbols(const GdbResponse &response)
+void GdbPlainEngine::handleFileExecAndSymbols(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
handleInferiorPrepared();
} else {
QByteArray ba = response.data["msg"].data();
@@ -92,10 +89,10 @@ void GdbPlainEngine::runEngine()
postCommand("-exec-run", GdbEngine::RunRequest, CB(handleExecRun));
}
-void GdbPlainEngine::handleExecRun(const GdbResponse &response)
+void GdbPlainEngine::handleExecRun(const DebuggerResponse &response)
{
QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
- if (response.resultClass == GdbResultRunning) {
+ if (response.resultClass == ResultRunning) {
//notifyEngineRunOkAndInferiorRunRequested();
notifyEngineRunAndInferiorRunOk(); // For gdb < 7.0
//showStatusMessage(tr("Running..."));
diff --git a/src/plugins/debugger/gdb/gdbplainengine.h b/src/plugins/debugger/gdb/gdbplainengine.h
index 1cf33e92635..fc889c9d282 100644
--- a/src/plugins/debugger/gdb/gdbplainengine.h
+++ b/src/plugins/debugger/gdb/gdbplainengine.h
@@ -46,8 +46,8 @@ public:
explicit GdbPlainEngine(const DebuggerStartParameters &startParameters);
private:
- void handleExecRun(const GdbResponse &response);
- void handleFileExecAndSymbols(const GdbResponse &response);
+ void handleExecRun(const DebuggerResponse &response);
+ void handleFileExecAndSymbols(const DebuggerResponse &response);
void setupInferior();
void runEngine();
diff --git a/src/plugins/debugger/gdb/gdbprocess.cpp b/src/plugins/debugger/gdb/gdbprocess.cpp
index 4987fa0d753..7115923b6a1 100644
--- a/src/plugins/debugger/gdb/gdbprocess.cpp
+++ b/src/plugins/debugger/gdb/gdbprocess.cpp
@@ -31,6 +31,7 @@
#include "gdbprocess.h"
#include <debugger/debuggerconstants.h>
+#include <debugger/debuggercore.h>
#include <debugger/procinterrupt.h>
namespace Debugger {
@@ -115,8 +116,11 @@ void GdbProcess::setProcessEnvironment(const QProcessEnvironment &env)
m_gdbProc.setProcessEnvironment(env);
}
-void GdbProcess::setEnvironment(const QStringList &env)
+void GdbProcess::setEnvironment(const QStringList &env_)
{
+ QStringList env = env_;
+ if (isNativeMixedActive())
+ env.append(QLatin1String("QV4_FORCE_INTERPRETER=1")); // FIXME: REMOVE!
m_gdbProc.setEnvironment(Utils::Environment(env));
}
diff --git a/src/plugins/debugger/gdb/remotegdbserveradapter.cpp b/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
index b5c7b72d88a..137a41ed2da 100644
--- a/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
+++ b/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
@@ -38,19 +38,20 @@
#include <debugger/debuggerstartparameters.h>
#include <debugger/debuggerstringutils.h>
+#include <coreplugin/messagebox.h>
+
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QFileInfo>
-#include <QMessageBox>
+
+using namespace Utils;
namespace Debugger {
namespace Internal {
-#define CB(callback) \
- static_cast<GdbEngine::GdbCommandCallback>(&GdbRemoteServerEngine::callback), \
- STRINGIFY(callback)
+#define CB(callback) [this](const DebuggerResponse &r) { callback(r); }
///////////////////////////////////////////////////////////////////////
//
@@ -61,16 +62,17 @@ namespace Internal {
GdbRemoteServerEngine::GdbRemoteServerEngine(const DebuggerStartParameters &startParameters)
: GdbEngine(startParameters), m_startAttempted(false)
{
- if (Utils::HostOsInfo::isWindowsHost())
+ if (HostOsInfo::isWindowsHost())
m_gdbProc->setUseCtrlCStub(startParameters.useCtrlCStub); // This is only set for QNX/BlackBerry
- connect(&m_uploadProc, SIGNAL(error(QProcess::ProcessError)),
- SLOT(uploadProcError(QProcess::ProcessError)));
- connect(&m_uploadProc, SIGNAL(readyReadStandardOutput()),
- SLOT(readUploadStandardOutput()));
- connect(&m_uploadProc, SIGNAL(readyReadStandardError()),
- SLOT(readUploadStandardError()));
- connect(&m_uploadProc, SIGNAL(finished(int)),
- SLOT(uploadProcFinished()));
+
+ connect(&m_uploadProc, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
+ this, &GdbRemoteServerEngine::uploadProcError);
+ connect(&m_uploadProc, &QProcess::readyReadStandardOutput,
+ this, &GdbRemoteServerEngine::readUploadStandardOutput);
+ connect(&m_uploadProc, &QProcess::readyReadStandardError,
+ this, &GdbRemoteServerEngine::readUploadStandardError);
+ connect(&m_uploadProc, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
+ this, &GdbRemoteServerEngine::uploadProcFinished);
}
void GdbRemoteServerEngine::setupEngine()
@@ -81,9 +83,9 @@ void GdbRemoteServerEngine::setupEngine()
// Provide script information about the environment
QString arglist;
- Utils::QtcProcess::addArg(&arglist, startParameters().serverStartScript);
- Utils::QtcProcess::addArg(&arglist, startParameters().executable);
- Utils::QtcProcess::addArg(&arglist, startParameters().remoteChannel);
+ QtcProcess::addArg(&arglist, startParameters().serverStartScript);
+ QtcProcess::addArg(&arglist, startParameters().executable);
+ QtcProcess::addArg(&arglist, startParameters().remoteChannel);
m_uploadProc.start(_("/bin/sh ") + arglist);
m_uploadProc.waitForStarted();
@@ -130,7 +132,7 @@ void GdbRemoteServerEngine::uploadProcError(QProcess::ProcessError error)
}
showMessage(msg, StatusBar);
- showMessageBox(QMessageBox::Critical, tr("Error"), msg);
+ Core::AsynchronousMessageBox::critical(tr("Error"), msg);
}
void GdbRemoteServerEngine::readUploadStandardOutput()
@@ -173,12 +175,12 @@ void GdbRemoteServerEngine::setupInferior()
//const QByteArray sysroot = sp.sysroot.toLocal8Bit();
//const QByteArray remoteArch = sp.remoteArchitecture.toLatin1();
- const QString args = isMasterEngine() ? startParameters().processArgs : masterEngine()->startParameters().processArgs;
+ const QString args = isMasterEngine() ? startParameters().processArgs
+ : masterEngine()->startParameters().processArgs;
// if (!remoteArch.isEmpty())
// postCommand("set architecture " + remoteArch);
- const QString solibSearchPath
- = sp.solibSearchPath.join(Utils::HostOsInfo::pathListSeparator());
+ const QString solibSearchPath = sp.solibSearchPath.join(HostOsInfo::pathListSeparator());
if (!solibSearchPath.isEmpty())
postCommand("set solib-search-path " + solibSearchPath.toLocal8Bit());
@@ -205,7 +207,7 @@ void GdbRemoteServerEngine::setupInferior()
// mi_execute_async_cli_command: Assertion `is_running (inferior_ptid)'
// failed.\nA problem internal to GDB has been detected,[...]
if (boolSetting(TargetAsync))
- postCommand("set target-async on", CB(handleSetTargetAsync));
+ postCommand("set target-async on", NoFlags, CB(handleSetTargetAsync));
if (executableFileName.isEmpty()) {
showMessage(tr("No symbol file given."), StatusBar);
@@ -215,21 +217,21 @@ void GdbRemoteServerEngine::setupInferior()
if (!executableFileName.isEmpty()) {
postCommand("-file-exec-and-symbols \"" + executableFileName.toLocal8Bit() + '"',
- CB(handleFileExecAndSymbols));
+ NoFlags, CB(handleFileExecAndSymbols));
}
}
-void GdbRemoteServerEngine::handleSetTargetAsync(const GdbResponse &response)
+void GdbRemoteServerEngine::handleSetTargetAsync(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultError)
+ if (response.resultClass == ResultError)
qDebug() << "Adapter too old: does not support asynchronous mode.";
}
-void GdbRemoteServerEngine::handleFileExecAndSymbols(const GdbResponse &response)
+void GdbRemoteServerEngine::handleFileExecAndSymbols(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
callTargetRemote();
} else {
QByteArray reason = response.data["msg"].data();
@@ -265,17 +267,17 @@ void GdbRemoteServerEngine::callTargetRemote()
}
if (m_isQnxGdb)
- postCommand("target qnx " + channel, CB(handleTargetQnx));
+ postCommand("target qnx " + channel, NoFlags, CB(handleTargetQnx));
else if (startParameters().multiProcess)
- postCommand("target extended-remote " + channel, CB(handleTargetExtendedRemote));
+ postCommand("target extended-remote " + channel, NoFlags, CB(handleTargetExtendedRemote));
else
- postCommand("target remote " + channel, CB(handleTargetRemote), 10);
+ postCommand("target remote " + channel, NoFlags, CB(handleTargetRemote));
}
-void GdbRemoteServerEngine::handleTargetRemote(const GdbResponse &response)
+void GdbRemoteServerEngine::handleTargetRemote(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// gdb server will stop the remote application itself.
showMessage(_("INFERIOR STARTED"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
@@ -293,10 +295,10 @@ void GdbRemoteServerEngine::handleTargetRemote(const GdbResponse &response)
}
}
-void GdbRemoteServerEngine::handleTargetExtendedRemote(const GdbResponse &response)
+void GdbRemoteServerEngine::handleTargetExtendedRemote(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
showMessage(_("ATTACHED TO GDB SERVER STARTED"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
QString postAttachCommands = stringSetting(GdbPostAttachCommands);
@@ -307,10 +309,10 @@ void GdbRemoteServerEngine::handleTargetExtendedRemote(const GdbResponse &respon
if (startParameters().attachPID > 0) { // attach to pid if valid
// gdb server will stop the remote application itself.
postCommand("attach " + QByteArray::number(startParameters().attachPID),
- CB(handleTargetExtendedAttach));
+ NoFlags, CB(handleTargetExtendedAttach));
} else {
postCommand("-gdb-set remote exec-file " + startParameters().remoteExecutable.toLatin1(),
- CB(handleTargetExtendedAttach));
+ NoFlags, CB(handleTargetExtendedAttach));
}
} else {
QString msg = msgConnectRemoteServerFailed(
@@ -319,10 +321,10 @@ void GdbRemoteServerEngine::handleTargetExtendedRemote(const GdbResponse &respon
}
}
-void GdbRemoteServerEngine::handleTargetExtendedAttach(const GdbResponse &response)
+void GdbRemoteServerEngine::handleTargetExtendedAttach(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// gdb server will stop the remote application itself.
handleInferiorPrepared();
} else {
@@ -332,17 +334,11 @@ void GdbRemoteServerEngine::handleTargetExtendedAttach(const GdbResponse &respon
}
}
-void GdbRemoteServerEngine::notifyInferiorSetupOk()
-{
- emit aboutToNotifyInferiorSetupOk();
- GdbEngine::notifyInferiorSetupOk();
-}
-
-void GdbRemoteServerEngine::handleTargetQnx(const GdbResponse &response)
+void GdbRemoteServerEngine::handleTargetQnx(const DebuggerResponse &response)
{
QTC_ASSERT(m_isQnxGdb, qDebug() << m_isQnxGdb);
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// gdb server will stop the remote application itself.
showMessage(_("INFERIOR STARTED"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
@@ -350,9 +346,9 @@ void GdbRemoteServerEngine::handleTargetQnx(const GdbResponse &response)
const qint64 pid = isMasterEngine() ? startParameters().attachPID : masterEngine()->startParameters().attachPID;
const QString remoteExecutable = isMasterEngine() ? startParameters().remoteExecutable : masterEngine()->startParameters().remoteExecutable;
if (pid > -1)
- postCommand("attach " + QByteArray::number(pid), CB(handleAttach));
+ postCommand("attach " + QByteArray::number(pid), NoFlags, CB(handleAttach));
else if (!remoteExecutable.isEmpty())
- postCommand("set nto-executable " + remoteExecutable.toLatin1(), CB(handleSetNtoExecutable));
+ postCommand("set nto-executable " + remoteExecutable.toLatin1(), NoFlags, CB(handleSetNtoExecutable));
else
handleInferiorPrepared();
} else {
@@ -363,18 +359,18 @@ void GdbRemoteServerEngine::handleTargetQnx(const GdbResponse &response)
}
}
-void GdbRemoteServerEngine::handleAttach(const GdbResponse &response)
+void GdbRemoteServerEngine::handleAttach(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
switch (response.resultClass) {
- case GdbResultDone:
- case GdbResultRunning: {
+ case ResultDone:
+ case ResultRunning: {
showMessage(_("INFERIOR ATTACHED"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
handleInferiorPrepared();
break;
}
- case GdbResultError:
+ case ResultError:
if (response.data["msg"].data() == "ptrace: Operation not permitted.") {
notifyInferiorSetupFailed(msgPtraceError(startParameters().startMode));
break;
@@ -386,18 +382,18 @@ void GdbRemoteServerEngine::handleAttach(const GdbResponse &response)
}
}
-void GdbRemoteServerEngine::handleSetNtoExecutable(const GdbResponse &response)
+void GdbRemoteServerEngine::handleSetNtoExecutable(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
switch (response.resultClass) {
- case GdbResultDone:
- case GdbResultRunning: {
+ case ResultDone:
+ case ResultRunning: {
showMessage(_("EXECUTABLE SET"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
handleInferiorPrepared();
break;
}
- case GdbResultError:
+ case ResultError:
default:
QString msg = QString::fromLocal8Bit(response.data["msg"].data());
notifyInferiorSetupFailed(msg);
@@ -418,10 +414,10 @@ void GdbRemoteServerEngine::runEngine()
}
}
-void GdbRemoteServerEngine::handleExecRun(const GdbResponse &response)
+void GdbRemoteServerEngine::handleExecRun(const DebuggerResponse &response)
{
QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
- if (response.resultClass == GdbResultRunning) {
+ if (response.resultClass == ResultRunning) {
notifyEngineRunAndInferiorRunOk();
showMessage(_("INFERIOR STARTED"));
showMessage(msgInferiorSetupOk(), StatusBar);
@@ -438,7 +434,7 @@ void GdbRemoteServerEngine::interruptInferior2()
if (boolSetting(TargetAsync)) {
postCommand("-exec-interrupt", GdbEngine::Immediate,
CB(handleInterruptInferior));
- } else if (m_isQnxGdb && Utils::HostOsInfo::isWindowsHost()) {
+ } else if (m_isQnxGdb && HostOsInfo::isWindowsHost()) {
m_gdbProc->winInterruptByCtrlC();
} else {
bool ok = m_gdbProc->interrupt();
@@ -451,9 +447,9 @@ void GdbRemoteServerEngine::interruptInferior2()
}
}
-void GdbRemoteServerEngine::handleInterruptInferior(const GdbResponse &response)
+void GdbRemoteServerEngine::handleInterruptInferior(const DebuggerResponse &response)
{
- if (response.resultClass == GdbResultDone) {
+ if (response.resultClass == ResultDone) {
// The gdb server will trigger extra output that we will pick up
// to do a proper state transition.
} else {
diff --git a/src/plugins/debugger/gdb/remotegdbserveradapter.h b/src/plugins/debugger/gdb/remotegdbserveradapter.h
index 9966ac057fc..2b0c732d812 100644
--- a/src/plugins/debugger/gdb/remotegdbserveradapter.h
+++ b/src/plugins/debugger/gdb/remotegdbserveradapter.h
@@ -66,7 +66,6 @@ signals:
* a server start script should be used, but none is given.
*/
void requestSetup();
- void aboutToNotifyInferiorSetupOk();
private:
Q_SLOT void readUploadStandardOutput();
@@ -77,18 +76,17 @@ private:
void notifyEngineRemoteServerRunning(const QByteArray &serverChannel, int inferiorPid);
void notifyEngineRemoteSetupFinished(const RemoteSetupResult &result);
- void notifyInferiorSetupOk();
- void handleSetTargetAsync(const GdbResponse &response);
- void handleFileExecAndSymbols(const GdbResponse &response);
- void handleTargetRemote(const GdbResponse &response);
- void handleTargetExtendedRemote(const GdbResponse &response);
- void handleTargetExtendedAttach(const GdbResponse &response);
- void handleTargetQnx(const GdbResponse &response);
- void handleAttach(const GdbResponse &response);
- void handleSetNtoExecutable(const GdbResponse &response);
- void handleInterruptInferior(const GdbResponse &response);
- void handleExecRun(const GdbResponse &response);
+ void handleSetTargetAsync(const DebuggerResponse &response);
+ void handleFileExecAndSymbols(const DebuggerResponse &response);
+ void handleTargetRemote(const DebuggerResponse &response);
+ void handleTargetExtendedRemote(const DebuggerResponse &response);
+ void handleTargetExtendedAttach(const DebuggerResponse &response);
+ void handleTargetQnx(const DebuggerResponse &response);
+ void handleAttach(const DebuggerResponse &response);
+ void handleSetNtoExecutable(const DebuggerResponse &response);
+ void handleInterruptInferior(const DebuggerResponse &response);
+ void handleExecRun(const DebuggerResponse &response);
QProcess m_uploadProc;
bool m_startAttempted;
diff --git a/src/plugins/debugger/gdb/startgdbserverdialog.cpp b/src/plugins/debugger/gdb/startgdbserverdialog.cpp
index 6c224b5b6cc..346668ea19e 100644
--- a/src/plugins/debugger/gdb/startgdbserverdialog.cpp
+++ b/src/plugins/debugger/gdb/startgdbserverdialog.cpp
@@ -37,6 +37,7 @@
#include <debugger/debuggerstartparameters.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <projectexplorer/kitchooser.h>
#include <projectexplorer/devicesupport/deviceprocesslist.h>
#include <projectexplorer/devicesupport/deviceprocessesdialog.h>
@@ -45,7 +46,6 @@
#include <utils/portlist.h>
#include <utils/qtcassert.h>
-#include <QMessageBox>
#include <QFileInfo>
using namespace Core;
@@ -90,7 +90,7 @@ GdbServerStarter::~GdbServerStarter()
void GdbServerStarter::handleRemoteError(const QString &errorMsg)
{
- QMessageBox::critical(0, tr("Remote Error"), errorMsg);
+ AsynchronousMessageBox::critical(tr("Remote Error"), errorMsg);
}
void GdbServerStarter::portGathererError(const QString &text)
@@ -103,8 +103,10 @@ void GdbServerStarter::portGathererError(const QString &text)
void GdbServerStarter::run()
{
QTC_ASSERT(d->device, return);
- connect(&d->gatherer, SIGNAL(error(QString)), SLOT(portGathererError(QString)));
- connect(&d->gatherer, SIGNAL(portListReady()), SLOT(portListReady()));
+ connect(&d->gatherer, &DeviceUsedPortsGatherer::error,
+ this, &GdbServerStarter::portGathererError);
+ connect(&d->gatherer, &DeviceUsedPortsGatherer::portListReady,
+ this, &GdbServerStarter::portListReady);
d->gatherer.start(d->device);
}
@@ -118,11 +120,16 @@ void GdbServerStarter::portListReady()
return;
}
- connect(&d->runner, SIGNAL(connectionError()), SLOT(handleConnectionError()));
- connect(&d->runner, SIGNAL(processStarted()), SLOT(handleProcessStarted()));
- connect(&d->runner, SIGNAL(readyReadStandardOutput()), SLOT(handleProcessOutputAvailable()));
- connect(&d->runner, SIGNAL(readyReadStandardError()), SLOT(handleProcessErrorOutput()));
- connect(&d->runner, SIGNAL(processClosed(int)), SLOT(handleProcessClosed(int)));
+ connect(&d->runner, &SshRemoteProcessRunner::connectionError,
+ this, &GdbServerStarter::handleConnectionError);
+ connect(&d->runner, &SshRemoteProcessRunner::processStarted,
+ this, &GdbServerStarter::handleProcessStarted);
+ connect(&d->runner, &SshRemoteProcessRunner::readyReadStandardOutput,
+ this, &GdbServerStarter::handleProcessOutputAvailable);
+ connect(&d->runner, &SshRemoteProcessRunner::readyReadStandardError,
+ this, &GdbServerStarter::handleProcessErrorOutput);
+ connect(&d->runner, &SshRemoteProcessRunner::processClosed,
+ this, &GdbServerStarter::handleProcessClosed);
QByteArray gdbServerPath = d->device->debugServerPath().toUtf8();
if (gdbServerPath.isEmpty())
@@ -191,15 +198,15 @@ void GdbServerStarter::attach(int port)
localExecutable = candidate;
}
if (localExecutable.isEmpty()) {
- QMessageBox::warning(ICore::mainWindow(), tr("Warning"),
+ AsynchronousMessageBox::warning(tr("Warning"),
tr("Cannot find local executable for remote process \"%1\".")
.arg(d->process.exe));
return;
}
- QList<Abi> abis = Abi::abisOfBinary(Utils::FileName::fromString(localExecutable));
+ QList<Abi> abis = Abi::abisOfBinary(FileName::fromString(localExecutable));
if (abis.isEmpty()) {
- QMessageBox::warning(ICore::mainWindow(), tr("Warning"),
+ AsynchronousMessageBox::warning(tr("Warning"),
tr("Cannot find ABI for remote process \"%1\".")
.arg(d->process.exe));
return;
diff --git a/src/plugins/debugger/gdb/termgdbadapter.cpp b/src/plugins/debugger/gdb/termgdbadapter.cpp
index 33bf3a176e7..8a9b20355b4 100644
--- a/src/plugins/debugger/gdb/termgdbadapter.cpp
+++ b/src/plugins/debugger/gdb/termgdbadapter.cpp
@@ -39,18 +39,13 @@
#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <coreplugin/icore.h>
-
-#include <QMessageBox>
+#include <coreplugin/messagebox.h>
using namespace Utils;
namespace Debugger {
namespace Internal {
-#define CB(callback) \
- static_cast<GdbEngine::GdbCommandCallback>(&GdbTermEngine::callback), \
- STRINGIFY(callback)
-
///////////////////////////////////////////////////////////////////////
//
// TermGdbAdapter
@@ -63,11 +58,11 @@ GdbTermEngine::GdbTermEngine(const DebuggerStartParameters &startParameters)
#ifdef Q_OS_WIN
// Windows up to xp needs a workaround for attaching to freshly started processes. see proc_stub_win
if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)
- m_stubProc.setMode(Utils::ConsoleProcess::Suspend);
+ m_stubProc.setMode(ConsoleProcess::Suspend);
else
- m_stubProc.setMode(Utils::ConsoleProcess::Debug);
+ m_stubProc.setMode(ConsoleProcess::Debug);
#else
- m_stubProc.setMode(Utils::ConsoleProcess::Debug);
+ m_stubProc.setMode(ConsoleProcess::Debug);
m_stubProc.setSettings(Core::ICore::settings());
#endif
}
@@ -95,9 +90,12 @@ void GdbTermEngine::setupEngine()
// Set environment + dumper preload.
m_stubProc.setEnvironment(startParameters().environment);
- connect(&m_stubProc, SIGNAL(processError(QString)), SLOT(stubError(QString)));
- connect(&m_stubProc, SIGNAL(processStarted()), SLOT(stubStarted()));
- connect(&m_stubProc, SIGNAL(stubStopped()), SLOT(stubExited()));
+ connect(&m_stubProc, &ConsoleProcess::processError,
+ this, &GdbTermEngine::stubError);
+ connect(&m_stubProc, &ConsoleProcess::processStarted,
+ this, &GdbTermEngine::stubStarted);
+ connect(&m_stubProc, &ConsoleProcess::stubStopped,
+ this, &GdbTermEngine::stubExited);
// FIXME: Starting the stub implies starting the inferior. This is
// fairly unclean as far as the state machine and error reporting go.
@@ -136,17 +134,17 @@ void GdbTermEngine::runEngine()
{
QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
const qint64 attachedPID = m_stubProc.applicationPID();
- postCommand("attach " + QByteArray::number(attachedPID),
- CB(handleStubAttached));
+ postCommand("attach " + QByteArray::number(attachedPID), NoFlags,
+ [this](const DebuggerResponse &r) { handleStubAttached(r); });
}
-void GdbTermEngine::handleStubAttached(const GdbResponse &response)
+void GdbTermEngine::handleStubAttached(const DebuggerResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
switch (response.resultClass) {
- case GdbResultDone:
- case GdbResultRunning:
+ case ResultDone:
+ case ResultRunning:
if (startParameters().toolChainAbi.os() != ProjectExplorer::Abi::WindowsOS) {
showMessage(_("INFERIOR ATTACHED"));
} else {
@@ -165,7 +163,7 @@ void GdbTermEngine::handleStubAttached(const GdbResponse &response)
notifyEngineRunAndInferiorStopOk();
continueInferiorInternal();
break;
- case GdbResultError:
+ case ResultError:
if (response.data["msg"].data() == "ptrace: Operation not permitted.") {
showMessage(msgPtraceError(startParameters().startMode));
notifyEngineRunFailed();
@@ -188,7 +186,7 @@ void GdbTermEngine::interruptInferior2()
void GdbTermEngine::stubError(const QString &msg)
{
- showMessageBox(QMessageBox::Critical, tr("Debugger Error"), msg);
+ Core::AsynchronousMessageBox::critical(tr("Debugger Error"), msg);
}
void GdbTermEngine::stubExited()
diff --git a/src/plugins/debugger/gdb/termgdbadapter.h b/src/plugins/debugger/gdb/termgdbadapter.h
index 6af88b39a15..2ffebbabb07 100644
--- a/src/plugins/debugger/gdb/termgdbadapter.h
+++ b/src/plugins/debugger/gdb/termgdbadapter.h
@@ -60,7 +60,7 @@ private:
void interruptInferior2();
void shutdownEngine();
- void handleStubAttached(const GdbResponse &response);
+ void handleStubAttached(const DebuggerResponse &response);
Q_SLOT void stubStarted();
Q_SLOT void stubExited();
diff --git a/src/plugins/debugger/imageviewer.cpp b/src/plugins/debugger/imageviewer.cpp
index 21c3501ea3c..26015f9fc68 100644
--- a/src/plugins/debugger/imageviewer.cpp
+++ b/src/plugins/debugger/imageviewer.cpp
@@ -104,11 +104,11 @@ ImageViewer::ImageViewer(QWidget *parent)
, m_imageWidget(new ImageWidget)
, m_infoLabel(new QLabel)
{
- QVBoxLayout *mainLayout = new QVBoxLayout(this);
+ auto mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(m_infoLabel);
mainLayout->addWidget(m_scrollArea);
m_scrollArea->setWidget(m_imageWidget);
- connect(m_imageWidget, SIGNAL(clicked(QString)), this, SLOT(clicked(QString)));
+ connect(m_imageWidget, &ImageWidget::clicked, this, &ImageViewer::clicked);
}
void ImageViewer::setImage(const QImage &i)
diff --git a/src/plugins/debugger/lldb/lldbengine.cpp b/src/plugins/debugger/lldb/lldbengine.cpp
index 5fb75784fa7..359403bfa4d 100644
--- a/src/plugins/debugger/lldb/lldbengine.cpp
+++ b/src/plugins/debugger/lldb/lldbengine.cpp
@@ -50,25 +50,26 @@
#include <debugger/watchhandler.h>
#include <debugger/watchutils.h>
+#include <coreplugin/messagebox.h>
+#include <coreplugin/idocument.h>
+#include <coreplugin/icore.h>
+
+#include <texteditor/texteditor.h>
+
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
#include <utils/qtcprocess.h>
-#include <texteditor/texteditor.h>
-#include <coreplugin/idocument.h>
-#include <coreplugin/icore.h>
-
+#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QTimer>
-#include <QVariant>
-
-#include <QApplication>
-#include <QMessageBox>
#include <QToolTip>
+#include <QVariant>
+using namespace Core;
using namespace Utils;
namespace Debugger {
@@ -91,25 +92,25 @@ LldbEngine::LldbEngine(const DebuggerStartParameters &startParameters)
#ifdef Q_OS_WIN
// Windows up to xp needs a workaround for attaching to freshly started processes. see proc_stub_win
if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)
- m_stubProc.setMode(Utils::ConsoleProcess::Suspend);
+ m_stubProc.setMode(ConsoleProcess::Suspend);
else
- m_stubProc.setMode(Utils::ConsoleProcess::Debug);
+ m_stubProc.setMode(ConsoleProcess::Debug);
#else
- m_stubProc.setMode(Utils::ConsoleProcess::Debug);
- m_stubProc.setSettings(Core::ICore::settings());
+ m_stubProc.setMode(ConsoleProcess::Debug);
+ m_stubProc.setSettings(ICore::settings());
#endif
}
- connect(action(AutoDerefPointers), SIGNAL(valueChanged(QVariant)),
- SLOT(updateLocals()));
- connect(action(CreateFullBacktrace), SIGNAL(triggered()),
- SLOT(createFullBacktrace()));
- connect(action(UseDebuggingHelpers), SIGNAL(valueChanged(QVariant)),
- SLOT(updateLocals()));
- connect(action(UseDynamicType), SIGNAL(valueChanged(QVariant)),
- SLOT(updateLocals()));
- connect(action(IntelFlavor), SIGNAL(valueChanged(QVariant)),
- SLOT(updateAll()));
+ connect(action(AutoDerefPointers), &SavedAction::valueChanged,
+ this, &LldbEngine::updateLocals);
+ connect(action(CreateFullBacktrace), &QAction::triggered,
+ this, &LldbEngine::createFullBacktrace);
+ connect(action(UseDebuggingHelpers), &SavedAction::valueChanged,
+ this, &LldbEngine::updateLocals);
+ connect(action(UseDynamicType), &SavedAction::valueChanged,
+ this, &LldbEngine::updateLocals);
+ connect(action(IntelFlavor), &SavedAction::valueChanged,
+ this, &LldbEngine::updateAll);
}
LldbEngine::~LldbEngine()
@@ -120,18 +121,19 @@ LldbEngine::~LldbEngine()
void LldbEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages)
{
- runCommand(Command("executeDebuggerCommand").arg("command", command));
+ DebuggerCommand cmd("executeDebuggerCommand");
+ cmd.arg("command", command);
+ runCommand(cmd);
}
-void LldbEngine::runCommand(const Command &command)
+void LldbEngine::runCommand(const DebuggerCommand &command)
{
QTC_ASSERT(m_lldbProc.state() == QProcess::Running, notifyEngineIll());
++m_lastToken;
QByteArray token = QByteArray::number(m_lastToken);
- QByteArray cmd = "{\"cmd\":\"" + command.function + "\","
- + command.args + "\"token\":" + token + "}\n";
- showMessage(_(token + cmd), LogInput);
- m_lldbProc.write(cmd);
+ QByteArray cmd = command.function + "({" + command.args + "})";
+ showMessage(_(token + cmd + '\n'), LogInput);
+ m_lldbProc.write("sc db." + cmd + "\n");
}
void LldbEngine::debugLastCommand()
@@ -142,7 +144,7 @@ void LldbEngine::debugLastCommand()
void LldbEngine::shutdownInferior()
{
QTC_ASSERT(state() == InferiorShutdownRequested, qDebug() << state());
- runCommand(Command("shutdownInferior"));
+ runCommand(DebuggerCommand("shutdownInferior"));
}
void LldbEngine::shutdownEngine()
@@ -174,9 +176,9 @@ bool LldbEngine::prepareCommand()
DebuggerStartParameters &sp = startParameters();
QtcProcess::SplitError perr;
sp.processArgs = QtcProcess::prepareArgs(sp.processArgs, &perr,
- Utils::HostOsInfo::hostOs(),
+ HostOsInfo::hostOs(),
&sp.environment, &sp.workingDirectory).toWindowsArgs();
- if (perr != Utils::QtcProcess::SplitOk) {
+ if (perr != QtcProcess::SplitOk) {
// perr == BadQuoting is never returned on Windows
// FIXME? QTCREATORBUG-2809
notifyEngineSetupFailed();
@@ -207,9 +209,9 @@ void LldbEngine::setupEngine()
// Set environment + dumper preload.
m_stubProc.setEnvironment(startParameters().environment);
- connect(&m_stubProc, SIGNAL(processError(QString)), SLOT(stubError(QString)));
- connect(&m_stubProc, SIGNAL(processStarted()), SLOT(stubStarted()));
- connect(&m_stubProc, SIGNAL(stubStopped()), SLOT(stubExited()));
+ connect(&m_stubProc, &ConsoleProcess::processError, this, &LldbEngine::stubError);
+ connect(&m_stubProc, &ConsoleProcess::processStarted, this, &LldbEngine::stubStarted);
+ connect(&m_stubProc, &ConsoleProcess::stubStopped, this, &LldbEngine::stubExited);
// FIXME: Starting the stub implies starting the inferior. This is
// fairly unclean as far as the state machine and error reporting go.
@@ -233,28 +235,24 @@ void LldbEngine::setupEngine()
void LldbEngine::startLldb()
{
m_lldbCmd = startParameters().debuggerCommand;
- connect(&m_lldbProc, SIGNAL(error(QProcess::ProcessError)),
- SLOT(handleLldbError(QProcess::ProcessError)));
- connect(&m_lldbProc, SIGNAL(finished(int,QProcess::ExitStatus)),
- SLOT(handleLldbFinished(int,QProcess::ExitStatus)));
- connect(&m_lldbProc, SIGNAL(readyReadStandardOutput()),
- SLOT(readLldbStandardOutput()));
- connect(&m_lldbProc, SIGNAL(readyReadStandardError()),
- SLOT(readLldbStandardError()));
-
- connect(this, SIGNAL(outputReady(QByteArray)),
- SLOT(handleResponse(QByteArray)), Qt::QueuedConnection);
-
- QStringList args;
- args.append(_("-i"));
- args.append(Core::ICore::resourcePath() + _("/debugger/lldbbridge.py"));
- args.append(m_lldbCmd);
- showMessage(_("STARTING LLDB: python ") + args.join(QLatin1Char(' ')));
+ connect(&m_lldbProc, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
+ this, &LldbEngine::handleLldbError);
+ connect(&m_lldbProc, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
+ this, &LldbEngine::handleLldbFinished);
+ connect(&m_lldbProc, &QProcess::readyReadStandardOutput,
+ this, &LldbEngine::readLldbStandardOutput);
+ connect(&m_lldbProc, &QProcess::readyReadStandardError,
+ this, &LldbEngine::readLldbStandardError);
+
+ connect(this, &LldbEngine::outputReady,
+ this, &LldbEngine::handleResponse, Qt::QueuedConnection);
+
+ showMessage(_("STARTING LLDB: ") + m_lldbCmd);
m_lldbProc.setEnvironment(startParameters().environment.toStringList());
if (!startParameters().workingDirectory.isEmpty())
m_lldbProc.setWorkingDirectory(startParameters().workingDirectory);
- m_lldbProc.start(_("python"), args);
+ m_lldbProc.start(m_lldbCmd);
if (!m_lldbProc.waitForStarted()) {
const QString msg = tr("Unable to start LLDB \"%1\": %2")
@@ -262,8 +260,23 @@ void LldbEngine::startLldb()
notifyEngineSetupFailed();
showMessage(_("ADAPTER START FAILED"));
if (!msg.isEmpty())
- Core::ICore::showWarningWithOptions(tr("Adapter start failed."), msg);
+ ICore::showWarningWithOptions(tr("Adapter start failed."), msg);
}
+
+ showMessage(_("ADAPTER STARTED"));
+ showStatusMessage(tr("Setting up inferior..."));
+
+ const QByteArray dumperSourcePath =
+ ICore::resourcePath().toLocal8Bit() + "/debugger/";
+
+ m_lldbProc.write("sc sys.path.insert(1, '" + dumperSourcePath + "')\n");
+ m_lldbProc.write("sc from lldbbridge import *\n");
+ m_lldbProc.write("sc print(dir())\n");
+ m_lldbProc.write("sc db = Dumper()\n");
+ m_lldbProc.write("sc db.report('lldbversion=\"%s\"' % lldb.SBDebugger.GetVersionString())\n");
+
+ showMessage(_("ENGINE SUCCESSFULLY STARTED"));
+ notifyEngineSetupOk();
}
void LldbEngine::setupInferior()
@@ -272,35 +285,48 @@ void LldbEngine::setupInferior()
const QString path = stringSetting(ExtraDumperFile);
if (!path.isEmpty()) {
- QFileInfo fi(path);
-
- Command cmd1("executeDebuggerCommand");
- cmd1.arg("command", "python sys.path.insert(1, '" + fi.absolutePath().toUtf8() + "')");
- runCommand(cmd1);
-
- Command cmd2("executeDebuggerCommand");
- cmd2.arg("python from " + fi.baseName().toUtf8() + " import *");
- runCommand(cmd2);
+ DebuggerCommand cmd("addDumperModule");
+ cmd.arg("path", path.toUtf8());
+ runCommand(cmd);
}
const QString commands = stringSetting(ExtraDumperCommands);
if (!commands.isEmpty()) {
- Command cmd("executeDebuggerCommand");
- cmd.arg(commands.toUtf8());
+ DebuggerCommand cmd("executeDebuggerCommand");
+ cmd.arg("commands", commands.toUtf8());
runCommand(cmd);
}
+ DebuggerCommand cmd1("loadDumperFiles");
+ runCommand(cmd1);
+
QString executable;
- Utils::QtcProcess::Arguments args;
- Utils::QtcProcess::prepareCommand(QFileInfo(sp.executable).absoluteFilePath(),
- sp.processArgs, &executable, &args);
+ QtcProcess::Arguments args;
+ QtcProcess::prepareCommand(QFileInfo(sp.executable).absoluteFilePath(),
+ sp.processArgs, &executable, &args);
- Command cmd("setupInferior");
+ DebuggerCommand cmd("setupInferior");
cmd.arg("executable", executable);
cmd.arg("breakOnMain", sp.breakOnMain);
cmd.arg("useTerminal", sp.useTerminal);
cmd.arg("startMode", sp.startMode);
+ cmd.beginList("bkpts");
+ foreach (Breakpoint bp, breakHandler()->unclaimedBreakpoints()) {
+ if (acceptsBreakpoint(bp)) {
+ showMessage(_("TAKING OWNERSHIP OF BREAKPOINT %1 IN STATE %2")
+ .arg(bp.id().toString()).arg(bp.state()));
+ bp.setEngine(this);
+ cmd.beginGroup();
+ bp.addToCommand(&cmd);
+ cmd.endGroup();
+ } else {
+ showMessage(_("BREAKPOINT %1 IN STATE %2 IS NOT ACCEPTABLE")
+ .arg(bp.id().toString()).arg(bp.state()));
+ }
+ }
+ cmd.endList();
+
cmd.beginList("processArgs");
foreach (const QString &arg, args.toUnixArgs())
cmd.arg(arg.toUtf8().toHex());
@@ -340,19 +366,7 @@ void LldbEngine::setupInferior()
void LldbEngine::runEngine()
{
- QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
-
- Command cmd("handleBreakpoints");
- if (attemptBreakpointSynchronizationHelper(&cmd)) {
- runEngine2();
- } else {
- cmd.arg("continuation", "runEngine2");
- runCommand(cmd);
- }
-}
-
-void LldbEngine::runEngine2()
-{
+ QTC_ASSERT(state() == EngineRunRequested, qDebug() << state(); return);
showStatusMessage(tr("Running requested..."), 5000);
runCommand("runEngine");
}
@@ -414,6 +428,8 @@ void LldbEngine::handleResponse(const QByteArray &response)
const QByteArray name = item.name();
if (name == "data")
refreshLocals(item);
+ else if (name == "dumpers")
+ watchHandler()->addDumpers(item);
else if (name == "stack")
refreshStack(item);
else if (name == "stack-position")
@@ -446,8 +462,6 @@ void LldbEngine::handleResponse(const QByteArray &response)
refreshDisassembly(item);
else if (name == "memory")
refreshMemory(item);
- else if (name == "continuation")
- runContinuation(item);
else if (name == "full-backtrace")
showFullBacktrace(item);
else if (name == "statusmessage") {
@@ -465,17 +479,11 @@ void LldbEngine::showFullBacktrace(const GdbMi &data)
QString::fromUtf8(QByteArray::fromHex(data.data())));
}
-void LldbEngine::runContinuation(const GdbMi &data)
-{
- const QByteArray target = data.data();
- QMetaObject::invokeMethod(this, target, Qt::QueuedConnection);
-}
-
void LldbEngine::executeRunToLine(const ContextData &data)
{
resetLocation();
notifyInferiorRunRequested();
- Command cmd("executeRunToLocation");
+ DebuggerCommand cmd("executeRunToLocation");
cmd.arg("file", data.fileName);
cmd.arg("line", data.lineNumber);
cmd.arg("address", data.address);
@@ -486,14 +494,16 @@ void LldbEngine::executeRunToFunction(const QString &functionName)
{
resetLocation();
notifyInferiorRunRequested();
- runCommand(Command("executeRunToFunction").arg("function", functionName));
+ DebuggerCommand cmd("executeRunToFunction");
+ cmd.arg("function", functionName);
+ runCommand(cmd);
}
void LldbEngine::executeJumpToLine(const ContextData &data)
{
resetLocation();
notifyInferiorRunRequested();
- Command cmd("executeJumpToLocation");
+ DebuggerCommand cmd("executeJumpToLocation");
cmd.arg("file", data.fileName);
cmd.arg("line", data.lineNumber);
cmd.arg("address", data.address);
@@ -508,13 +518,14 @@ void LldbEngine::activateFrame(int frameIndex)
const int n = stackHandler()->stackSize();
if (frameIndex == n) {
- Command cmd("reportStack");
+ DebuggerCommand cmd("reportStack");
+ cmd.arg("nativeMixed", isNativeMixedActive());
cmd.arg("stacklimit", n * 10 + 3);
runCommand(cmd);
return;
}
- Command cmd("activateFrame");
+ DebuggerCommand cmd("activateFrame");
cmd.arg("index", frameIndex);
cmd.arg("thread", threadsHandler()->currentThread().raw());
runCommand(cmd);
@@ -525,117 +536,61 @@ void LldbEngine::activateFrame(int frameIndex)
void LldbEngine::selectThread(ThreadId threadId)
{
- runCommand(Command("selectThread").arg("id", threadId.raw()));
+ DebuggerCommand cmd("selectThread");
+ cmd.arg("id", threadId.raw());
+ runCommand(cmd);
}
-bool LldbEngine::acceptsBreakpoint(BreakpointModelId id) const
+bool LldbEngine::stateAcceptsBreakpointChanges() const
{
- return breakHandler()->breakpointData(id).isCppBreakpoint()
- && startParameters().startMode != AttachCore;
+ switch (state()) {
+ case InferiorSetupRequested:
+ case InferiorRunRequested:
+ case InferiorRunOk:
+ case InferiorStopRequested:
+ case InferiorStopOk:
+ return true;
+ default:
+ return false;
+ }
}
-bool LldbEngine::attemptBreakpointSynchronizationHelper(Command *cmd)
+bool LldbEngine::acceptsBreakpoint(Breakpoint bp) const
{
- BreakHandler *handler = breakHandler();
-
- foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
- // Take ownership of the breakpoint. Requests insertion.
- if (acceptsBreakpoint(id)) {
- showMessage(_("TAKING OWNERSHIP OF BREAKPOINT %1 IN STATE %2")
- .arg(id.toString()).arg(handler->state(id)));
- handler->setEngine(id, this);
- } else {
- showMessage(_("BREAKPOINT %1 IN STATE %2 IS NOT ACCEPTABLE")
- .arg(id.toString()).arg(handler->state(id)));
- }
- }
+ if (startParameters().startMode == AttachCore)
+ return false;
+ // We handle QML breakpoint unless specifically disabled.
+ if (isNativeMixedEnabled() && !(startParameters().languages & QmlLanguage))
+ return true;
+ return bp.parameters().isCppBreakpoint();
+}
- bool done = true;
- cmd->beginList("bkpts");
- foreach (BreakpointModelId id, handler->engineBreakpointIds(this)) {
- const BreakpointResponse &response = handler->response(id);
- const BreakpointState bpState = handler->state(id);
- switch (bpState) {
- case BreakpointNew:
- // Should not happen once claimed.
- QTC_CHECK(false);
- break;
- case BreakpointInsertRequested:
- done = false;
- cmd->beginGroup()
- .arg("operation", "add")
- .arg("modelid", id.toByteArray())
- .arg("type", handler->type(id))
- .arg("ignorecount", handler->ignoreCount(id))
- .arg("condition", handler->condition(id).toHex())
- .arg("function", handler->functionName(id).toUtf8())
- .arg("oneshot", handler->isOneShot(id))
- .arg("enabled", handler->isEnabled(id))
- .arg("file", handler->fileName(id).toUtf8())
- .arg("line", handler->lineNumber(id))
- .arg("address", handler->address(id))
- .arg("expression", handler->expression(id))
- .endGroup();
- handler->notifyBreakpointInsertProceeding(id);
- break;
- case BreakpointChangeRequested:
- done = false;
- cmd->beginGroup()
- .arg("operation", "change")
- .arg("modelid", id.toByteArray())
- .arg("lldbid", response.id.toByteArray())
- .arg("type", handler->type(id))
- .arg("ignorecount", handler->ignoreCount(id))
- .arg("condition", handler->condition(id).toHex())
- .arg("function", handler->functionName(id).toUtf8())
- .arg("oneshot", handler->isOneShot(id))
- .arg("enabled", handler->isEnabled(id))
- .arg("file", handler->fileName(id).toUtf8())
- .arg("line", handler->lineNumber(id))
- .arg("address", handler->address(id))
- .arg("expression", handler->expression(id))
- .endGroup();
- handler->notifyBreakpointChangeProceeding(id);
- break;
- case BreakpointRemoveRequested:
- done = false;
- cmd->beginGroup()
- .arg("operation", "remove")
- .arg("modelid", id.toByteArray())
- .arg("lldbid", response.id.toByteArray())
- .endGroup();
- handler->notifyBreakpointRemoveProceeding(id);
- break;
- case BreakpointChangeProceeding:
- case BreakpointInsertProceeding:
- case BreakpointRemoveProceeding:
- case BreakpointInserted:
- case BreakpointDead:
- QTC_ASSERT(false, qDebug() << "UNEXPECTED STATE" << bpState << "FOR BP " << id);
- break;
- default:
- QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << bpState << "FOR BP" << id);
- }
- }
- cmd->endList();
- return done;
+void LldbEngine::insertBreakpoint(Breakpoint bp)
+{
+ DebuggerCommand cmd("insertBreakpoint");
+ bp.addToCommand(&cmd);
+ bp.notifyBreakpointInsertProceeding();
+ runCommand(cmd);
}
-void LldbEngine::attemptBreakpointSynchronization()
+void LldbEngine::changeBreakpoint(Breakpoint bp)
{
- showMessage(_("ATTEMPT BREAKPOINT SYNCHRONIZATION"));
- if (!stateAcceptsBreakpointChanges()) {
- showMessage(_("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE"));
- return;
- }
+ const BreakpointResponse &response = bp.response();
+ DebuggerCommand cmd("changeBreakpoint");
+ cmd.arg("lldbid", response.id.toByteArray());
+ bp.addToCommand(&cmd);
+ bp.notifyBreakpointChangeProceeding();
+ runCommand(cmd);
+}
- Command cmd("handleBreakpoints");
- if (!attemptBreakpointSynchronizationHelper(&cmd)) {
- showMessage(_("BREAKPOINTS ARE NOT FULLY SYNCHRONIZED"));
- runCommand(cmd);
- } else {
- showMessage(_("BREAKPOINTS ARE SYNCHRONIZED"));
- }
+void LldbEngine::removeBreakpoint(Breakpoint bp)
+{
+ const BreakpointResponse &response = bp.response();
+ DebuggerCommand cmd("removeBreakpoint");
+ cmd.arg("modelid", bp.id().toByteArray());
+ cmd.arg("lldbid", response.id.toByteArray());
+ bp.notifyBreakpointRemoveProceeding();
+ runCommand(cmd);
}
void LldbEngine::updateBreakpointData(const GdbMi &bkpt, bool added)
@@ -643,9 +598,10 @@ void LldbEngine::updateBreakpointData(const GdbMi &bkpt, bool added)
BreakHandler *handler = breakHandler();
BreakpointResponseId rid = BreakpointResponseId(bkpt["lldbid"].data());
BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
- if (!id.isValid())
- id = handler->findBreakpointByResponseId(rid);
- BreakpointResponse response = handler->response(id);
+ Breakpoint bp = handler->breakpointById(id);
+ if (!bp.isValid())
+ bp = handler->findBreakpointByResponseId(rid);
+ BreakpointResponse response = bp.response();
if (added)
response.id = rid;
QTC_CHECK(response.id == rid);
@@ -669,7 +625,7 @@ void LldbEngine::updateBreakpointData(const GdbMi &bkpt, bool added)
sub.functionName = location["func"].toUtf8();
sub.fileName = location["file"].toUtf8();
sub.lineNumber = location["line"].toInt();
- handler->insertSubBreakpoint(id, sub);
+ bp.insertSubBreakpoint(sub);
}
} else if (numChild == 1) {
const GdbMi location = locations.childAt(0);
@@ -679,11 +635,11 @@ void LldbEngine::updateBreakpointData(const GdbMi &bkpt, bool added)
// This can happen for pending breakpoints.
showMessage(_("NO LOCATIONS (YET) FOR BP %1").arg(response.toString()));
}
- handler->setResponse(id, response);
+ bp.setResponse(response);
if (added)
- handler->notifyBreakpointInsertOk(id);
+ bp.notifyBreakpointInsertOk();
else
- handler->notifyBreakpointChangeOk(id);
+ bp.notifyBreakpointChangeOk();
}
void LldbEngine::refreshDisassembly(const GdbMi &data)
@@ -736,23 +692,25 @@ void LldbEngine::refreshOutput(const GdbMi &output)
void LldbEngine::refreshAddedBreakpoint(const GdbMi &bkpt)
{
BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
- QTC_CHECK(breakHandler()->state(id) == BreakpointInsertProceeding);
+ Breakpoint bp = breakHandler()->breakpointById(id);
+ QTC_CHECK(bp.state() == BreakpointInsertProceeding);
updateBreakpointData(bkpt, true);
}
void LldbEngine::refreshChangedBreakpoint(const GdbMi &bkpt)
{
BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
- QTC_CHECK(!id.isValid() || breakHandler()->state(id) == BreakpointChangeProceeding);
+ Breakpoint bp = breakHandler()->breakpointById(id);
+ QTC_CHECK(!bp.isValid() || bp.state() == BreakpointChangeProceeding);
updateBreakpointData(bkpt, false);
}
void LldbEngine::refreshRemovedBreakpoint(const GdbMi &bkpt)
{
- BreakHandler *handler = breakHandler();
BreakpointModelId id = BreakpointModelId(bkpt["modelid"].data());
- QTC_CHECK(handler->state(id) == BreakpointRemoveProceeding);
- handler->notifyBreakpointRemoveOk(id);
+ Breakpoint bp = breakHandler()->breakpointById(id);
+ QTC_CHECK(bp.state() == BreakpointRemoveProceeding);
+ bp.notifyBreakpointRemoveOk();
}
void LldbEngine::loadSymbols(const QString &moduleName)
@@ -771,7 +729,8 @@ void LldbEngine::reloadModules()
void LldbEngine::refreshModules(const GdbMi &modules)
{
- Modules mods;
+ ModulesHandler *handler = modulesHandler();
+ handler->beginUpdateAll();
foreach (const GdbMi &item, modules.children()) {
Module module;
module.modulePath = item["file"].toUtf8();
@@ -779,14 +738,16 @@ void LldbEngine::refreshModules(const GdbMi &modules)
module.symbolsRead = Module::UnknownReadState;
module.startAddress = item["loaded_addr"].toAddress();
module.endAddress = 0; // FIXME: End address not easily available.
- mods.append(module);
+ handler->updateModule(module);
}
- modulesHandler()->setModules(mods);
+ handler->endUpdateAll();
}
void LldbEngine::requestModuleSymbols(const QString &moduleName)
{
- runCommand(Command("listSymbols").arg("module", moduleName));
+ DebuggerCommand cmd("listSymbols");
+ cmd.arg("module", moduleName);
+ runCommand(cmd);
}
void LldbEngine::refreshSymbols(const GdbMi &symbols)
@@ -827,8 +788,6 @@ bool LldbEngine::setToolTipExpression(TextEditor::TextEditorWidget *editorWidget
UpdateParameters params;
params.tryPartial = true;
- params.tooltipOnly = true;
- params.tooltipExpression = context.expression;
params.varList = context.iname;
doUpdateLocals(params);
@@ -844,14 +803,16 @@ void LldbEngine::updateAll()
void LldbEngine::reloadFullStack()
{
- Command cmd("reportStack");
+ DebuggerCommand cmd("reportStack");
+ cmd.arg("nativeMixed", isNativeMixedActive());
cmd.arg("stacklimit", -1);
runCommand(cmd);
}
void LldbEngine::updateStack()
{
- Command cmd("reportStack");
+ DebuggerCommand cmd("reportStack");
+ cmd.arg("nativeMixed", isNativeMixedActive());
cmd.arg("stacklimit", action(MaximalStackDepth)->value().toInt());
runCommand(cmd);
}
@@ -866,7 +827,7 @@ void LldbEngine::assignValueInDebugger(const Internal::WatchData *data,
const QString &expression, const QVariant &value)
{
Q_UNUSED(data);
- Command cmd("assignValue");
+ DebuggerCommand cmd("assignValue");
cmd.arg("exp", expression.toLatin1().toHex());
cmd.arg("value", value.toString().toLatin1().toHex());
runCommand(cmd);
@@ -887,12 +848,9 @@ void LldbEngine::updateLocals()
void LldbEngine::doUpdateLocals(UpdateParameters params)
{
- WatchHandler *handler = watchHandler();
-
- Command cmd("updateData");
- cmd.arg("expanded", handler->expansionRequests());
- cmd.arg("typeformats", handler->typeFormatRequests());
- cmd.arg("formats", handler->individualFormatRequests());
+ DebuggerCommand cmd("updateData");
+ cmd.arg("nativeMixed", isNativeMixedActive());
+ watchHandler()->appendFormatRequests(&cmd);
const static bool alwaysVerbose = !qgetenv("QTC_DEBUGGER_PYTHON_VERBOSE").isEmpty();
cmd.arg("passexceptions", alwaysVerbose);
@@ -900,7 +858,6 @@ void LldbEngine::doUpdateLocals(UpdateParameters params)
cmd.arg("autoderef", boolSetting(AutoDerefPointers));
cmd.arg("dyntype", boolSetting(UseDynamicType));
cmd.arg("partial", params.tryPartial);
- cmd.arg("tooltiponly", params.tooltipOnly);
cmd.beginList("watchers");
@@ -908,19 +865,19 @@ void LldbEngine::doUpdateLocals(UpdateParameters params)
QHashIterator<QByteArray, int> it(WatchHandler::watcherNames());
while (it.hasNext()) {
it.next();
- cmd.beginGroup()
- .arg("iname", "watch." + QByteArray::number(it.value()))
- .arg("exp", it.key().toHex())
- .endGroup();
+ cmd.beginGroup();
+ cmd.arg("iname", "watch." + QByteArray::number(it.value()));
+ cmd.arg("exp", it.key().toHex());
+ cmd.endGroup();
}
// Tooltips
DebuggerToolTipContexts toolTips = DebuggerToolTipManager::pendingTooltips(this);
foreach (const DebuggerToolTipContext &p, toolTips) {
- cmd.beginGroup()
- .arg("iname", p.iname)
- .arg("exp", p.expression.toLatin1().toHex())
- .endGroup();
+ cmd.beginGroup();
+ cmd.arg("iname", p.iname);
+ cmd.arg("exp", p.expression.toLatin1().toHex());
+ cmd.endGroup();
}
cmd.endList();
@@ -949,8 +906,7 @@ void LldbEngine::handleLldbError(QProcess::ProcessError error)
default:
//setState(EngineShutdownRequested, true);
m_lldbProc.kill();
- showMessageBox(QMessageBox::Critical, tr("LLDB I/O Error"),
- errorMessage(error));
+ AsynchronousMessageBox::critical(tr("LLDB I/O Error"), errorMessage(error));
break;
}
}
@@ -1016,29 +972,18 @@ void LldbEngine::refreshLocals(const GdbMi &vars)
//const bool partial = response.cookie.toBool();
WatchHandler *handler = watchHandler();
handler->resetValueCache();
- QList<WatchData> list;
- //if (!partial) {
- list.append(*handler->findData("local"));
- list.append(*handler->findData("watch"));
- list.append(*handler->findData("tooltip"));
- list.append(*handler->findData("return"));
- //}
+ QSet<QByteArray> toDelete;
+ foreach (WatchItem *item, handler->model()->treeLevelItems<WatchItem *>(2))
+ toDelete.insert(item->d.iname);
foreach (const GdbMi &child, vars.children()) {
- WatchData dummy;
- dummy.iname = child["iname"].data();
- GdbMi wname = child["wname"];
- if (wname.isValid()) {
- // Happens (only) for watched expressions.
- dummy.exp = QByteArray::fromHex(wname.data());
- dummy.name = QString::fromUtf8(dummy.exp);
- } else {
- dummy.name = child["name"].toUtf8();
- }
- parseWatchData(handler->expandedINames(), dummy, child, &list);
+ WatchItem *item = new WatchItem(child);
+ handler->insertItem(item);
+ toDelete.remove(item->d.iname);
}
- handler->insertData(list);
+
+ handler->purgeOutdatedItems(toDelete);
DebuggerToolTipManager::updateEngine(this);
}
@@ -1055,7 +1000,17 @@ void LldbEngine::refreshStack(const GdbMi &stack)
frame.from = item["func"].toUtf8();
frame.line = item["line"].toInt();
frame.address = item["addr"].toAddress();
- frame.usable = QFileInfo(frame.file).isReadable();
+ GdbMi usable = item["usable"];
+ if (usable.isValid())
+ frame.usable = usable.data().toInt();
+ else
+ frame.usable = QFileInfo(frame.file).isReadable();
+ if (item["language"].data() == "js"
+ || frame.file.endsWith(QLatin1String(".js"))
+ || frame.file.endsWith(QLatin1String(".qml"))) {
+ frame.language = QmlLanguage;
+ frame.fixQmlFrame(startParameters());
+ }
frames.append(frame);
}
bool canExpand = stack["hasmore"].toInt();
@@ -1085,16 +1040,15 @@ void LldbEngine::setStackPosition(int index)
void LldbEngine::refreshRegisters(const GdbMi &registers)
{
RegisterHandler *handler = registerHandler();
- Registers regs;
foreach (const GdbMi &item, registers.children()) {
Register reg;
reg.name = item["name"].data();
reg.value = item["value"].data();
- //reg.type = item["type"].data();
- regs.append(reg);
+ reg.size = item["size"].data().toInt();
+ reg.reportedType = item["type"].data();
+ handler->updateRegister(reg);
}
- //handler->setRegisters(registers);
- handler->setAndMarkRegisters(regs);
+ handler->commitUpdates();
}
void LldbEngine::refreshThreads(const GdbMi &threads)
@@ -1205,7 +1159,7 @@ void LldbEngine::fetchDisassembler(DisassemblerAgent *agent)
m_disassemblerAgents.insert(p, id);
}
const Location &loc = agent->location();
- Command cmd("disassemble");
+ DebuggerCommand cmd("disassemble");
cmd.arg("cookie", id);
cmd.arg("address", loc.address());
cmd.arg("function", loc.functionName());
@@ -1227,7 +1181,7 @@ void LldbEngine::fetchMemory(MemoryAgent *agent, QObject *editorToken,
m_memoryAgents.insert(agent, id);
}
m_memoryAgentTokens.insert(id, editorToken);
- Command cmd("fetchMemory");
+ DebuggerCommand cmd("fetchMemory");
cmd.arg("address", addr);
cmd.arg("length", length);
cmd.arg("cookie", id);
@@ -1243,20 +1197,21 @@ void LldbEngine::changeMemory(MemoryAgent *agent, QObject *editorToken,
m_memoryAgents.insert(agent, id);
m_memoryAgentTokens.insert(id, editorToken);
}
- Command cmd("writeMemory");
+ DebuggerCommand cmd("writeMemory");
cmd.arg("address", addr);
cmd.arg("data", data.toHex());
cmd.arg("cookie", id);
runCommand(cmd);
}
-void LldbEngine::setRegisterValue(int regnr, const QString &value)
+void LldbEngine::setRegisterValue(const QByteArray &name, const QString &value)
{
- Register reg = registerHandler()->registers().at(regnr);
- runCommand(Command("setRegister").arg("name", reg.name).arg("value", value));
+ DebuggerCommand cmd("setRegister");
+ cmd.arg("name", name);
+ cmd.arg("value", value);
+ runCommand(cmd);
}
-
bool LldbEngine::hasCapability(unsigned cap) const
{
if (cap & (ReverseSteppingCapability
@@ -1308,132 +1263,13 @@ void LldbEngine::notifyEngineRemoteSetupFinished(const RemoteSetupResult &result
showMessage(_("ADAPTER START FAILED"));
if (!result.reason.isEmpty()) {
const QString title = tr("Adapter start failed");
- Core::ICore::showWarningWithOptions(title, result.reason);
+ ICore::showWarningWithOptions(title, result.reason);
}
notifyEngineSetupFailed();
return;
}
}
-///////////////////////////////////////////////////////////////////////
-//
-// Command
-//
-///////////////////////////////////////////////////////////////////////
-
-const LldbEngine::Command &LldbEngine::Command::argHelper(const char *name, const QByteArray &data) const
-{
- args.append('"');
- args.append(name);
- args.append("\":");
- args.append(data);
- args.append(",");
- return *this;
-}
-
-QByteArray LldbEngine::Command::toData(const QList<QByteArray> &value)
-{
- QByteArray res;
- foreach (const QByteArray &item, value) {
- if (!res.isEmpty())
- res.append(',');
- res += item;
- }
- return '[' + res + ']';
-}
-
-QByteArray LldbEngine::Command::toData(const QHash<QByteArray, QByteArray> &value)
-{
- QByteArray res;
- QHashIterator<QByteArray, QByteArray> it(value);
- while (it.hasNext()) {
- it.next();
- if (!res.isEmpty())
- res.append(',');
- res += '"' + it.key() + "\":" + it.value();
- }
- return '{' + res + '}';
-}
-
-const LldbEngine::Command &LldbEngine::Command::arg(const char *name, int value) const
-{
- return argHelper(name, QByteArray::number(value));
-}
-
-const LldbEngine::Command &LldbEngine::Command::arg(const char *name, qlonglong value) const
-{
- return argHelper(name, QByteArray::number(value));
-}
-
-const LldbEngine::Command &LldbEngine::Command::arg(const char *name, qulonglong value) const
-{
- return argHelper(name, QByteArray::number(value));
-}
-
-const LldbEngine::Command &LldbEngine::Command::arg(const char *name, const QString &value) const
-{
- return arg(name, value.toUtf8().data());
-}
-
-const LldbEngine::Command &LldbEngine::Command::arg(const char *name, const QByteArray &value) const
-{
- return arg(name, value.data());
-}
-
-const LldbEngine::Command &LldbEngine::Command::arg(const char *name, const char *value) const
-{
- args.append('"');
- args.append(name);
- args.append("\":\"");
- args.append(value);
- args.append("\",");
- return *this;
-}
-
-const LldbEngine::Command &LldbEngine::Command::arg(const char *value) const
-{
- args.append("\"");
- args.append(value);
- args.append("\",");
- return *this;
-}
-
-const LldbEngine::Command &LldbEngine::Command::beginList(const char *name) const
-{
- if (name) {
- args += '"';
- args += name;
- args += "\":";
- }
- args += '[';
- return *this;
-}
-
-void LldbEngine::Command::endList() const
-{
- if (args.endsWith(','))
- args.chop(1);
- args += "],";
-}
-
-const LldbEngine::Command &LldbEngine::Command::beginGroup(const char *name) const
-{
- if (name) {
- args += '"';
- args += name;
- args += "\":";
- }
- args += '{';
- return *this;
-}
-
-void LldbEngine::Command::endGroup() const
-{
- if (args.endsWith(','))
- args.chop(1);
- args += "},";
-}
-
void LldbEngine::stubStarted()
{
startLldb();
@@ -1441,7 +1277,7 @@ void LldbEngine::stubStarted()
void LldbEngine::stubError(const QString &msg)
{
- showMessageBox(QMessageBox::Critical, tr("Debugger Error"), msg);
+ AsynchronousMessageBox::critical(tr("Debugger Error"), msg);
}
void LldbEngine::stubExited()
diff --git a/src/plugins/debugger/lldb/lldbengine.h b/src/plugins/debugger/lldb/lldbengine.h
index cb209a79cfb..02fef25d6ee 100644
--- a/src/plugins/debugger/lldb/lldbengine.h
+++ b/src/plugins/debugger/lldb/lldbengine.h
@@ -66,33 +66,6 @@ public:
~LldbEngine();
private:
- // Convenience struct to build up backend commands.
- struct Command
- {
- Command() {}
- Command(const char *f) : function(f) {}
-
- const Command &arg(const char *name) const;
- const Command &arg(const char *name, int value) const;
- const Command &arg(const char *name, qlonglong value) const;
- const Command &arg(const char *name, qulonglong value) const;
- const Command &arg(const char *name, const QString &value) const;
- const Command &arg(const char *name, const QByteArray &value) const;
- const Command &arg(const char *name, const char *value) const;
- const Command &beginList(const char *name = 0) const;
- void endList() const;
- const Command &beginGroup(const char *name = 0) const;
- void endGroup() const;
-
- static QByteArray toData(const QList<QByteArray> &value);
- static QByteArray toData(const QHash<QByteArray, QByteArray> &value);
-
- QByteArray function;
- mutable QByteArray args;
- private:
- const Command &argHelper(const char *name, const QByteArray &value) const;
- };
-
// DebuggerEngine implementation
void executeStep();
void executeStepOut();
@@ -122,9 +95,12 @@ private:
void activateFrame(int index);
void selectThread(ThreadId threadId);
- bool acceptsBreakpoint(BreakpointModelId id) const;
- void attemptBreakpointSynchronization();
- bool attemptBreakpointSynchronizationHelper(Command *command);
+ // This should be always the last call in a function.
+ bool stateAcceptsBreakpointChanges() const;
+ bool acceptsBreakpoint(Breakpoint bp) const;
+ void insertBreakpoint(Breakpoint bp);
+ void removeBreakpoint(Breakpoint bp);
+ void changeBreakpoint(Breakpoint bp);
void assignValueInDebugger(const WatchData *data,
const QString &expr, const QVariant &value);
@@ -143,7 +119,7 @@ private:
bool supportsThreads() const { return true; }
bool isSynchronous() const { return true; }
void updateWatchData(const WatchData &data, const WatchUpdateFlags &flags);
- void setRegisterValue(int regnr, const QString &value);
+ void setRegisterValue(const QByteArray &name, const QString &value);
void fetchMemory(Internal::MemoryAgent *, QObject *, quint64 addr, quint64 length);
void changeMemory(Internal::MemoryAgent *, QObject *, quint64 addr, const QByteArray &data);
@@ -161,7 +137,6 @@ private:
Q_SLOT void readLldbStandardOutput();
Q_SLOT void readLldbStandardError();
Q_SLOT void handleResponse(const QByteArray &data);
- Q_SLOT void runEngine2();
Q_SLOT void updateAll();
Q_SLOT void updateStack();
Q_SLOT void updateLocals();
@@ -184,7 +159,6 @@ private:
void refreshAddedBreakpoint(const GdbMi &bkpts);
void refreshChangedBreakpoint(const GdbMi &bkpts);
void refreshRemovedBreakpoint(const GdbMi &bkpts);
- void runContinuation(const GdbMi &data);
void showFullBacktrace(const GdbMi &data);
typedef void (LldbEngine::*LldbCommandContinuation)();
@@ -202,9 +176,9 @@ private:
void handleChildren(const WatchData &data0, const GdbMi &item,
QList<WatchData> *list);
- void runCommand(const Command &cmd);
+ void runCommand(const DebuggerCommand &cmd);
void debugLastCommand();
- Command m_lastDebuggableCommand;
+ DebuggerCommand m_lastDebuggableCommand;
QByteArray m_inbuffer;
QString m_scriptFileName;
diff --git a/src/plugins/debugger/loadcoredialog.cpp b/src/plugins/debugger/loadcoredialog.cpp
index d6188aba551..e2b8063a43c 100644
--- a/src/plugins/debugger/loadcoredialog.cpp
+++ b/src/plugins/debugger/loadcoredialog.cpp
@@ -82,14 +82,13 @@ public:
QString localFile() const { return m_localFile; }
QString remoteFile() const { return m_remoteFile; }
-private slots:
- void handleSftpOperationFinished(QSsh::SftpJobId, const QString &error);
+private:
+ void handleSftpOperationFinished(SftpJobId, const QString &error);
void handleSftpOperationFailed(const QString &errorMessage);
void handleConnectionError(const QString &errorMessage);
void handleRemoteError(const QString &errorMessage);
void selectFile();
-private:
QSortFilterProxyModel m_model;
SftpFileSystemModel m_fileSystemModel;
QTreeView *m_fileSystemView;
@@ -128,13 +127,15 @@ SelectRemoteFileDialog::SelectRemoteFileDialog(QWidget *parent)
layout->addWidget(m_textBrowser);
layout->addWidget(m_buttonBox);
- QObject::connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));
- QObject::connect(m_buttonBox, SIGNAL(accepted()), SLOT(selectFile()));
+ connect(m_buttonBox, &QDialogButtonBox::rejected,
+ this, &QDialog::reject);
+ connect(m_buttonBox, &QDialogButtonBox::accepted,
+ this, &SelectRemoteFileDialog::selectFile);
- connect(&m_fileSystemModel, SIGNAL(sftpOperationFailed(QString)),
- SLOT(handleSftpOperationFailed(QString)));
- connect(&m_fileSystemModel, SIGNAL(connectionError(QString)),
- SLOT(handleConnectionError(QString)));
+ connect(&m_fileSystemModel, &SftpFileSystemModel::sftpOperationFailed,
+ this, &SelectRemoteFileDialog::handleSftpOperationFailed);
+ connect(&m_fileSystemModel, &SftpFileSystemModel::connectionError,
+ this, &SelectRemoteFileDialog::handleConnectionError);
}
void SelectRemoteFileDialog::attachToDevice(Kit *k)
@@ -143,7 +144,7 @@ void SelectRemoteFileDialog::attachToDevice(Kit *k)
QTC_ASSERT(k, return);
IDevice::ConstPtr device = DeviceKitInformation::device(k);
QTC_ASSERT(device, return);
- QSsh::SshConnectionParameters sshParams = device->sshParameters();
+ SshConnectionParameters sshParams = device->sshParameters();
m_fileSystemModel.setSshConnection(sshParams);
}
@@ -159,7 +160,7 @@ void SelectRemoteFileDialog::handleConnectionError(const QString &errorMessage)
//reject();
}
-void SelectRemoteFileDialog::handleSftpOperationFinished(QSsh::SftpJobId, const QString &error)
+void SelectRemoteFileDialog::handleSftpOperationFinished(SftpJobId, const QString &error)
{
if (error.isEmpty()) {
m_textBrowser->append(tr("Download of remote file succeeded."));
@@ -184,8 +185,8 @@ void SelectRemoteFileDialog::selectFile()
m_buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
m_fileSystemView->setEnabled(false);
- connect(&m_fileSystemModel, SIGNAL(sftpOperationFinished(QSsh::SftpJobId,QString)),
- SLOT(handleSftpOperationFinished(QSsh::SftpJobId,QString)));
+ connect(&m_fileSystemModel, &SftpFileSystemModel::sftpOperationFinished,
+ this, &SelectRemoteFileDialog::handleSftpOperationFinished);
{
QTemporaryFile localFile(QDir::tempPath() + QLatin1String("/remotecore-XXXXXX"));
@@ -271,7 +272,7 @@ AttachCoreDialog::AttachCoreDialog(QWidget *parent)
d->forceLocalLabel->setBuddy(d->forceLocalCheckBox);
d->remoteCoreFileName = new QLineEdit(this);
- d->selectRemoteCoreButton = new QPushButton(tr("Browse..."), this);
+ d->selectRemoteCoreButton = new QPushButton(PathChooser::browseButtonLabel(), this);
d->localCoreFileName = new PathChooser(this);
d->localCoreFileName->setHistoryCompleter(QLatin1String("Debugger.CoreFile.History"));
@@ -323,14 +324,14 @@ AttachCoreDialog::~AttachCoreDialog()
int AttachCoreDialog::exec()
{
- connect(d->selectRemoteCoreButton, SIGNAL(clicked()), SLOT(selectRemoteCoreFile()));
- connect(d->remoteCoreFileName, SIGNAL(textChanged(QString)), SLOT(coreFileChanged(QString)));
- connect(d->localExecFileName, SIGNAL(changed(QString)), SLOT(changed()));
- connect(d->localCoreFileName, SIGNAL(changed(QString)), SLOT(coreFileChanged(QString)));
- connect(d->forceLocalCheckBox, SIGNAL(stateChanged(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()));
+ connect(d->selectRemoteCoreButton, &QAbstractButton::clicked, this, &AttachCoreDialog::selectRemoteCoreFile);
+ connect(d->remoteCoreFileName, &QLineEdit::textChanged, this, &AttachCoreDialog::coreFileChanged);
+ connect(d->localExecFileName, &PathChooser::changed, this, &AttachCoreDialog::changed);
+ connect(d->localCoreFileName, &PathChooser::changed, this, &AttachCoreDialog::coreFileChanged);
+ connect(d->forceLocalCheckBox, &QCheckBox::stateChanged, this, &AttachCoreDialog::changed);
+ connect(d->kitChooser, &KitChooser::currentIndexChanged, this, &AttachCoreDialog::changed);
+ connect(d->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ connect(d->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
changed();
AttachCoreDialogPrivate::State st = d->getDialogState(*this);
@@ -364,7 +365,7 @@ bool AttachCoreDialog::useLocalCoreFile() const
void AttachCoreDialog::coreFileChanged(const QString &core)
{
- if (!Utils::HostOsInfo::isWindowsHost() && QFile::exists(core)) {
+ if (!HostOsInfo::isWindowsHost() && QFile::exists(core)) {
Kit *k = d->kitChooser->currentKit();
QTC_ASSERT(k, return);
FileName cmd = DebuggerKitInformation::debuggerCommand(k);
@@ -441,7 +442,7 @@ QString AttachCoreDialog::remoteCoreFile() const
return d->remoteCoreFileName->text();
}
-void AttachCoreDialog::setKitId(Core::Id id)
+void AttachCoreDialog::setKitId(Id id)
{
d->kitChooser->setCurrentKitId(id);
}
diff --git a/src/plugins/debugger/logwindow.cpp b/src/plugins/debugger/logwindow.cpp
index c40b091ec2f..3c233dcc5d1 100644
--- a/src/plugins/debugger/logwindow.cpp
+++ b/src/plugins/debugger/logwindow.cpp
@@ -145,27 +145,27 @@ class DebuggerPane : public QPlainTextEdit
Q_OBJECT
public:
- DebuggerPane(QWidget *parent)
+ DebuggerPane(LogWindow *parent)
: QPlainTextEdit(parent)
{
setFrameStyle(QFrame::NoFrame);
m_clearContentsAction = new QAction(this);
m_clearContentsAction->setText(tr("Clear Contents"));
m_clearContentsAction->setEnabled(true);
- connect(m_clearContentsAction, SIGNAL(triggered(bool)),
- parent, SLOT(clearContents()));
+ connect(m_clearContentsAction, &QAction::triggered,
+ parent, &LogWindow::clearContents);
m_saveContentsAction = new QAction(this);
m_saveContentsAction->setText(tr("Save Contents"));
m_saveContentsAction->setEnabled(true);
- connect(m_saveContentsAction, SIGNAL(triggered()),
- this, SLOT(saveContents()));
+ connect(m_saveContentsAction, &QAction::triggered,
+ this, &DebuggerPane::saveContents);
m_reloadDebuggingHelpersAction = new QAction(this);
m_reloadDebuggingHelpersAction->setText(tr("Reload Debugging Helpers"));
m_reloadDebuggingHelpersAction->setEnabled(true);
- connect(m_reloadDebuggingHelpersAction, SIGNAL(triggered()),
- this, SLOT(reloadDebuggingHelpers()));
+ connect(m_reloadDebuggingHelpersAction, &QAction::triggered,
+ this, &DebuggerPane::reloadDebuggingHelpers);
}
void contextMenuEvent(QContextMenuEvent *ev)
@@ -209,11 +209,10 @@ public:
setUndoRedoEnabled(true);
}
-private slots:
+private:
void saveContents();
void reloadDebuggingHelpers();
-private:
QAction *m_clearContentsAction;
QAction *m_saveContentsAction;
QAction *m_reloadDebuggingHelpersAction;
@@ -239,7 +238,7 @@ class InputPane : public DebuggerPane
{
Q_OBJECT
public:
- InputPane(QWidget *parent)
+ InputPane(LogWindow *parent)
: DebuggerPane(parent)
{
(void) new InputHighlighter(this);
@@ -305,7 +304,7 @@ class CombinedPane : public DebuggerPane
{
Q_OBJECT
public:
- CombinedPane(QWidget *parent)
+ CombinedPane(LogWindow *parent)
: DebuggerPane(parent)
{
(void) new OutputHighlighter(this);
@@ -354,7 +353,7 @@ LogWindow::LogWindow(QWidget *parent)
m_ignoreNextInputEcho = false;
- QSplitter *m_splitter = new Core::MiniSplitter(Qt::Horizontal);
+ auto m_splitter = new Core::MiniSplitter(Qt::Horizontal);
m_splitter->setParent(this);
// Mixed input/output.
@@ -374,25 +373,25 @@ LogWindow::LogWindow(QWidget *parent)
m_commandEdit->setFrame(false);
m_commandEdit->setHistoryCompleter(QLatin1String("DebuggerInput"));
- QToolButton *repeatButton = new QToolButton(this);
+ auto 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;
+ auto commandBox = new QHBoxLayout;
commandBox->addWidget(repeatButton);
commandBox->addWidget(new QLabel(tr("Command:"), this));
commandBox->addWidget(m_commandEdit);
commandBox->setMargin(2);
commandBox->setSpacing(6);
- QVBoxLayout *leftBox = new QVBoxLayout;
+ auto leftBox = new QVBoxLayout;
leftBox->addWidget(m_inputText);
leftBox->addItem(commandBox);
leftBox->setMargin(0);
leftBox->setSpacing(0);
- QWidget *leftDummy = new QWidget;
+ auto leftDummy = new QWidget;
leftDummy->setLayout(leftBox);
m_splitter->addWidget(leftDummy);
@@ -400,14 +399,14 @@ LogWindow::LogWindow(QWidget *parent)
m_splitter->setStretchFactor(0, 1);
m_splitter->setStretchFactor(1, 3);
- QVBoxLayout *layout = new QVBoxLayout(this);
+ auto layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(m_splitter);
layout->addWidget(new Core::FindToolBarPlaceHolder(this));
setLayout(layout);
- Aggregation::Aggregate *aggregate = new Aggregation::Aggregate;
+ auto aggregate = new Aggregation::Aggregate;
aggregate->add(m_combinedText);
aggregate->add(new Core::BaseTextFind(m_combinedText));
@@ -419,14 +418,15 @@ LogWindow::LogWindow(QWidget *parent)
SIGNAL(statusMessageRequested(QString,int)));
connect(m_inputText, SIGNAL(commandSelected(int)),
m_combinedText, SLOT(gotoResult(int)));
- connect(m_commandEdit, SIGNAL(returnPressed()),
- SLOT(sendCommand()));
+ connect(m_commandEdit, &QLineEdit::returnPressed,
+ this, &LogWindow::sendCommand);
connect(m_inputText, SIGNAL(executeLineRequested()),
SLOT(executeLine()));
- connect(repeatButton, SIGNAL(clicked()),
- SLOT(repeatLastCommand()));
+ connect(repeatButton, &QAbstractButton::clicked,
+ this, &LogWindow::repeatLastCommand);
- connect(&m_outputTimer, SIGNAL(timeout()), SLOT(doOutput()));
+ connect(&m_outputTimer, &QTimer::timeout,
+ this, &LogWindow::doOutput);
setMinimumHeight(60);
}
diff --git a/src/plugins/debugger/memoryagent.cpp b/src/plugins/debugger/memoryagent.cpp
index 4eede820720..18835e23636 100644
--- a/src/plugins/debugger/memoryagent.cpp
+++ b/src/plugins/debugger/memoryagent.cpp
@@ -40,13 +40,12 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/messagebox.h>
#include <utils/qtcassert.h>
#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/invoker.h>
-#include <QMessageBox>
-
#include <cstring>
using namespace Core;
@@ -136,15 +135,12 @@ void MemoryAgent::connectBinEditorWidget(QWidget *w)
connect(w, SIGNAL(addWatchpointRequested(quint64,uint)), SLOT(handleWatchpointRequest(quint64,uint)));
}
-bool MemoryAgent::doCreateBinEditor(quint64 addr, unsigned flags,
- const QList<MemoryMarkup> &ml, const QPoint &pos,
- QString title, QWidget *parent)
+bool MemoryAgent::doCreateBinEditor(const MemoryViewSetupData &data)
{
- const bool readOnly = (flags & DebuggerEngine::MemoryReadOnly) != 0;
- if (title.isEmpty())
- title = tr("Memory at 0x%1").arg(addr, 0, 16);
+ const bool readOnly = (data.flags & DebuggerEngine::MemoryReadOnly) != 0;
+ QString title = data.title.isEmpty() ? tr("Memory at 0x%1").arg(data.startAddress, 0, 16) : data.title;
// Separate view?
- if (flags & DebuggerEngine::MemoryView) {
+ if (data.flags & DebuggerEngine::MemoryView) {
// Ask BIN editor plugin for factory service and have it create a bin editor widget.
QWidget *binEditor = 0;
if (QObject *factory = ExtensionSystem::PluginManager::getObjectByClassName(QLatin1String("BinEditor::BinEditorWidgetFactory")))
@@ -156,24 +152,22 @@ bool MemoryAgent::doCreateBinEditor(quint64 addr, unsigned flags,
MemoryView::setBinEditorNewWindowRequestAllowed(binEditor, true);
MemoryView *topLevel = 0;
// Memory view tracking register value, providing its own updating mechanism.
- if (flags & DebuggerEngine::MemoryTrackRegister) {
- RegisterMemoryView *rmv = new RegisterMemoryView(binEditor, parent);
- rmv->init(m_engine->registerHandler(), int(addr));
- topLevel = rmv;
+ if (data.flags & DebuggerEngine::MemoryTrackRegister) {
+ topLevel = new RegisterMemoryView(binEditor, data.startAddress, data.registerName, m_engine->registerHandler(), data.parent);
} else {
// Ordinary memory view
- MemoryView::setBinEditorMarkup(binEditor, ml);
- MemoryView::setBinEditorRange(binEditor, addr, MemoryAgent::DataRange, MemoryAgent::BinBlockSize);
- topLevel = new MemoryView(binEditor, parent);
+ MemoryView::setBinEditorMarkup(binEditor, data.markup);
+ MemoryView::setBinEditorRange(binEditor, data.startAddress, MemoryAgent::DataRange, MemoryAgent::BinBlockSize);
+ topLevel = new MemoryView(binEditor, data.parent);
topLevel->setWindowTitle(title);
}
m_views << topLevel;
- topLevel->move(pos);
+ topLevel->move(data.pos);
topLevel->show();
return true;
}
// Editor: Register tracking not supported.
- QTC_ASSERT(!(flags & DebuggerEngine::MemoryTrackRegister), return false);
+ QTC_ASSERT(!(data.flags & DebuggerEngine::MemoryTrackRegister), return false);
if (!title.endsWith(QLatin1Char('$')))
title.append(QLatin1String(" $"));
IEditor *editor = EditorManager::openEditorWithContents(
@@ -186,18 +180,16 @@ bool MemoryAgent::doCreateBinEditor(quint64 addr, unsigned flags,
connectBinEditorWidget(editorBinEditor);
MemoryView::setBinEditorReadOnly(editorBinEditor, readOnly);
MemoryView::setBinEditorNewWindowRequestAllowed(editorBinEditor, true);
- MemoryView::setBinEditorRange(editorBinEditor, addr, MemoryAgent::DataRange, MemoryAgent::BinBlockSize);
- MemoryView::setBinEditorMarkup(editorBinEditor, ml);
+ MemoryView::setBinEditorRange(editorBinEditor, data.startAddress, MemoryAgent::DataRange, MemoryAgent::BinBlockSize);
+ MemoryView::setBinEditorMarkup(editorBinEditor, data.markup);
m_editors << editor;
return true;
}
-void MemoryAgent::createBinEditor(quint64 addr, unsigned flags,
- const QList<MemoryMarkup> &ml, const QPoint &pos,
- const QString &title, QWidget *parent)
+void MemoryAgent::createBinEditor(const MemoryViewSetupData &data)
{
- if (!doCreateBinEditor(addr, flags, ml, pos, title, parent))
- showMessageBox(QMessageBox::Warning,
+ if (!doCreateBinEditor(data))
+ AsynchronousMessageBox::warning(
tr("No Memory Viewer Available"),
tr("The memory contents cannot be shown as no viewer plugin "
"for binary data has been loaded."));
@@ -205,7 +197,9 @@ void MemoryAgent::createBinEditor(quint64 addr, unsigned flags,
void MemoryAgent::createBinEditor(quint64 addr)
{
- createBinEditor(addr, 0, QList<MemoryMarkup>(), QPoint(), QString(), 0);
+ MemoryViewSetupData data;
+ data.startAddress = addr;
+ createBinEditor(data);
}
void MemoryAgent::fetchLazyData(quint64 block)
@@ -240,7 +234,7 @@ void MemoryAgent::handleWatchpointRequest(quint64 address, uint size)
void MemoryAgent::updateContents()
{
- foreach (const QPointer<Core::IEditor> &e, m_editors)
+ foreach (const QPointer<IEditor> &e, m_editors)
if (e)
MemoryView::binEditorUpdateContents(e->widget());
// Update all views except register views, which trigger on
diff --git a/src/plugins/debugger/memoryagent.h b/src/plugins/debugger/memoryagent.h
index 5967c38c2b6..33386f126e0 100644
--- a/src/plugins/debugger/memoryagent.h
+++ b/src/plugins/debugger/memoryagent.h
@@ -34,21 +34,20 @@
#include "debuggerconstants.h"
#include <QObject>
+#include <QPoint>
#include <QPointer>
#include <QColor>
-QT_FORWARD_DECLARE_CLASS(QPoint)
-
namespace Core { class IEditor; }
namespace ProjectExplorer { class Abi; }
namespace Debugger {
+namespace Internal {
class DebuggerEngine;
-
-namespace Internal {
class MemoryView;
+
class MemoryMarkup
{
public:
@@ -62,6 +61,20 @@ public:
QString toolTip;
};
+class MemoryViewSetupData
+{
+public:
+ MemoryViewSetupData() : parent(0), startAddress(0), flags(0) {}
+
+ QWidget *parent;
+ quint64 startAddress;
+ QByteArray registerName;
+ unsigned flags;
+ QList<Internal::MemoryMarkup> markup;
+ QPoint pos;
+ QString title;
+};
+
class MemoryAgent : public QObject
{
Q_OBJECT
@@ -80,9 +93,7 @@ public:
public slots:
// Called by engine to create a new view.
- void createBinEditor(quint64 startAddr, unsigned flags,
- const QList<MemoryMarkup> &ml, const QPoint &pos,
- const QString &title, QWidget *parent);
+ void createBinEditor(const MemoryViewSetupData &data);
void createBinEditor(quint64 startAddr);
// Called by engine to create a tooltip.
void addLazyData(QObject *editorToken, quint64 addr, const QByteArray &data);
@@ -101,9 +112,7 @@ private slots:
private:
void connectBinEditorWidget(QWidget *w);
- bool doCreateBinEditor(quint64 startAddr, unsigned flags,
- const QList<MemoryMarkup> &ml, const QPoint &pos,
- QString title, QWidget *parent);
+ bool doCreateBinEditor(const MemoryViewSetupData &data);
QList<QPointer<Core::IEditor> > m_editors;
QList<QPointer<MemoryView> > m_views;
diff --git a/src/plugins/debugger/memoryview.cpp b/src/plugins/debugger/memoryview.cpp
index aefb1e469d2..a7850668b0c 100644
--- a/src/plugins/debugger/memoryview.cpp
+++ b/src/plugins/debugger/memoryview.cpp
@@ -138,24 +138,27 @@ void MemoryView::setMarkup(const QList<MemoryMarkup> &m)
\sa Debugger::Internal::MemoryAgent, Debugger::DebuggerEngine
*/
-RegisterMemoryView::RegisterMemoryView(QWidget *binEditor, QWidget *parent) :
+RegisterMemoryView::RegisterMemoryView(QWidget *binEditor, quint64 addr,
+ const QByteArray &regName,
+ RegisterHandler *handler, QWidget *parent) :
MemoryView(binEditor, parent),
- m_registerIndex(0), m_registerAddress(0)
+ m_registerName(regName), m_registerAddress(addr)
{
+ connect(handler, &QAbstractItemModel::modelReset, this, &QWidget::close);
+ connect(handler, &RegisterHandler::registerChanged, this, &RegisterMemoryView::onRegisterChanged);
+ updateContents();
}
-void RegisterMemoryView::slotRegisterSet(const QModelIndex &index)
+void RegisterMemoryView::onRegisterChanged(const QByteArray &name, quint64 value)
{
- if (m_registerIndex != index.row())
- return;
- const QVariant newAddressV = index.data(Qt::EditRole);
- if (newAddressV.type() == QVariant::ULongLong)
- setRegisterAddress(newAddressV.toULongLong());
+ if (name == m_registerName)
+ setRegisterAddress(value);
}
-QString RegisterMemoryView::title(const QString &registerName, quint64 a)
+QString RegisterMemoryView::title(const QByteArray &registerName, quint64 a)
{
- return tr("Memory at Register \"%1\" (0x%2)").arg(registerName).arg(a, 0, 16);
+ return tr("Memory at Register \"%1\" (0x%2)")
+ .arg(QString::fromUtf8(registerName)).arg(a, 0, 16);
}
void RegisterMemoryView::setRegisterAddress(quint64 v)
@@ -171,25 +174,13 @@ void RegisterMemoryView::setRegisterAddress(quint64 v)
setMarkup(registerMarkup(v, m_registerName));
}
-QList<MemoryMarkup> RegisterMemoryView::registerMarkup(quint64 a, const QString &name)
+QList<MemoryMarkup> RegisterMemoryView::registerMarkup(quint64 a, const QByteArray &regName)
{
QList<MemoryMarkup> result;
result.push_back(MemoryMarkup(a, 1, QColor(Qt::blue).lighter(),
- tr("Register \"%1\"").arg(name)));
+ tr("Register \"%1\"").arg(QString::fromUtf8(regName))));
return result;
}
-void RegisterMemoryView::init(RegisterHandler *h, int registerIndex)
-{
- m_registerIndex = registerIndex;
- m_registerName = QString::fromLatin1(h->registerAt(registerIndex).name);
- // Known issue: CDB might reset the model by changing the special
- // registers it reports.
- connect(h, SIGNAL(modelReset()), this, SLOT(close()));
- connect(h, SIGNAL(registerSet(QModelIndex)),
- this, SLOT(slotRegisterSet(QModelIndex)));
- setRegisterAddress(h->registerAt(m_registerIndex).editValue().toULongLong());
-}
-
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/memoryview.h b/src/plugins/debugger/memoryview.h
index a88d6742d44..aa81540ecba 100644
--- a/src/plugins/debugger/memoryview.h
+++ b/src/plugins/debugger/memoryview.h
@@ -69,21 +69,17 @@ class RegisterMemoryView : public MemoryView
{
Q_OBJECT
public:
- explicit RegisterMemoryView(QWidget *binEditor, QWidget *parent = 0);
+ explicit RegisterMemoryView(QWidget *binEditor, quint64 addr, const QByteArray &regName,
+ RegisterHandler *rh, QWidget *parent = 0);
- void init(RegisterHandler *rh, int index);
-
- static QList<MemoryMarkup> registerMarkup(quint64 a, const QString &name);
- static QString title(const QString &registerName, quint64 a = 0);
-
-private slots:
- void slotRegisterSet(const QModelIndex &index);
+ static QList<MemoryMarkup> registerMarkup(quint64 a, const QByteArray &regName);
+ static QString title(const QByteArray &registerName, quint64 a = 0);
private:
+ void onRegisterChanged(const QByteArray &name, quint64 value);
void setRegisterAddress(quint64 v);
- int m_registerIndex;
- QString m_registerName;
+ QByteArray m_registerName;
quint64 m_registerAddress;
};
diff --git a/src/plugins/debugger/moduleshandler.cpp b/src/plugins/debugger/moduleshandler.cpp
index f404d561f33..3e793a424b6 100644
--- a/src/plugins/debugger/moduleshandler.cpp
+++ b/src/plugins/debugger/moduleshandler.cpp
@@ -31,7 +31,9 @@
#include "moduleshandler.h"
#include <utils/qtcassert.h>
+#include <utils/treemodel.h>
+#include <QCoreApplication>
#include <QDebug>
#include <QSortFilterProxyModel>
@@ -46,211 +48,109 @@ using namespace Utils;
namespace Debugger {
namespace Internal {
-class ModulesModel : public QAbstractItemModel
+class ModuleItem : public TreeItem
{
public:
- explicit ModulesModel(QObject *parent)
- : QAbstractItemModel(parent)
- {}
+ QVariant data(int column, int role) const;
- int columnCount(const QModelIndex &parent) const
- { return parent.isValid() ? 0 : 5; }
- int rowCount(const QModelIndex &parent) const
- { return parent.isValid() ? 0 : m_modules.size(); }
- QModelIndex parent(const QModelIndex &) const { return QModelIndex(); }
- QModelIndex index(int row, int column, const QModelIndex &) const
- { return createIndex(row, column); }
- QVariant headerData(int section, Qt::Orientation orientation, int role) const;
- QVariant data(const QModelIndex &index, int role) const;
-
- void clearModel();
- void removeModule(const QString &modulePath);
- void setModules(const Modules &modules);
- void updateModule(const Module &module);
-
- int indexOfModule(const QString &modulePath) const;
-
- Modules m_modules;
+public:
+ Module module;
+ bool updated;
};
-
-QVariant ModulesModel::headerData(int section,
- Qt::Orientation orientation, int role) const
+QVariant ModuleItem::data(int column, int role) const
{
- if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
- static QString headers[] = {
- ModulesHandler::tr("Module Name") + QLatin1String(" "),
- ModulesHandler::tr("Module Path") + QLatin1String(" "),
- ModulesHandler::tr("Symbols Read") + QLatin1String(" "),
- ModulesHandler::tr("Symbols Type") + QLatin1String(" "),
- ModulesHandler::tr("Start Address") + QLatin1String(" "),
- ModulesHandler::tr("End Address") + QLatin1String(" ")
- };
- return headers[section];
- }
- return QVariant();
-}
-
-QVariant ModulesModel::data(const QModelIndex &index, int role) const
-{
- int row = index.row();
- if (row < 0 || row >= m_modules.size())
- return QVariant();
-
- const Module &module = m_modules.at(row);
-
- switch (index.column()) {
- case 0:
- if (role == Qt::DisplayRole)
- return module.moduleName;
- // FIXME: add icons
- //if (role == Qt::DecorationRole)
- // return module.symbolsRead ? icon2 : icon;
- break;
- case 1:
- if (role == Qt::DisplayRole)
- return module.modulePath;
- if (role == Qt::ToolTipRole) {
- QString msg;
- if (!module.elfData.buildId.isEmpty())
- msg += QString::fromLatin1("Build Id: " + module.elfData.buildId);
- if (!module.elfData.debugLink.isEmpty())
- msg += QString::fromLatin1("Debug Link: " + module.elfData.debugLink);
- return msg;
+ switch (column) {
+ case 0:
+ if (role == Qt::DisplayRole)
+ return module.moduleName;
+ // FIXME: add icons
+ //if (role == Qt::DecorationRole)
+ // return module.symbolsRead ? icon2 : icon;
+ break;
+ case 1:
+ if (role == Qt::DisplayRole)
+ return module.modulePath;
+ if (role == Qt::ToolTipRole) {
+ QString msg;
+ if (!module.elfData.buildId.isEmpty())
+ msg += QString::fromLatin1("Build Id: " + module.elfData.buildId);
+ if (!module.elfData.debugLink.isEmpty())
+ msg += QString::fromLatin1("Debug Link: " + module.elfData.debugLink);
+ return msg;
+ }
+ break;
+ case 2:
+ if (role == Qt::DisplayRole)
+ switch (module.symbolsRead) {
+ case Module::UnknownReadState: return ModulesHandler::tr("Unknown");
+ case Module::ReadFailed: return ModulesHandler::tr("No");
+ case Module::ReadOk: return ModulesHandler::tr("Yes");
}
- break;
- case 2:
- if (role == Qt::DisplayRole)
- switch (module.symbolsRead) {
- case Module::UnknownReadState: return ModulesHandler::tr("Unknown");
- case Module::ReadFailed: return ModulesHandler::tr("No");
- case Module::ReadOk: return ModulesHandler::tr("Yes");
- }
- break;
- case 3:
- if (role == Qt::DisplayRole)
- switch (module.elfData.symbolsType) {
- case UnknownSymbols:
- return ModulesHandler::tr("Unknown");
- case NoSymbols:
- return ModulesHandler::tr("None");
- case PlainSymbols:
- return ModulesHandler::tr("Plain");
- case FastSymbols:
- return ModulesHandler::tr("Fast");
- case LinkedSymbols:
- return ModulesHandler::tr("debuglnk");
- case BuildIdSymbols:
- return ModulesHandler::tr("buildid");
- }
- else if (role == Qt::ToolTipRole)
- switch (module.elfData.symbolsType) {
- case UnknownSymbols:
- return ModulesHandler::tr(
- "It is unknown whether this module contains debug "
- "information.\nUse \"Examine Symbols\" from the "
- "context menu to initiate a check.");
- case NoSymbols:
- return ModulesHandler::tr(
- "This module neither contains nor references debug "
- "information.\nStepping into the module or setting "
- "breakpoints by file and line will not work.");
- case PlainSymbols:
- return ModulesHandler::tr(
- "This module contains debug information.\nStepping "
- "into the module or setting breakpoints by file and "
- "line is expected to work.");
- case FastSymbols:
- return ModulesHandler::tr(
- "This module contains debug information.\nStepping "
- "into the module or setting breakpoints by file and "
- "line is expected to work.");
- case LinkedSymbols:
- case BuildIdSymbols:
- return ModulesHandler::tr(
- "This module does not contain debug information "
- "itself, but contains a reference to external "
- "debug information.");
- }
- break;
- case 4:
- if (role == Qt::DisplayRole)
- if (module.startAddress)
- return QString(QLatin1String("0x")
- + QString::number(module.startAddress, 16));
- break;
- case 5:
- if (role == Qt::DisplayRole) {
- if (module.endAddress)
- return QString(QLatin1String("0x")
- + QString::number(module.endAddress, 16));
- //: End address of loaded module
- return ModulesHandler::tr("<unknown>", "address");
+ break;
+ case 3:
+ if (role == Qt::DisplayRole)
+ switch (module.elfData.symbolsType) {
+ case UnknownSymbols:
+ return ModulesHandler::tr("Unknown");
+ case NoSymbols:
+ return ModulesHandler::tr("None");
+ case PlainSymbols:
+ return ModulesHandler::tr("Plain");
+ case FastSymbols:
+ return ModulesHandler::tr("Fast");
+ case LinkedSymbols:
+ return ModulesHandler::tr("debuglnk");
+ case BuildIdSymbols:
+ return ModulesHandler::tr("buildid");
}
- break;
- }
- return QVariant();
-}
-
-void ModulesModel::setModules(const Modules &m)
-{
- beginResetModel();
- m_modules = m;
- endResetModel();
-}
-
-void ModulesModel::clearModel()
-{
- if (!m_modules.isEmpty()) {
- beginResetModel();
- m_modules.clear();
- endResetModel();
- }
-}
-
-int ModulesModel::indexOfModule(const QString &modulePath) const
-{
- // Recent modules are more likely to be unloaded first.
- for (int i = m_modules.size() - 1; i >= 0; i--)
- if (m_modules.at(i).modulePath == modulePath)
- return i;
- return -1;
-}
-
-void ModulesModel::removeModule(const QString &modulePath)
-{
- const int row = indexOfModule(modulePath);
- QTC_ASSERT(row != -1, return);
- beginRemoveRows(QModelIndex(), row, row);
- m_modules.remove(row);
- endRemoveRows();
-}
-
-void ModulesModel::updateModule(const Module &module)
-{
- const int row = indexOfModule(module.modulePath);
- const QString path = module.modulePath;
- if (path.isEmpty())
- return;
- try { // MinGW occasionallly throws std::bad_alloc.
- ElfReader reader(path);
- ElfData elfData = reader.readHeaders();
-
- if (row == -1) {
- const int n = m_modules.size();
- beginInsertRows(QModelIndex(), n, n);
- m_modules.push_back(module);
- m_modules.back().elfData = elfData;
- endInsertRows();
- } else {
- m_modules[row] = module;
- m_modules[row].elfData = elfData;
- dataChanged(index(row, 0, QModelIndex()), index(row, 4, QModelIndex()));
+ else if (role == Qt::ToolTipRole)
+ switch (module.elfData.symbolsType) {
+ case UnknownSymbols:
+ return ModulesHandler::tr(
+ "It is unknown whether this module contains debug "
+ "information.\nUse \"Examine Symbols\" from the "
+ "context menu to initiate a check.");
+ case NoSymbols:
+ return ModulesHandler::tr(
+ "This module neither contains nor references debug "
+ "information.\nStepping into the module or setting "
+ "breakpoints by file and line will not work.");
+ case PlainSymbols:
+ return ModulesHandler::tr(
+ "This module contains debug information.\nStepping "
+ "into the module or setting breakpoints by file and "
+ "line is expected to work.");
+ case FastSymbols:
+ return ModulesHandler::tr(
+ "This module contains debug information.\nStepping "
+ "into the module or setting breakpoints by file and "
+ "line is expected to work.");
+ case LinkedSymbols:
+ case BuildIdSymbols:
+ return ModulesHandler::tr(
+ "This module does not contain debug information "
+ "itself, but contains a reference to external "
+ "debug information.");
+ }
+ break;
+ case 4:
+ if (role == Qt::DisplayRole)
+ if (module.startAddress)
+ return QString(QLatin1String("0x")
+ + QString::number(module.startAddress, 16));
+ break;
+ case 5:
+ if (role == Qt::DisplayRole) {
+ if (module.endAddress)
+ return QString(QLatin1String("0x")
+ + QString::number(module.endAddress, 16));
+ //: End address of loaded module
+ return ModulesHandler::tr("<unknown>", "address");
}
- } catch(...) {
- qWarning("%s: An exception occurred while reading module '%s'",
- Q_FUNC_INFO, qPrintable(module.modulePath));
+ break;
}
+ return QVariant();
}
//////////////////////////////////////////////////////////////////
@@ -259,11 +159,32 @@ void ModulesModel::updateModule(const Module &module)
//
//////////////////////////////////////////////////////////////////
+static ModuleItem *moduleFromPath(TreeItem *root, const QString &modulePath)
+{
+ // Recent modules are more likely to be unloaded first.
+ for (int i = root->rowCount(); --i >= 0; ) {
+ auto item = static_cast<ModuleItem *>(root->child(i));
+ if (item->module.modulePath == modulePath)
+ return item;
+ }
+ return 0;
+}
+
ModulesHandler::ModulesHandler(DebuggerEngine *engine)
{
m_engine = engine;
- m_model = new ModulesModel(this);
+
+ QString pad = QLatin1String(" ");
+ m_model = new TreeModel(this);
m_model->setObjectName(QLatin1String("ModulesModel"));
+ m_model->setHeader(QStringList()
+ << ModulesHandler::tr("Module Name") + pad
+ << ModulesHandler::tr("Module Path") + pad
+ << ModulesHandler::tr("Symbols Read") + pad
+ << ModulesHandler::tr("Symbols Type") + pad
+ << ModulesHandler::tr("Start Address") + pad
+ << ModulesHandler::tr("End Address") + pad);
+
m_proxyModel = new QSortFilterProxyModel(this);
m_proxyModel->setObjectName(QLatin1String("ModulesProxyModel"));
m_proxyModel->setSourceModel(m_model);
@@ -276,27 +197,65 @@ QAbstractItemModel *ModulesHandler::model() const
void ModulesHandler::removeAll()
{
- m_model->clearModel();
+ m_model->removeItems();
+}
+
+Modules ModulesHandler::modules() const
+{
+ Modules mods;
+ TreeItem *root = m_model->rootItem();
+ for (int i = root->rowCount(); --i >= 0; )
+ mods.append(static_cast<ModuleItem *>(root->child(i))->module);
+ return mods;
}
void ModulesHandler::removeModule(const QString &modulePath)
{
- m_model->removeModule(modulePath);
+ if (ModuleItem *item = moduleFromPath(m_model->rootItem(), modulePath))
+ m_model->removeItem(item);
}
void ModulesHandler::updateModule(const Module &module)
{
- m_model->updateModule(module);
+ const QString path = module.modulePath;
+ if (path.isEmpty())
+ return;
+
+ ModuleItem *item = moduleFromPath(m_model->rootItem(), path);
+ if (item) {
+ item->module = module;
+ } else {
+ item = new ModuleItem;
+ item->module = module;
+ m_model->rootItem()->appendChild(item);
+ }
+
+ try { // MinGW occasionallly throws std::bad_alloc.
+ ElfReader reader(path);
+ item->module.elfData = reader.readHeaders();
+ item->update();
+ } catch(...) {
+ qWarning("%s: An exception occurred while reading module '%s'",
+ Q_FUNC_INFO, qPrintable(module.modulePath));
+ }
+ item->updated = true;
}
-void ModulesHandler::setModules(const Modules &modules)
+void ModulesHandler::beginUpdateAll()
{
- m_model->setModules(modules);
+ TreeItem *root = m_model->rootItem();
+ for (int i = root->rowCount(); --i >= 0; )
+ static_cast<ModuleItem *>(root->child(i))->updated = false;
}
-Modules ModulesHandler::modules() const
+void ModulesHandler::endUpdateAll()
{
- return m_model->m_modules;
+ TreeItem *root = m_model->rootItem();
+ for (int i = root->rowCount(); --i >= 0; ) {
+ auto item = static_cast<ModuleItem *>(root->child(i));
+ if (!item->updated)
+ m_model->removeItem(item);
+ }
}
} // namespace Internal
diff --git a/src/plugins/debugger/moduleshandler.h b/src/plugins/debugger/moduleshandler.h
index 61b68e7ac38..bad6d1c8799 100644
--- a/src/plugins/debugger/moduleshandler.h
+++ b/src/plugins/debugger/moduleshandler.h
@@ -32,6 +32,7 @@
#define DEBUGGER_MODULESHANDLER_H
#include <utils/elfreader.h>
+#include <utils/treemodel.h>
QT_BEGIN_NAMESPACE
class QAbstractItemModel;
@@ -39,12 +40,9 @@ class QSortFilterProxyModel;
QT_END_NAMESPACE
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
-class ModulesModel;
+class DebuggerEngine;
//////////////////////////////////////////////////////////////////
//
@@ -111,7 +109,6 @@ public:
typedef QVector<Module> Modules;
-
//////////////////////////////////////////////////////////////////
//
// ModulesHandler
@@ -127,16 +124,18 @@ public:
QAbstractItemModel *model() const;
- void setModules(const Modules &modules);
void removeModule(const QString &modulePath);
void updateModule(const Module &module);
- Modules modules() const;
+ void beginUpdateAll();
+ void endUpdateAll();
+
void removeAll();
+ Modules modules() const;
private:
DebuggerEngine *m_engine;
- ModulesModel *m_model;
+ Utils::TreeModel *m_model;
QSortFilterProxyModel *m_proxyModel;
};
diff --git a/src/plugins/debugger/moduleswindow.cpp b/src/plugins/debugger/moduleswindow.cpp
index 19ebd36362c..e9605587d61 100644
--- a/src/plugins/debugger/moduleswindow.cpp
+++ b/src/plugins/debugger/moduleswindow.cpp
@@ -57,8 +57,8 @@ ModulesTreeView::ModulesTreeView()
{
setSortingEnabled(true);
- connect(this, SIGNAL(activated(QModelIndex)),
- SLOT(moduleActivated(QModelIndex)));
+ connect(this, &QAbstractItemView::activated,
+ this, &ModulesTreeView::moduleActivated);
}
void ModulesTreeView::moduleActivated(const QModelIndex &index)
diff --git a/src/plugins/debugger/pdb/pdbengine.cpp b/src/plugins/debugger/pdb/pdbengine.cpp
index 559b2a8f8a0..a6a2acb2268 100644
--- a/src/plugins/debugger/pdb/pdbengine.cpp
+++ b/src/plugins/debugger/pdb/pdbengine.cpp
@@ -52,6 +52,7 @@
#include <texteditor/texteditor.h>
#include <coreplugin/idocument.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <QDateTime>
#include <QDebug>
@@ -61,7 +62,6 @@
#include <QVariant>
#include <QApplication>
-#include <QMessageBox>
#include <QToolTip>
@@ -157,17 +157,17 @@ void PdbEngine::setupEngine()
m_pdb = _("python");
showMessage(_("STARTING PDB ") + m_pdb);
- connect(&m_pdbProc, SIGNAL(error(QProcess::ProcessError)),
- SLOT(handlePdbError(QProcess::ProcessError)));
- connect(&m_pdbProc, SIGNAL(finished(int,QProcess::ExitStatus)),
- SLOT(handlePdbFinished(int,QProcess::ExitStatus)));
- connect(&m_pdbProc, SIGNAL(readyReadStandardOutput()),
- SLOT(readPdbStandardOutput()));
- connect(&m_pdbProc, SIGNAL(readyReadStandardError()),
- SLOT(readPdbStandardError()));
+ connect(&m_pdbProc, static_cast<void(QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
+ this, &PdbEngine::handlePdbError);
+ connect(&m_pdbProc, static_cast<void(QProcess::*)(int,QProcess::ExitStatus)>(&QProcess::finished),
+ this, &PdbEngine::handlePdbFinished);
+ connect(&m_pdbProc, &QProcess::readyReadStandardOutput,
+ this, &PdbEngine::readPdbStandardOutput);
+ connect(&m_pdbProc, &QProcess::readyReadStandardError,
+ this, &PdbEngine::readPdbStandardError);
- connect(this, SIGNAL(outputReady(QByteArray)),
- SLOT(handleOutput2(QByteArray)), Qt::QueuedConnection);
+ connect(this, &PdbEngine::outputReady,
+ this, &PdbEngine::handleOutput2, Qt::QueuedConnection);
// We will stop immediately, so setup a proper callback.
PdbCommand cmd;
@@ -198,7 +198,7 @@ void PdbEngine::setupInferior()
QString fileName = QFileInfo(startParameters().executable).absoluteFilePath();
QFile scriptFile(fileName);
if (!scriptFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
- showMessageBox(QMessageBox::Critical, tr("Python Error"),
+ Core::AsynchronousMessageBox::critical(tr("Python Error"),
_("Cannot open script file %1:\n%2").
arg(fileName, scriptFile.errorString()));
notifyInferiorSetupFailed();
@@ -327,34 +327,31 @@ void PdbEngine::selectThread(ThreadId threadId)
Q_UNUSED(threadId)
}
-bool PdbEngine::acceptsBreakpoint(BreakpointModelId id) const
+bool PdbEngine::acceptsBreakpoint(Breakpoint bp) const
{
- const QString fileName = breakHandler()->fileName(id);
+ const QString fileName = bp.fileName();
return fileName.endsWith(QLatin1String(".py"));
}
-void PdbEngine::insertBreakpoint(BreakpointModelId id)
+void PdbEngine::insertBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- QTC_CHECK(handler->state(id) == BreakpointInsertRequested);
- handler->notifyBreakpointInsertProceeding(id);
+ QTC_CHECK(bp.state() == BreakpointInsertRequested);
+ bp.notifyBreakpointInsertProceeding();
QByteArray loc;
- if (handler->type(id) == BreakpointByFunction)
- loc = handler->functionName(id).toLatin1();
+ if (bp.type() == BreakpointByFunction)
+ loc = bp.functionName().toLatin1();
else
- loc = handler->fileName(id).toLocal8Bit() + ':'
- + QByteArray::number(handler->lineNumber(id));
+ loc = bp.fileName().toLocal8Bit() + ':'
+ + QByteArray::number(bp.lineNumber());
- postCommand("break " + loc, CB(handleBreakInsert), QVariant(id));
+ postCommand("break " + loc, CB(handleBreakInsert), QVariant::fromValue(bp));
}
void PdbEngine::handleBreakInsert(const PdbResponse &response)
{
//qDebug() << "BP RESPONSE: " << response.data;
// "Breakpoint 1 at /pdb/math.py:10"
- BreakpointModelId id(response.cookie.toInt());
- BreakHandler *handler = breakHandler();
QTC_ASSERT(response.data.startsWith("Breakpoint "), return);
int pos1 = response.data.indexOf(" at ");
QTC_ASSERT(pos1 != -1, return);
@@ -366,22 +363,21 @@ void PdbEngine::handleBreakInsert(const PdbResponse &response)
br.id = BreakpointResponseId(bpnr);
br.fileName = _(file);
br.lineNumber = line.toInt();
- handler->setResponse(id, br);
- QTC_CHECK(!handler->needsChange(id));
- handler->notifyBreakpointInsertOk(id);
+ Breakpoint bp = response.cookie.value<Breakpoint>();
+ bp.setResponse(br);
+ QTC_CHECK(!bp.needsChange());
+ bp.notifyBreakpointInsertOk();
}
-void PdbEngine::removeBreakpoint(BreakpointModelId id)
+void PdbEngine::removeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- QTC_CHECK(handler->state(id) == BreakpointRemoveRequested);
- handler->notifyBreakpointRemoveProceeding(id);
- BreakpointResponse br = handler->response(id);
- showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString())
- .arg(handler->fileName(id)));
+ QTC_CHECK(bp.state() == BreakpointRemoveRequested);
+ bp.notifyBreakpointRemoveProceeding();
+ BreakpointResponse br = bp.response();
+ showMessage(_("DELETING BP %1 IN %2").arg(br.id.toString()).arg(bp.fileName()));
postCommand("clear " + br.id.toByteArray());
// Pretend it succeeds without waiting for response.
- handler->notifyBreakpointRemoveOk(id);
+ bp.notifyBreakpointRemoveOk();
}
void PdbEngine::loadSymbols(const QString &moduleName)
@@ -402,7 +398,8 @@ void PdbEngine::handleListModules(const PdbResponse &response)
{
GdbMi out;
out.fromString(response.data.trimmed());
- Modules modules;
+ ModulesHandler *handler = modulesHandler();
+ handler->beginUpdateAll();
foreach (const GdbMi &item, out.children()) {
Module module;
module.moduleName = _(item["name"].data());
@@ -417,9 +414,9 @@ void PdbEngine::handleListModules(const PdbResponse &response)
path = _("(builtin)");
}
module.modulePath = path;
- modules.append(module);
+ handler->updateModule(module);
}
- modulesHandler()->setModules(modules);
+ handler->endUpdateAll();
}
void PdbEngine::requestModuleSymbols(const QString &moduleName)
@@ -555,8 +552,8 @@ void PdbEngine::handlePdbError(QProcess::ProcessError error)
default:
//setState(EngineShutdownRequested, true);
m_pdbProc.kill();
- showMessageBox(QMessageBox::Critical, tr("Pdb I/O Error"),
- errorMessage(error));
+ Core::AsynchronousMessageBox::critical(tr("Pdb I/O Error"),
+ errorMessage(error));
break;
}
}
@@ -728,7 +725,7 @@ void PdbEngine::updateLocals()
options.chop(1);
postCommand("qdebug('" + options + "','"
- + handler->expansionRequests() + "','"
+// + handler->expansionRequests() + "','"
+ handler->typeFormatRequests() + "','"
+ handler->individualFormatRequests() + "','"
+ watchers.toHex() + "')", CB(handleListLocals));
@@ -803,16 +800,19 @@ void PdbEngine::handleListLocals(const PdbResponse &response)
//qDebug() << "ALL: " << all.toString();
//GdbMi data = all.findChild("data");
- QList<WatchData> list;
WatchHandler *handler = watchHandler();
+
+ QSet<QByteArray> toDelete;
+ foreach (WatchItem *item, handler->model()->treeLevelItems<WatchItem *>(2))
+ toDelete.insert(item->d.iname);
+
foreach (const GdbMi &child, all.children()) {
- WatchData dummy;
- dummy.iname = child["iname"].data();
- dummy.name = _(child["name"].data());
- //qDebug() << "CHILD: " << child.toString();
- parseWatchData(handler->expandedINames(), dummy, child, &list);
+ WatchItem *item = new WatchItem(child);
+ handler->insertItem(item);
+ toDelete.remove(item->d.iname);
}
- handler->insertData(list);
+
+ handler->purgeOutdatedItems(toDelete);
}
bool PdbEngine::hasCapability(unsigned cap) const
@@ -825,6 +825,5 @@ DebuggerEngine *createPdbEngine(const DebuggerStartParameters &startParameters)
return new PdbEngine(startParameters);
}
-
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/pdb/pdbengine.h b/src/plugins/debugger/pdb/pdbengine.h
index 2a1cd55ced0..41dc68a119a 100644
--- a/src/plugins/debugger/pdb/pdbengine.h
+++ b/src/plugins/debugger/pdb/pdbengine.h
@@ -89,9 +89,9 @@ private:
void activateFrame(int index);
void selectThread(ThreadId threadId);
- bool acceptsBreakpoint(BreakpointModelId id) const;
- void insertBreakpoint(BreakpointModelId id);
- void removeBreakpoint(BreakpointModelId id);
+ bool acceptsBreakpoint(Breakpoint bp) const;
+ void insertBreakpoint(Breakpoint bp);
+ void removeBreakpoint(Breakpoint bp);
void assignValueInDebugger(const WatchData *data,
const QString &expr, const QVariant &value);
@@ -116,11 +116,11 @@ private:
QString errorMessage(QProcess::ProcessError error) const;
bool hasCapability(unsigned cap) const;
- Q_SLOT void handlePdbFinished(int, QProcess::ExitStatus status);
- Q_SLOT void handlePdbError(QProcess::ProcessError error);
- Q_SLOT void readPdbStandardOutput();
- Q_SLOT void readPdbStandardError();
- Q_SLOT void handleOutput2(const QByteArray &data);
+ void handlePdbFinished(int, QProcess::ExitStatus status);
+ void handlePdbError(QProcess::ProcessError error);
+ void readPdbStandardOutput();
+ void readPdbStandardError();
+ void handleOutput2(const QByteArray &data);
void handleResponse(const QByteArray &ba);
void handleOutput(const QByteArray &data);
void updateAll();
diff --git a/src/plugins/debugger/qml/baseqmldebuggerclient.cpp b/src/plugins/debugger/qml/baseqmldebuggerclient.cpp
index c1b443b9859..5a7f9287a1e 100644
--- a/src/plugins/debugger/qml/baseqmldebuggerclient.cpp
+++ b/src/plugins/debugger/qml/baseqmldebuggerclient.cpp
@@ -29,6 +29,7 @@
****************************************************************************/
#include "baseqmldebuggerclient.h"
+#include <debugger/breakhandler.h>
#include <utils/qtcassert.h>
@@ -52,7 +53,7 @@ BaseQmlDebuggerClient::~BaseQmlDebuggerClient()
delete d;
}
-bool BaseQmlDebuggerClient::acceptsBreakpoint(const BreakpointModelId &/*id*/)
+bool BaseQmlDebuggerClient::acceptsBreakpoint(Breakpoint /*bp*/)
{
return false;
}
diff --git a/src/plugins/debugger/qml/baseqmldebuggerclient.h b/src/plugins/debugger/qml/baseqmldebuggerclient.h
index cb0d63b1399..409a3dc9c5b 100644
--- a/src/plugins/debugger/qml/baseqmldebuggerclient.h
+++ b/src/plugins/debugger/qml/baseqmldebuggerclient.h
@@ -67,11 +67,11 @@ public:
virtual void activateFrame(int index) = 0;
- virtual bool acceptsBreakpoint(const BreakpointModelId &id);
- virtual void insertBreakpoint(const BreakpointModelId &id, int adjustedLine,
+ virtual bool acceptsBreakpoint(Breakpoint bp);
+ virtual void insertBreakpoint(Breakpoint bp, int adjustedLine,
int adjustedColumn = -1) = 0;
- virtual void removeBreakpoint(const BreakpointModelId &id) = 0;
- virtual void changeBreakpoint(const BreakpointModelId &id) = 0;
+ virtual void removeBreakpoint(Breakpoint bp) = 0;
+ virtual void changeBreakpoint(Breakpoint bp) = 0;
virtual void synchronizeBreakpoints() = 0;
virtual void assignValueInDebugger(const WatchData *data,
diff --git a/src/plugins/debugger/qml/qmladapter.cpp b/src/plugins/debugger/qml/qmladapter.cpp
index 2557753a4e7..73f29d0400f 100644
--- a/src/plugins/debugger/qml/qmladapter.cpp
+++ b/src/plugins/debugger/qml/qmladapter.cpp
@@ -57,21 +57,25 @@ QmlAdapter::QmlAdapter(DebuggerEngine *engine, QObject *parent)
{
m_connectionTimer.setInterval(4000);
m_connectionTimer.setSingleShot(true);
- connect(&m_connectionTimer, SIGNAL(timeout()), SLOT(checkConnectionState()));
+ connect(&m_connectionTimer, &QTimer::timeout, this, &QmlAdapter::checkConnectionState);
m_conn = new QmlDebugConnection(this);
- connect(m_conn, SIGNAL(stateMessage(QString)), SLOT(showConnectionStateMessage(QString)));
- connect(m_conn, SIGNAL(errorMessage(QString)), SLOT(showConnectionErrorMessage(QString)));
- connect(m_conn, SIGNAL(error(QDebugSupport::Error)),
- SLOT(connectionErrorOccurred(QDebugSupport::Error)));
- connect(m_conn, SIGNAL(opened()), &m_connectionTimer, SLOT(stop()));
- connect(m_conn, SIGNAL(opened()), SIGNAL(connected()));
- connect(m_conn, SIGNAL(closed()), SIGNAL(disconnected()));
+ connect(m_conn, &QmlDebugConnection::stateMessage,
+ this, &QmlAdapter::showConnectionStateMessage);
+ connect(m_conn, &QmlDebugConnection::errorMessage,
+ this, &QmlAdapter::showConnectionErrorMessage);
+ connect(m_conn, &QmlDebugConnection::error,
+ this, &QmlAdapter::connectionErrorOccurred);
+ connect(m_conn, &QmlDebugConnection::opened,
+ &m_connectionTimer, &QTimer::stop);
+ connect(m_conn, &QmlDebugConnection::opened,
+ this, &QmlAdapter::connected);
+ connect(m_conn, &QmlDebugConnection::closed,
+ this, &QmlAdapter::disconnected);
createDebuggerClients();
m_msgClient = new QDebugMessageClient(m_conn);
- connect(m_msgClient, SIGNAL(newState(QmlDebug::QmlDebugClient::State)),
- this, SLOT(clientStateChanged(QmlDebug::QmlDebugClient::State)));
+ connect(m_msgClient, &QDebugMessageClient::newState, this, &QmlAdapter::clientStateChanged);
}
@@ -125,7 +129,7 @@ void QmlAdapter::clientStateChanged(QmlDebugClient::State state)
void QmlAdapter::debugClientStateChanged(QmlDebugClient::State state)
{
- if (state != QmlDebug::QmlDebugClient::Enabled)
+ if (state != QmlDebugClient::Enabled)
return;
QmlDebugClient *client = qobject_cast<QmlDebugClient*>(sender());
QTC_ASSERT(client, return);
@@ -150,16 +154,16 @@ bool QmlAdapter::isConnected() const
void QmlAdapter::createDebuggerClients()
{
QScriptDebuggerClient *debugClient1 = new QScriptDebuggerClient(m_conn);
- connect(debugClient1, SIGNAL(newState(QmlDebug::QmlDebugClient::State)),
- this, SLOT(clientStateChanged(QmlDebug::QmlDebugClient::State)));
- connect(debugClient1, SIGNAL(newState(QmlDebug::QmlDebugClient::State)),
- this, SLOT(debugClientStateChanged(QmlDebug::QmlDebugClient::State)));
+ connect(debugClient1, &QScriptDebuggerClient::newState,
+ this, &QmlAdapter::clientStateChanged);
+ connect(debugClient1, &QScriptDebuggerClient::newState,
+ this, &QmlAdapter::debugClientStateChanged);
QmlV8DebuggerClient *debugClient2 = new QmlV8DebuggerClient(m_conn);
- connect(debugClient2, SIGNAL(newState(QmlDebug::QmlDebugClient::State)),
- this, SLOT(clientStateChanged(QmlDebug::QmlDebugClient::State)));
- connect(debugClient2, SIGNAL(newState(QmlDebug::QmlDebugClient::State)),
- this, SLOT(debugClientStateChanged(QmlDebug::QmlDebugClient::State)));
+ connect(debugClient2, &QmlV8DebuggerClient::newState,
+ this, &QmlAdapter::clientStateChanged);
+ connect(debugClient2, &QmlV8DebuggerClient::newState,
+ this, &QmlAdapter::debugClientStateChanged);
m_debugClients.insert(debugClient1->name(),debugClient1);
m_debugClients.insert(debugClient2->name(),debugClient2);
@@ -206,21 +210,21 @@ QDebugMessageClient *QmlAdapter::messageClient() const
}
void QmlAdapter::logServiceStateChange(const QString &service, float version,
- QmlDebug::QmlDebugClient::State newState)
+ QmlDebugClient::State newState)
{
switch (newState) {
- case QmlDebug::QmlDebugClient::Unavailable: {
+ case QmlDebugClient::Unavailable: {
showConnectionStateMessage(_("Status of \"%1\" Version: %2 changed to 'unavailable'.").
arg(service).arg(QString::number(version)));
break;
}
- case QmlDebug::QmlDebugClient::Enabled: {
+ case QmlDebugClient::Enabled: {
showConnectionStateMessage(_("Status of \"%1\" Version: %2 changed to 'enabled'.").
arg(service).arg(QString::number(version)));
break;
}
- case QmlDebug::QmlDebugClient::NotConnected: {
+ case QmlDebugClient::NotConnected: {
showConnectionStateMessage(_("Status of \"%1\" Version: %2 changed to 'not connected'.").
arg(service).arg(QString::number(version)));
break;
diff --git a/src/plugins/debugger/qml/qmladapter.h b/src/plugins/debugger/qml/qmladapter.h
index bba06ea8e43..e9f39368785 100644
--- a/src/plugins/debugger/qml/qmladapter.h
+++ b/src/plugins/debugger/qml/qmladapter.h
@@ -43,11 +43,10 @@ class QDebugMessageClient;
}
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
+
class BaseQmlDebuggerClient;
+class DebuggerEngine;
class QmlAdapterPrivate;
class QmlAdapter : public QObject
diff --git a/src/plugins/debugger/qml/qmlcppengine.cpp b/src/plugins/debugger/qml/qmlcppengine.cpp
index f6813113bed..1d01a19020d 100644
--- a/src/plugins/debugger/qml/qmlcppengine.cpp
+++ b/src/plugins/debugger/qml/qmlcppengine.cpp
@@ -30,8 +30,10 @@
#include "qmlcppengine.h"
#include "qmlengine.h"
+
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerstartparameters.h>
+#include <debugger/breakhandler.h>
#include <debugger/stackhandler.h>
#include <debugger/watchhandler.h>
@@ -184,9 +186,9 @@ void QmlCppEngine::reloadFullStack()
m_cppEngine->reloadFullStack();
}
-void QmlCppEngine::setRegisterValue(int regnr, const QString &value)
+void QmlCppEngine::setRegisterValue(const QByteArray &name, const QString &value)
{
- m_cppEngine->setRegisterValue(regnr, value);
+ m_cppEngine->setRegisterValue(name, value);
}
@@ -244,10 +246,10 @@ void QmlCppEngine::attemptBreakpointSynchronization()
}
}
-bool QmlCppEngine::acceptsBreakpoint(BreakpointModelId id) const
+bool QmlCppEngine::acceptsBreakpoint(Breakpoint bp) const
{
- return m_cppEngine->acceptsBreakpoint(id)
- || m_qmlEngine->acceptsBreakpoint(id);
+ return m_cppEngine->acceptsBreakpoint(bp)
+ || m_qmlEngine->acceptsBreakpoint(bp);
}
void QmlCppEngine::selectThread(ThreadId threadId)
@@ -285,26 +287,10 @@ void QmlCppEngine::detachDebugger()
void QmlCppEngine::executeStep()
{
-// TODO: stepping from qml -> cpp requires more thought
-// if (m_activeEngine == m_qmlEngine) {
-// QTC_CHECK(m_cppEngine->state() == InferiorRunOk);
-// if (m_cppEngine->setupQmlStep(true))
-// return; // Wait for callback to readyToExecuteQmlStep()
-// } else {
-// notifyInferiorRunRequested();
-// m_cppEngine->executeStep();
-// }
-
notifyInferiorRunRequested();
m_activeEngine->executeStep();
}
-void QmlCppEngine::readyToExecuteQmlStep()
-{
- notifyInferiorRunRequested();
- m_qmlEngine->executeStep();
-}
-
void QmlCppEngine::executeStepOut()
{
notifyInferiorRunRequested();
@@ -424,7 +410,6 @@ void QmlCppEngine::notifyInferiorShutdownOk()
void QmlCppEngine::notifyInferiorSetupOk()
{
EDEBUG("\nMASTER INFERIOR SETUP OK");
- emit aboutToNotifyInferiorSetupOk();
DebuggerEngine::notifyInferiorSetupOk();
}
@@ -774,6 +759,18 @@ void QmlCppEngine::resetLocation()
DebuggerEngine::resetLocation();
}
+void QmlCppEngine::reloadDebuggingHelpers()
+{
+ if (m_cppEngine)
+ m_cppEngine->reloadDebuggingHelpers();
+}
+
+void QmlCppEngine::debugLastCommand()
+{
+ if (m_cppEngine)
+ m_cppEngine->debugLastCommand();
+}
+
DebuggerEngine *QmlCppEngine::cppEngine() const
{
return m_cppEngine;
diff --git a/src/plugins/debugger/qml/qmlcppengine.h b/src/plugins/debugger/qml/qmlcppengine.h
index 665d343119e..898803ee69a 100644
--- a/src/plugins/debugger/qml/qmlcppengine.h
+++ b/src/plugins/debugger/qml/qmlcppengine.h
@@ -68,7 +68,7 @@ public:
void reloadSourceFiles();
void reloadFullStack();
- void setRegisterValue(int regnr, const QString &value);
+ void setRegisterValue(const QByteArray &name, const QString &value);
bool hasCapability(unsigned cap) const;
bool isSynchronous() const;
@@ -78,7 +78,7 @@ public:
void updateAll();
void attemptBreakpointSynchronization();
- bool acceptsBreakpoint(BreakpointModelId id) const;
+ bool acceptsBreakpoint(Breakpoint bp) const;
void selectThread(ThreadId threadId);
void assignValueInDebugger(const WatchData *data,
@@ -97,6 +97,8 @@ public:
protected:
void detachDebugger();
+ void reloadDebuggingHelpers();
+ void debugLastCommand();
void executeStep();
void executeStepOut();
void executeNext();
@@ -128,15 +130,11 @@ protected:
void notifyInferiorSetupOk();
void notifyEngineRemoteServerRunning(const QByteArray &, int pid);
-signals:
- void aboutToNotifyInferiorSetupOk();
-
private:
void engineStateChanged(DebuggerState newState);
void setState(DebuggerState newState, bool forced = false);
void slaveEngineStateChanged(DebuggerEngine *slaveEngine, DebuggerState state);
- void readyToExecuteQmlStep();
void setActiveEngine(DebuggerEngine *engine);
private:
diff --git a/src/plugins/debugger/qml/qmlengine.cpp b/src/plugins/debugger/qml/qmlengine.cpp
index 4924fce386c..8f8422d14d6 100644
--- a/src/plugins/debugger/qml/qmlengine.cpp
+++ b/src/plugins/debugger/qml/qmlengine.cpp
@@ -249,9 +249,9 @@ public:
quint32 *column;
};
-QmlJS::ConsoleManagerInterface *qmlConsoleManager()
+ConsoleManagerInterface *qmlConsoleManager()
{
- return QmlJS::ConsoleManagerInterface::instance();
+ return ConsoleManagerInterface::instance();
}
///////////////////////////////////////////////////////////////////////
@@ -351,12 +351,6 @@ QmlEngine::~QmlEngine()
Core::EditorManager::closeDocuments(documentsToClose.toList());
}
-void QmlEngine::notifyInferiorSetupOk()
-{
- emit aboutToNotifyInferiorSetupOk();
- DebuggerEngine::notifyInferiorSetupOk();
-}
-
void QmlEngine::setupInferior()
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
@@ -803,21 +797,20 @@ void QmlEngine::selectThread(ThreadId threadId)
Q_UNUSED(threadId)
}
-void QmlEngine::insertBreakpoint(BreakpointModelId id)
+void QmlEngine::insertBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- BreakpointState state = handler->state(id);
- QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << id << this << state);
- handler->notifyBreakpointInsertProceeding(id);
+ BreakpointState state = bp.state();
+ QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << bp << this << state);
+ bp.notifyBreakpointInsertProceeding();
- const BreakpointParameters &params = handler->breakpointData(id);
+ const BreakpointParameters &params = bp.parameters();
quint32 line = params.lineNumber;
quint32 column = 0;
if (params.type == BreakpointByFileAndLine) {
bool valid = false;
if (!adjustBreakpointLineAndColumn(params.fileName, &line, &column,
&valid)) {
- pendingBreakpoints.insertMulti(params.fileName, id);
+ pendingBreakpoints.insertMulti(params.fileName, bp);
return;
}
if (!valid)
@@ -825,65 +818,61 @@ void QmlEngine::insertBreakpoint(BreakpointModelId id)
}
if (m_adapter.activeDebuggerClient()) {
- m_adapter.activeDebuggerClient()->insertBreakpoint(id, line, column);
+ m_adapter.activeDebuggerClient()->insertBreakpoint(bp, line, column);
} else {
foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
- client->insertBreakpoint(id, line, column);
+ client->insertBreakpoint(bp, line, column);
}
}
}
-void QmlEngine::removeBreakpoint(BreakpointModelId id)
+void QmlEngine::removeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
-
- const BreakpointParameters &params = handler->breakpointData(id);
+ const BreakpointParameters &params = bp.parameters();
if (params.type == BreakpointByFileAndLine &&
pendingBreakpoints.contains(params.fileName)) {
- QHash<QString, BreakpointModelId>::iterator i =
- pendingBreakpoints.find(params.fileName);
- while (i != pendingBreakpoints.end() && i.key() == params.fileName) {
- if (i.value() == id) {
- pendingBreakpoints.erase(i);
+ auto it = pendingBreakpoints.find(params.fileName);
+ while (it != pendingBreakpoints.end() && it.key() == params.fileName) {
+ if (it.value() == bp.id()) {
+ pendingBreakpoints.erase(it);
return;
}
- ++i;
+ ++it;
}
}
- BreakpointState state = handler->state(id);
- QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << id << this << state);
- handler->notifyBreakpointRemoveProceeding(id);
+ BreakpointState state = bp.state();
+ QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << bp << this << state);
+ bp.notifyBreakpointRemoveProceeding();
if (m_adapter.activeDebuggerClient()) {
- m_adapter.activeDebuggerClient()->removeBreakpoint(id);
+ m_adapter.activeDebuggerClient()->removeBreakpoint(bp);
} else {
foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
- client->removeBreakpoint(id);
+ client->removeBreakpoint(bp);
}
}
- if (handler->state(id) == BreakpointRemoveProceeding)
- handler->notifyBreakpointRemoveOk(id);
+ if (bp.state() == BreakpointRemoveProceeding)
+ bp.notifyBreakpointRemoveOk();
}
-void QmlEngine::changeBreakpoint(BreakpointModelId id)
+void QmlEngine::changeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = breakHandler();
- BreakpointState state = handler->state(id);
- QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << id << this << state);
- handler->notifyBreakpointChangeProceeding(id);
+ BreakpointState state = bp.state();
+ QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << bp << this << state);
+ bp.notifyBreakpointChangeProceeding();
if (m_adapter.activeDebuggerClient()) {
- m_adapter.activeDebuggerClient()->changeBreakpoint(id);
+ m_adapter.activeDebuggerClient()->changeBreakpoint(bp);
} else {
foreach (BaseQmlDebuggerClient *client, m_adapter.debuggerClients()) {
- client->changeBreakpoint(id);
+ client->changeBreakpoint(bp);
}
}
- if (handler->state(id) == BreakpointChangeProceeding)
- handler->notifyBreakpointChangeOk(id);
+ if (bp.state() == BreakpointChangeProceeding)
+ bp.notifyBreakpointChangeOk();
}
void QmlEngine::attemptBreakpointSynchronization()
@@ -896,26 +885,26 @@ void QmlEngine::attemptBreakpointSynchronization()
BreakHandler *handler = breakHandler();
DebuggerEngine *bpOwner = isSlaveEngine() ? masterEngine() : this;
- foreach (BreakpointModelId id, handler->unclaimedBreakpointIds()) {
+ foreach (Breakpoint bp, handler->unclaimedBreakpoints()) {
// Take ownership of the breakpoint. Requests insertion.
- if (acceptsBreakpoint(id))
- handler->setEngine(id, bpOwner);
+ if (acceptsBreakpoint(bp))
+ bp.setEngine(bpOwner);
}
- foreach (BreakpointModelId id, handler->engineBreakpointIds(bpOwner)) {
- switch (handler->state(id)) {
+ foreach (Breakpoint bp, handler->engineBreakpoints(bpOwner)) {
+ switch (bp.state()) {
case BreakpointNew:
// Should not happen once claimed.
QTC_CHECK(false);
continue;
case BreakpointInsertRequested:
- insertBreakpoint(id);
+ insertBreakpoint(bp);
continue;
case BreakpointChangeRequested:
- changeBreakpoint(id);
+ changeBreakpoint(bp);
continue;
case BreakpointRemoveRequested:
- removeBreakpoint(id);
+ removeBreakpoint(bp);
continue;
case BreakpointChangeProceeding:
case BreakpointInsertProceeding:
@@ -924,7 +913,7 @@ void QmlEngine::attemptBreakpointSynchronization()
case BreakpointDead:
continue;
}
- QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << id << state());
+ QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << bp << state());
}
DebuggerEngine::attemptBreakpointSynchronization();
@@ -938,9 +927,9 @@ void QmlEngine::attemptBreakpointSynchronization()
}
}
-bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
+bool QmlEngine::acceptsBreakpoint(Breakpoint bp) const
{
- if (!breakHandler()->breakpointData(id).isCppBreakpoint())
+ if (!bp.parameters().isCppBreakpoint())
return true;
//If it is a Cpp Breakpoint query if the type can be also handled by the debugger client
@@ -949,7 +938,7 @@ bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
//This is because the older client does not support BreakpointOnQmlSignalHandler
bool acceptBreakpoint = false;
if (m_adapter.activeDebuggerClient())
- acceptBreakpoint = m_adapter.activeDebuggerClient()->acceptsBreakpoint(id);
+ acceptBreakpoint = m_adapter.activeDebuggerClient()->acceptsBreakpoint(bp);
return acceptBreakpoint;
}
@@ -1052,7 +1041,7 @@ void QmlEngine::synchronizeWatchers()
}
}
-QmlJS::ConsoleItem *constructLogItemTree(QmlJS::ConsoleItem *parent,
+ConsoleItem *constructLogItemTree(ConsoleItem *parent,
const QVariant &result,
const QString &key = QString())
{
@@ -1146,14 +1135,14 @@ void QmlEngine::disconnected()
notifyInferiorExited();
}
-void QmlEngine::documentUpdated(QmlJS::Document::Ptr doc)
+void QmlEngine::documentUpdated(Document::Ptr doc)
{
QString fileName = doc->fileName();
if (pendingBreakpoints.contains(fileName)) {
- QList<BreakpointModelId> ids = pendingBreakpoints.values(fileName);
+ QList<Breakpoint> bps = pendingBreakpoints.values(fileName);
pendingBreakpoints.remove(fileName);
- foreach (const BreakpointModelId &id, ids)
- insertBreakpoint(id);
+ foreach (const Breakpoint bp, bps)
+ insertBreakpoint(bp);
}
}
@@ -1178,7 +1167,7 @@ void QmlEngine::updateCurrentContext()
synchronizeWatchers();
- QmlJS::ConsoleManagerInterface *consoleManager = qmlConsoleManager();
+ ConsoleManagerInterface *consoleManager = qmlConsoleManager();
if (consoleManager)
consoleManager->setContext(tr("Context:") + QLatin1Char(' ') + context);
}
diff --git a/src/plugins/debugger/qml/qmlengine.h b/src/plugins/debugger/qml/qmlengine.h
index 9b8b9987bf0..baddc4ae65a 100644
--- a/src/plugins/debugger/qml/qmlengine.h
+++ b/src/plugins/debugger/qml/qmlengine.h
@@ -60,7 +60,6 @@ public:
DebuggerEngine *masterEngine = 0);
~QmlEngine();
- void notifyInferiorSetupOk();
void notifyEngineRemoteServerRunning(const QByteArray &, int pid);
void notifyEngineRemoteSetupFinished(const RemoteSetupResult &result);
@@ -85,12 +84,11 @@ public:
void updateScriptSource(const QString &fileName, int lineOffset,
int columnOffset, const QString &source);
- void insertBreakpoint(BreakpointModelId id);
+ void insertBreakpoint(Breakpoint bp);
signals:
void tooltipRequested(const QPoint &mousePos,
TextEditor::TextEditorWidget *editorWidget, int cursorPos);
- void aboutToNotifyInferiorSetupOk();
private slots:
void disconnected();
@@ -142,9 +140,9 @@ private:
void selectThread(ThreadId threadId);
void attemptBreakpointSynchronization();
- void removeBreakpoint(BreakpointModelId id);
- void changeBreakpoint(BreakpointModelId id);
- bool acceptsBreakpoint(BreakpointModelId id) const;
+ void removeBreakpoint(Breakpoint bp);
+ void changeBreakpoint(Breakpoint bp);
+ bool acceptsBreakpoint(Breakpoint bp) const;
void assignValueInDebugger(const WatchData *data,
const QString &expr, const QVariant &value);
@@ -192,7 +190,7 @@ private:
QHash<QString, QTextDocument*> m_sourceDocuments;
QHash<QString, QWeakPointer<TextEditor::BaseTextEditor> > m_sourceEditors;
InteractiveInterpreter m_interpreter;
- QHash<QString,BreakpointModelId> pendingBreakpoints;
+ QHash<QString,Breakpoint> pendingBreakpoints;
QList<quint32> queryIds;
bool m_retryOnConnectFail;
bool m_automaticConnect;
diff --git a/src/plugins/debugger/qml/qmlinspectoradapter.cpp b/src/plugins/debugger/qml/qmlinspectoradapter.cpp
index 3c711f98e75..08edb3588b1 100644
--- a/src/plugins/debugger/qml/qmlinspectoradapter.cpp
+++ b/src/plugins/debugger/qml/qmlinspectoradapter.cpp
@@ -299,7 +299,7 @@ void QmlInspectorAdapter::createPreviewForEditor(Core::IEditor *newEditor)
!= QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
return;
- QString filename = newEditor->document()->filePath();
+ QString filename = newEditor->document()->filePath().toString();
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()->filePath(), preview);
+ m_textPreviews.insert(newEditor->document()->filePath().toString(), 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()->filePath())) {
+ = m_textPreviews.value(editor->document()->filePath().toString())) {
preview->unassociateEditor(editor);
}
}
@@ -364,7 +364,7 @@ void QmlInspectorAdapter::updatePendingPreviewDocuments(QmlJS::Document::Ptr doc
Core::IEditor *editor = editors.takeFirst();
createPreviewForEditor(editor);
QmlLiveTextPreview *preview
- = m_textPreviews.value(editor->document()->filePath());
+ = m_textPreviews.value(editor->document()->filePath().toString());
foreach (Core::IEditor *editor, editors)
preview->associateEditor(editor);
}
@@ -460,7 +460,7 @@ void QmlInspectorAdapter::initializePreviews()
QList<Core::IEditor *> editors = Core::DocumentModel::editorsForDocument(document);
createPreviewForEditor(editors.takeFirst());
QmlLiveTextPreview *preview
- = m_textPreviews.value(document->filePath());
+ = m_textPreviews.value(document->filePath().toString());
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 6a481dd9262..a39f196aba6 100644
--- a/src/plugins/debugger/qml/qmlinspectoradapter.h
+++ b/src/plugins/debugger/qml/qmlinspectoradapter.h
@@ -47,11 +47,9 @@ class FileReference;
}
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
+class DebuggerEngine;
class WatchTreeView;
class QmlAdapter;
class QmlInspectorAgent;
diff --git a/src/plugins/debugger/qml/qmlinspectoragent.cpp b/src/plugins/debugger/qml/qmlinspectoragent.cpp
index 4bf64ed3123..0e34026b378 100644
--- a/src/plugins/debugger/qml/qmlinspectoragent.cpp
+++ b/src/plugins/debugger/qml/qmlinspectoragent.cpp
@@ -37,11 +37,11 @@
#include <debugger/watchhandler.h>
#include <qmldebug/qmldebugconstants.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
#include <QElapsedTimer>
-#include <QFileInfo>
#include <QLoggingCategory>
using namespace QmlDebug;
@@ -68,7 +68,8 @@ QmlInspectorAgent::QmlInspectorAgent(DebuggerEngine *engine, QObject *parent)
SIGNAL(valueChanged(QVariant)), SLOT(updateState()));
m_delayQueryTimer.setSingleShot(true);
m_delayQueryTimer.setInterval(100);
- connect(&m_delayQueryTimer, SIGNAL(timeout()), SLOT(queryEngineContext()));
+ connect(&m_delayQueryTimer, &QTimer::timeout,
+ this, &QmlInspectorAgent::queryEngineContext);
}
quint32 QmlInspectorAgent::queryExpressionResult(int debugId,
@@ -395,14 +396,14 @@ void QmlInspectorAgent::setEngineClient(BaseEngineDebugClient *client)
m_engineClient = client;
if (m_engineClient) {
- connect(m_engineClient, SIGNAL(newState(QmlDebug::QmlDebugClient::State)),
- this, SLOT(updateState()));
- connect(m_engineClient, SIGNAL(result(quint32,QVariant,QByteArray)),
- this, SLOT(onResult(quint32,QVariant,QByteArray)));
- connect(m_engineClient, SIGNAL(newObject(int,int,int)),
- this, SLOT(newObject(int,int,int)));
- connect(m_engineClient, SIGNAL(valueChanged(int,QByteArray,QVariant)),
- this, SLOT(onValueChanged(int,QByteArray,QVariant)));
+ connect(m_engineClient, &BaseEngineDebugClient::newState,
+ this, &QmlInspectorAgent::updateState);
+ connect(m_engineClient, &BaseEngineDebugClient::result,
+ this, &QmlInspectorAgent::onResult);
+ connect(m_engineClient, &BaseEngineDebugClient::newObject,
+ this, &QmlInspectorAgent::newObject);
+ connect(m_engineClient, &BaseEngineDebugClient::valueChanged,
+ this, &QmlInspectorAgent::onValueChanged);
}
updateState();
@@ -583,7 +584,7 @@ void QmlInspectorAgent::fetchContextObjectsForLocation(const QString &file,
log(LogSend, QString::fromLatin1("FETCH_OBJECTS_FOR_LOCATION %1:%2:%3").arg(file)
.arg(QString::number(lineNumber)).arg(QString::number(columnNumber)));
- quint32 queryId = m_engineClient->queryObjectsForLocation(QFileInfo(file).fileName(),
+ quint32 queryId = m_engineClient->queryObjectsForLocation(Utils::FileName::fromString(file).fileName(),
lineNumber, columnNumber);
qCDebug(qmlInspectorLog) << __FUNCTION__ << '(' << file << ':' << lineNumber
<< ':' << columnNumber << ')' << " - query id" << queryId;
diff --git a/src/plugins/debugger/qml/qmlinspectoragent.h b/src/plugins/debugger/qml/qmlinspectoragent.h
index 3c19a19c4ae..3c01307f150 100644
--- a/src/plugins/debugger/qml/qmlinspectoragent.h
+++ b/src/plugins/debugger/qml/qmlinspectoragent.h
@@ -37,11 +37,9 @@
#include <qmldebug/baseenginedebugclient.h>
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
+class DebuggerEngine;
class WatchData;
//map <filename, editorRevision> -> <lineNumber, columnNumber> -> debugId
diff --git a/src/plugins/debugger/qml/qmllivetextpreview.cpp b/src/plugins/debugger/qml/qmllivetextpreview.cpp
index 6877d373bd3..80ef6220c77 100644
--- a/src/plugins/debugger/qml/qmllivetextpreview.cpp
+++ b/src/plugins/debugger/qml/qmllivetextpreview.cpp
@@ -346,8 +346,8 @@ void MapObjectWithDebugReference::process(UiObjectBinding *ast)
/*!
* Manages a Qml/JS document for the inspector
*/
-QmlLiveTextPreview::QmlLiveTextPreview(const QmlJS::Document::Ptr &doc,
- const QmlJS::Document::Ptr &initDoc,
+QmlLiveTextPreview::QmlLiveTextPreview(const Document::Ptr &doc,
+ const Document::Ptr &initDoc,
QmlInspectorAdapter *inspectorAdapter,
QObject *parent)
: QObject(parent)
@@ -362,8 +362,8 @@ QmlLiveTextPreview::QmlLiveTextPreview(const QmlJS::Document::Ptr &doc,
{
QTC_CHECK(doc->fileName() == initDoc->fileName());
- QmlJS::ModelManagerInterface *modelManager
- = QmlJS::ModelManagerInterface::instance();
+ ModelManagerInterface *modelManager
+ = ModelManagerInterface::instance();
if (modelManager) {
connect(modelManager, SIGNAL(documentChangedOnDisk(QmlJS::Document::Ptr)),
SLOT(documentChanged(QmlJS::Document::Ptr)));
@@ -424,7 +424,7 @@ void QmlLiveTextPreview::unassociateEditor(Core::IEditor *oldEditor)
}
}
-void QmlLiveTextPreview::resetInitialDoc(const QmlJS::Document::Ptr &doc)
+void QmlLiveTextPreview::resetInitialDoc(const Document::Ptr &doc)
{
m_initialDoc = doc;
m_previousDoc = doc;
@@ -463,7 +463,7 @@ void QmlLiveTextPreview::updateDebugIds()
if (it != m_inspectorAdapter->agent()->debugIdHash().constEnd()) {
// Map all the object that comes from the document as it has been loaded
// by the server.
- const QmlJS::Document::Ptr &doc = m_initialDoc;
+ const Document::Ptr &doc = m_initialDoc;
MapObjectWithDebugReference visitor;
visitor.ids = (*it);
@@ -477,7 +477,7 @@ void QmlLiveTextPreview::updateDebugIds()
}
}
- const QmlJS::Document::Ptr &doc = m_previousDoc;
+ const Document::Ptr &doc = m_previousDoc;
if (!doc->qmlProgram())
return;
@@ -500,7 +500,7 @@ void QmlLiveTextPreview::updateDebugIds()
= m_createdObjects.constBegin();
it != m_createdObjects.constEnd(); ++it) {
- const QmlJS::Document::Ptr &doc = it.key();
+ const Document::Ptr &doc = it.key();
DebugIdHash::const_iterator id_it = m_inspectorAdapter->agent()->debugIdHash().constFind(
qMakePair<QString, int>(doc->fileName(), doc->editorRevision()));
@@ -527,14 +527,14 @@ void QmlLiveTextPreview::updateDebugIds()
changeSelectedElements(m_lastOffsets, QString());
}
-void QmlLiveTextPreview::changeSelectedElements(const QList<QmlJS::AST::UiObjectMember*> offsetObjects,
+void QmlLiveTextPreview::changeSelectedElements(const QList<UiObjectMember*> offsetObjects,
const QString &wordAtCursor)
{
if (m_editors.isEmpty() || !m_previousDoc)
return;
QList<int> offsets;
- foreach (QmlJS::AST::UiObjectMember *member, offsetObjects)
+ foreach (UiObjectMember *member, offsetObjects)
offsets << member->firstSourceLocation().offset;
if (!changeSelectedElements(offsets, wordAtCursor) && m_initialDoc && offsetObjects.count()) {
@@ -588,7 +588,7 @@ bool QmlLiveTextPreview::changeSelectedElements(const QList<int> offsets,
return true;
}
-void QmlLiveTextPreview::documentChanged(QmlJS::Document::Ptr doc)
+void QmlLiveTextPreview::documentChanged(Document::Ptr doc)
{
if (doc->fileName() != m_previousDoc->fileName())
return;
@@ -650,11 +650,11 @@ void QmlLiveTextPreview::onAutomaticUpdateFailed()
QList<int> QmlLiveTextPreview::objectReferencesForOffset(quint32 offset)
{
QList<int> result;
- QHashIterator<QmlJS::AST::UiObjectMember*, QList<int> > iter(m_debugIds);
- QmlJS::AST::UiObjectMember *possibleNode = 0;
+ QHashIterator<UiObjectMember*, QList<int> > iter(m_debugIds);
+ UiObjectMember *possibleNode = 0;
while (iter.hasNext()) {
iter.next();
- QmlJS::AST::UiObjectMember *member = iter.key();
+ UiObjectMember *member = iter.key();
quint32 startOffset = member->firstSourceLocation().offset;
quint32 endOffset = member->lastSourceLocation().offset;
if (startOffset <= offset && offset <= endOffset) {
diff --git a/src/plugins/debugger/qml/qmlv8debuggerclient.cpp b/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
index f4c08164507..0e119956ca1 100644
--- a/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
+++ b/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
@@ -471,7 +471,7 @@ void QmlV8DebuggerClientPrivate::setBreakpoint(const QString type, const QString
args.setProperty(_(TYPE), QScriptValue(type));
if (type == _(SCRIPTREGEXP))
args.setProperty(_(TARGET),
- QScriptValue(QFileInfo(target).fileName()));
+ QScriptValue(Utils::FileName::fromString(target).fileName()));
else
args.setProperty(_(TARGET), QScriptValue(target));
@@ -842,23 +842,22 @@ void QmlV8DebuggerClient::activateFrame(int index)
d->engine->stackHandler()->setCurrentIndex(index);
}
-bool QmlV8DebuggerClient::acceptsBreakpoint(const BreakpointModelId &id)
+bool QmlV8DebuggerClient::acceptsBreakpoint(Breakpoint bp)
{
- BreakpointType type = d->engine->breakHandler()->breakpointData(id).type;
+ BreakpointType type = bp.type();
return (type == BreakpointOnQmlSignalEmit
|| type == BreakpointByFileAndLine
|| type == BreakpointAtJavaScriptThrow);
}
-void QmlV8DebuggerClient::insertBreakpoint(const BreakpointModelId &id,
+void QmlV8DebuggerClient::insertBreakpoint(Breakpoint bp,
int adjustedLine,
int adjustedColumn)
{
- BreakHandler *handler = d->engine->breakHandler();
- const BreakpointParameters &params = handler->breakpointData(id);
+ const BreakpointParameters &params = bp.parameters();
if (params.type == BreakpointAtJavaScriptThrow) {
- handler->notifyBreakpointInsertOk(id);
+ bp.notifyBreakpointInsertOk();
d->setExceptionBreak(AllExceptions, params.enabled);
} else if (params.type == BreakpointByFileAndLine) {
@@ -868,19 +867,18 @@ void QmlV8DebuggerClient::insertBreakpoint(const BreakpointModelId &id,
} else if (params.type == BreakpointOnQmlSignalEmit) {
d->setBreakpoint(QString(_(EVENT)), params.functionName, params.enabled);
- d->engine->breakHandler()->notifyBreakpointInsertOk(id);
+ bp.notifyBreakpointInsertOk();
}
- d->breakpointsSync.insert(d->sequence, id);
+ d->breakpointsSync.insert(d->sequence, bp.id());
}
-void QmlV8DebuggerClient::removeBreakpoint(const BreakpointModelId &id)
+void QmlV8DebuggerClient::removeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = d->engine->breakHandler();
- const BreakpointParameters &params = handler->breakpointData(id);
+ const BreakpointParameters &params = bp.parameters();
- int breakpoint = d->breakpoints.value(id);
- d->breakpoints.remove(id);
+ int breakpoint = d->breakpoints.value(bp.id());
+ d->breakpoints.remove(bp.id());
if (params.type == BreakpointAtJavaScriptThrow)
d->setExceptionBreak(AllExceptions);
@@ -890,25 +888,25 @@ void QmlV8DebuggerClient::removeBreakpoint(const BreakpointModelId &id)
d->clearBreakpoint(breakpoint);
}
-void QmlV8DebuggerClient::changeBreakpoint(const BreakpointModelId &id)
+void QmlV8DebuggerClient::changeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = d->engine->breakHandler();
- const BreakpointParameters &params = handler->breakpointData(id);
+ const BreakpointParameters &params = bp.parameters();
- BreakpointResponse br = handler->response(id);
+ BreakpointResponse br = bp.response();
if (params.type == BreakpointAtJavaScriptThrow) {
d->setExceptionBreak(AllExceptions, params.enabled);
br.enabled = params.enabled;
- handler->setResponse(id, br);
+ bp.setResponse(br);
} else if (params.type == BreakpointOnQmlSignalEmit) {
d->setBreakpoint(QString(_(EVENT)), params.functionName, params.enabled);
br.enabled = params.enabled;
- handler->setResponse(id, br);
+ bp.setResponse(br);
} else {
//V8 supports only minimalistic changes in breakpoint
//Remove the breakpoint and add again
- handler->notifyBreakpointChangeOk(id);
- handler->removeBreakpoint(id);
+ bp.notifyBreakpointChangeOk();
+ bp.removeBreakpoint();
+ BreakHandler *handler = d->engine->breakHandler();
handler->appendBreakpoint(params);
}
}
@@ -984,7 +982,8 @@ void QmlV8DebuggerClient::expandObject(const QByteArray &iname, quint64 objectId
void QmlV8DebuggerClient::setEngine(QmlEngine *engine)
{
d->engine = engine;
- connect(this, SIGNAL(stackFrameCompleted()), engine, SIGNAL(stackFrameCompleted()));
+ connect(this, &QmlV8DebuggerClient::stackFrameCompleted,
+ engine, &QmlEngine::stackFrameCompleted);
}
void QmlV8DebuggerClient::getSourceFiles()
@@ -1086,12 +1085,12 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
//The breakpoint requested line should be same as
//actual line
BreakHandler *handler = d->engine->breakHandler();
- if (handler->state(id) != BreakpointInserted) {
- BreakpointResponse br = handler->response(id);
- br.lineNumber = breakpointData.value(_("line")
- ).toInt() + 1;
- handler->setResponse(id, br);
- handler->notifyBreakpointInsertOk(id);
+ Breakpoint bp = handler->breakpointById(id);
+ if (bp.state() != BreakpointInserted) {
+ BreakpointResponse br = bp.response();
+ br.lineNumber = breakpointData.value(_("line")).toInt() + 1;
+ bp.setResponse(br);
+ bp.notifyBreakpointInsertOk();
}
}
@@ -1211,10 +1210,10 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
BreakHandler *handler = d->engine->breakHandler();
foreach (int v8Id, v8BreakpointIds) {
- const BreakpointModelId internalId = d->breakpoints.key(v8Id);
-
- if (internalId.isValid()) {
- const BreakpointParameters &params = handler->breakpointData(internalId);
+ const BreakpointModelId id = d->breakpoints.key(v8Id);
+ Breakpoint bp = handler->breakpointById(id);
+ if (bp.isValid()) {
+ const BreakpointParameters &params = bp.parameters();
d->clearBreakpoint(v8Id);
d->setBreakpoint(QString(_(SCRIPTREGEXP)),
@@ -1224,7 +1223,7 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
newColumn,
QString(QString::fromLatin1(params.condition)),
params.ignoreCount);
- d->breakpointsSync.insert(d->sequence, internalId);
+ d->breakpointsSync.insert(d->sequence, id);
}
}
d->continueDebugging(Continue);
@@ -1242,17 +1241,18 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
BreakHandler *handler = d->engine->breakHandler();
foreach (int v8Id, v8BreakpointIds) {
const BreakpointModelId id = d->breakpoints.key(v8Id);
- if (id.isValid()) {
- BreakpointResponse br = handler->response(id);
+ Breakpoint bp = handler->breakpointById(id);
+ if (bp) {
+ BreakpointResponse br = bp.response();
if (br.functionName.isEmpty()) {
br.functionName = invocationText;
- handler->setResponse(id, br);
+ bp.setResponse(br);
}
- if (handler->state(id) != BreakpointInserted) {
+ if (bp.state() != BreakpointInserted) {
br.lineNumber = breakData.value(
_("sourceLine")).toInt() + 1;
- handler->setResponse(id, br);
- handler->notifyBreakpointInsertOk(id);
+ bp.setResponse(br);
+ bp.notifyBreakpointInsertOk();
}
}
}
diff --git a/src/plugins/debugger/qml/qmlv8debuggerclient.h b/src/plugins/debugger/qml/qmlv8debuggerclient.h
index 07f360c9d90..524084a11f9 100644
--- a/src/plugins/debugger/qml/qmlv8debuggerclient.h
+++ b/src/plugins/debugger/qml/qmlv8debuggerclient.h
@@ -77,11 +77,11 @@ public:
void activateFrame(int index);
- bool acceptsBreakpoint(const BreakpointModelId &id);
- void insertBreakpoint(const BreakpointModelId &id, int adjustedLine,
+ bool acceptsBreakpoint(Breakpoint bp);
+ void insertBreakpoint(Breakpoint bp, int adjustedLine,
int adjustedColumn = -1);
- void removeBreakpoint(const BreakpointModelId &id);
- void changeBreakpoint(const BreakpointModelId &id);
+ void removeBreakpoint(Breakpoint bp);
+ void changeBreakpoint(Breakpoint bp);
void synchronizeBreakpoints();
void assignValueInDebugger(const WatchData *data,
diff --git a/src/plugins/debugger/qml/qscriptdebuggerclient.cpp b/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
index 20944d90836..923a1bcb890 100644
--- a/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
+++ b/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
@@ -37,8 +37,9 @@
#include <debugger/debuggerstringutils.h>
#include <qmldebug/qmldebugclient.h>
+#include <coreplugin/messagebox.h>
+
#include <QFileInfo>
-#include <QMessageBox>
#include <utils/qtcassert.h>
using QmlDebug::QmlDebugStream;
@@ -219,9 +220,9 @@ void QScriptDebuggerClient::startSession()
BreakHandler *handler = d->engine->breakHandler();
DebuggerEngine * engine = d->engine->isSlaveEngine() ?
d->engine->masterEngine() : d->engine;
- foreach (BreakpointModelId id, handler->engineBreakpointIds(engine)) {
- QTC_CHECK(handler->state(id) == BreakpointInsertProceeding);
- handler->notifyBreakpointInsertOk(id);
+ foreach (Breakpoint bp, handler->engineBreakpoints(engine)) {
+ QTC_CHECK(bp.state() == BreakpointInsertProceeding);
+ bp.notifyBreakpointInsertOk();
}
d->sessionStarted = true;
}
@@ -246,46 +247,42 @@ void QScriptDebuggerClient::activateFrame(int index)
sendMessage(reply);
}
-void QScriptDebuggerClient::insertBreakpoint(const BreakpointModelId &id,
+void QScriptDebuggerClient::insertBreakpoint(Breakpoint bp,
int adjustedLine,
int /*adjustedColumn*/)
{
- BreakHandler *handler = d->engine->breakHandler();
- JSAgentBreakpointData bp;
- bp.fileUrl = QUrl::fromLocalFile(handler->fileName(id)).toString().toUtf8();
- bp.lineNumber = adjustedLine;
- bp.functionName = handler->functionName(id).toUtf8();
- d->breakpoints.insert(bp);
+ JSAgentBreakpointData jsbp;
+ jsbp.fileUrl = QUrl::fromLocalFile(bp.fileName()).toString().toUtf8();
+ jsbp.lineNumber = adjustedLine;
+ jsbp.functionName = bp.functionName().toUtf8();
+ d->breakpoints.insert(jsbp);
- BreakpointResponse br = handler->response(id);
+ BreakpointResponse br = bp.response();
br.lineNumber = adjustedLine;
- handler->setResponse(id, br);
- if (d->sessionStarted && handler->state(id) == BreakpointInsertProceeding)
- handler->notifyBreakpointInsertOk(id);
+ bp.setResponse(br);
+ if (d->sessionStarted && bp.state() == BreakpointInsertProceeding)
+ bp.notifyBreakpointInsertOk();
}
-void QScriptDebuggerClient::removeBreakpoint(const BreakpointModelId &id)
+void QScriptDebuggerClient::removeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = d->engine->breakHandler();
- JSAgentBreakpointData bp;
- bp.fileUrl = QUrl::fromLocalFile(handler->fileName(id)).toString().toUtf8();
- bp.lineNumber = handler->lineNumber(id);
- bp.functionName = handler->functionName(id).toUtf8();
- d->breakpoints.remove(bp);
+ JSAgentBreakpointData jsbp;
+ jsbp.fileUrl = QUrl::fromLocalFile(bp.fileName()).toString().toUtf8();
+ jsbp.lineNumber = bp.lineNumber();
+ jsbp.functionName = bp.functionName().toUtf8();
+ d->breakpoints.remove(jsbp);
}
-void QScriptDebuggerClient::changeBreakpoint(const BreakpointModelId &id)
+void QScriptDebuggerClient::changeBreakpoint(Breakpoint bp)
{
- BreakHandler *handler = d->engine->breakHandler();
- if (handler->isEnabled(id)) {
- BreakpointResponse br = handler->response(id);
- insertBreakpoint(id, br.lineNumber);
- } else {
- removeBreakpoint(id);
- }
- BreakpointResponse br = handler->response(id);
- br.enabled = handler->isEnabled(id);
- handler->setResponse(id, br);
+ if (bp.isEnabled())
+ insertBreakpoint(bp, bp.response().lineNumber);
+ else
+ removeBreakpoint(bp);
+
+ BreakpointResponse br = bp.response();
+ br.enabled = bp.isEnabled();
+ bp.setResponse(br);
}
void QScriptDebuggerClient::synchronizeBreakpoints()
@@ -448,7 +445,7 @@ void QScriptDebuggerClient::messageReceived(const QByteArray &data)
.arg(error.toHtmlEscaped())
: tr("<p>An uncaught exception occurred in \"%1\":</p><p>%2</p>")
.arg(QLatin1String(stackFrames.value(0).fileUrl), error.toHtmlEscaped());
- showMessageBox(QMessageBox::Information, tr("Uncaught Exception"), msg);
+ Core::AsynchronousMessageBox::information(tr("Uncaught Exception"), msg);
} else {
QString file;
int line = -1;
@@ -585,7 +582,8 @@ void QScriptDebuggerClient::insertLocalsAndWatches(QList<WatchData> &locals,
void QScriptDebuggerClient::setEngine(QmlEngine *engine)
{
d->engine = engine;
- connect(this, SIGNAL(stackFrameCompleted()), engine, SIGNAL(stackFrameCompleted()));
+ connect(this, &QScriptDebuggerClient::stackFrameCompleted,
+ engine, &DebuggerEngine::stackFrameCompleted);
}
void QScriptDebuggerClientPrivate::logSendMessage(const QString &msg) const
diff --git a/src/plugins/debugger/qml/qscriptdebuggerclient.h b/src/plugins/debugger/qml/qscriptdebuggerclient.h
index 7865bc6b688..a09a1839c2d 100644
--- a/src/plugins/debugger/qml/qscriptdebuggerclient.h
+++ b/src/plugins/debugger/qml/qscriptdebuggerclient.h
@@ -62,10 +62,10 @@ public:
void activateFrame(int index);
- void insertBreakpoint(const BreakpointModelId &id, int adjustedLine,
+ void insertBreakpoint(Breakpoint bp, int adjustedLine,
int adjustedColumn = -1);
- void removeBreakpoint(const BreakpointModelId &id);
- void changeBreakpoint(const BreakpointModelId &id);
+ void removeBreakpoint(Breakpoint bp);
+ void changeBreakpoint(Breakpoint bp);
void synchronizeBreakpoints();
void assignValueInDebugger(const WatchData *data, const QString &expression,
diff --git a/src/plugins/debugger/registerhandler.cpp b/src/plugins/debugger/registerhandler.cpp
index 61e3de0b2d8..d40536acbb1 100644
--- a/src/plugins/debugger/registerhandler.cpp
+++ b/src/plugins/debugger/registerhandler.cpp
@@ -46,518 +46,537 @@ namespace Internal {
//
//////////////////////////////////////////////////////////////////
-enum RegisterType
-{
- RegisterUnknown,
- //RegisterDummy, // like AH if EAX is present.
- RegisterI8,
- RegisterI16,
- RegisterI32,
- RegisterI64,
- RegisterI128,
- RegisterF32,
- RegisterF64,
- RegisterF80,
- RegisterXMM,
- RegisterMMX,
- RegisterNeon,
- RegisterFlags32
-};
-
static struct RegisterNameAndType
{
const char *name;
- RegisterType type;
+ RegisterKind kind;
+ int size;
} theNameAndType[] = {
// ARM
- { "r0", RegisterI32 },
- { "r1", RegisterI32 },
- { "r2", RegisterI32 },
- { "r3", RegisterI32 },
- { "r4", RegisterI32 },
- { "r5", RegisterI32 },
- { "r6", RegisterI32 },
- { "r7", RegisterI32 },
- { "r8", RegisterI32 },
- { "r9", RegisterI32 },
- { "r10", RegisterI32 },
- { "r11", RegisterI32 },
- { "r12", RegisterI32 },
- { "sp", RegisterI32 },
- { "lr", RegisterI32 },
- { "pc", RegisterI32 },
- { "cpsr", RegisterFlags32 },
- { "d0", RegisterI64 },
- { "d1", RegisterI64 },
- { "d2", RegisterI64 },
- { "d3", RegisterI64 },
- { "d4", RegisterI64 },
- { "d5", RegisterI64 },
- { "d6", RegisterI64 },
- { "d7", RegisterI64 },
- { "d8", RegisterI64 },
- { "d9", RegisterI64 },
- { "d10", RegisterI64 },
- { "d11", RegisterI64 },
- { "d12", RegisterI64 },
- { "d13", RegisterI64 },
- { "d14", RegisterI64 },
- { "d15", RegisterI64 },
- { "d16", RegisterI64 },
- { "d17", RegisterI64 },
- { "d18", RegisterI64 },
- { "d19", RegisterI64 },
- { "d20", RegisterI64 },
- { "d21", RegisterI64 },
- { "d22", RegisterI64 },
- { "d23", RegisterI64 },
- { "d24", RegisterI64 },
- { "d25", RegisterI64 },
- { "d26", RegisterI64 },
- { "d27", RegisterI64 },
- { "d28", RegisterI64 },
- { "d29", RegisterI64 },
- { "d30", RegisterI64 },
- { "d31", RegisterI64 },
- { "fpscr", RegisterFlags32 },
- { "s0", RegisterI32 },
- { "s1", RegisterI32 },
- { "s2", RegisterI32 },
- { "s3", RegisterI32 },
- { "s4", RegisterI32 },
- { "s5", RegisterI32 },
- { "s6", RegisterI32 },
- { "s7", RegisterI32 },
- { "s8", RegisterI32 },
- { "s9", RegisterI32 },
- { "s10", RegisterI32 },
- { "s11", RegisterI32 },
- { "s12", RegisterI32 },
- { "s13", RegisterI32 },
- { "s14", RegisterI32 },
- { "s15", RegisterI32 },
- { "s16", RegisterI32 },
- { "s17", RegisterI32 },
- { "s18", RegisterI32 },
- { "s19", RegisterI32 },
- { "s20", RegisterI32 },
- { "s21", RegisterI32 },
- { "s22", RegisterI32 },
- { "s23", RegisterI32 },
- { "s24", RegisterI32 },
- { "s25", RegisterI32 },
- { "s26", RegisterI32 },
- { "s27", RegisterI32 },
- { "s28", RegisterI32 },
- { "s29", RegisterI32 },
- { "s30", RegisterI32 },
- { "s31", RegisterI32 },
- { "q0", RegisterI128 },
- { "q1", RegisterI128 },
- { "q2", RegisterI128 },
- { "q3", RegisterI128 },
- { "q4", RegisterI128 },
- { "q5", RegisterI128 },
- { "q6", RegisterI128 },
- { "q7", RegisterI128 },
- { "q8", RegisterI128 },
- { "q9", RegisterI128 },
- { "q10", RegisterI128 },
- { "q11", RegisterI128 },
- { "q12", RegisterI128 },
- { "q13", RegisterI128 },
- { "q14", RegisterI128 },
- { "q15", RegisterI128 },
+ { "r0", IntegerRegister, 4 },
+ { "r1", IntegerRegister, 4 },
+ { "r2", IntegerRegister, 4 },
+ { "r3", IntegerRegister, 4 },
+ { "r4", IntegerRegister, 4 },
+ { "r5", IntegerRegister, 4 },
+ { "r6", IntegerRegister, 4 },
+ { "r7", IntegerRegister, 4 },
+ { "r8", IntegerRegister, 4 },
+ { "r9", IntegerRegister, 4 },
+ { "r10", IntegerRegister, 4 },
+ { "r11", IntegerRegister, 4 },
+ { "r12", IntegerRegister, 4 },
+ { "sp", IntegerRegister, 4 },
+ { "lr", IntegerRegister, 4 },
+ { "pc", IntegerRegister, 4 },
+ { "cpsr", FlagRegister, 4 },
+ { "d0", IntegerRegister, 8 },
+ { "d1", IntegerRegister, 8 },
+ { "d2", IntegerRegister, 8 },
+ { "d3", IntegerRegister, 8 },
+ { "d4", IntegerRegister, 8 },
+ { "d5", IntegerRegister, 8 },
+ { "d6", IntegerRegister, 8 },
+ { "d7", IntegerRegister, 8 },
+ { "d8", IntegerRegister, 8 },
+ { "d9", IntegerRegister, 8 },
+ { "d10", IntegerRegister, 8 },
+ { "d11", IntegerRegister, 8 },
+ { "d12", IntegerRegister, 8 },
+ { "d13", IntegerRegister, 8 },
+ { "d14", IntegerRegister, 8 },
+ { "d15", IntegerRegister, 8 },
+ { "d16", IntegerRegister, 8 },
+ { "d17", IntegerRegister, 8 },
+ { "d18", IntegerRegister, 8 },
+ { "d19", IntegerRegister, 8 },
+ { "d20", IntegerRegister, 8 },
+ { "d21", IntegerRegister, 8 },
+ { "d22", IntegerRegister, 8 },
+ { "d23", IntegerRegister, 8 },
+ { "d24", IntegerRegister, 8 },
+ { "d25", IntegerRegister, 8 },
+ { "d26", IntegerRegister, 8 },
+ { "d27", IntegerRegister, 8 },
+ { "d28", IntegerRegister, 8 },
+ { "d29", IntegerRegister, 8 },
+ { "d30", IntegerRegister, 8 },
+ { "d31", IntegerRegister, 8 },
+ { "fpscr", FlagRegister, 4 },
+ { "s0", IntegerRegister, 4 },
+ { "s1", IntegerRegister, 4 },
+ { "s2", IntegerRegister, 4 },
+ { "s3", IntegerRegister, 4 },
+ { "s4", IntegerRegister, 4 },
+ { "s5", IntegerRegister, 4 },
+ { "s6", IntegerRegister, 4 },
+ { "s7", IntegerRegister, 4 },
+ { "s8", IntegerRegister, 4 },
+ { "s9", IntegerRegister, 4 },
+ { "s10", IntegerRegister, 4 },
+ { "s11", IntegerRegister, 4 },
+ { "s12", IntegerRegister, 4 },
+ { "s13", IntegerRegister, 4 },
+ { "s14", IntegerRegister, 4 },
+ { "s15", IntegerRegister, 4 },
+ { "s16", IntegerRegister, 4 },
+ { "s17", IntegerRegister, 4 },
+ { "s18", IntegerRegister, 4 },
+ { "s19", IntegerRegister, 4 },
+ { "s20", IntegerRegister, 4 },
+ { "s21", IntegerRegister, 4 },
+ { "s22", IntegerRegister, 4 },
+ { "s23", IntegerRegister, 4 },
+ { "s24", IntegerRegister, 4 },
+ { "s25", IntegerRegister, 4 },
+ { "s26", IntegerRegister, 4 },
+ { "s27", IntegerRegister, 4 },
+ { "s28", IntegerRegister, 4 },
+ { "s29", IntegerRegister, 4 },
+ { "s30", IntegerRegister, 4 },
+ { "s31", IntegerRegister, 4 },
+ { "q0", IntegerRegister, 16 },
+ { "q1", IntegerRegister, 16 },
+ { "q2", IntegerRegister, 16 },
+ { "q3", IntegerRegister, 16 },
+ { "q4", IntegerRegister, 16 },
+ { "q5", IntegerRegister, 16 },
+ { "q6", IntegerRegister, 16 },
+ { "q7", IntegerRegister, 16 },
+ { "q8", IntegerRegister, 16 },
+ { "q9", IntegerRegister, 16 },
+ { "q10", IntegerRegister, 16 },
+ { "q11", IntegerRegister, 16 },
+ { "q12", IntegerRegister, 16 },
+ { "q13", IntegerRegister, 16 },
+ { "q14", IntegerRegister, 16 },
+ { "q15", IntegerRegister, 16 },
// Intel
- { "eax", RegisterI32 },
- { "ecx", RegisterI32 },
- { "edx", RegisterI32 },
- { "ebx", RegisterI32 },
- { "esp", RegisterI32 },
- { "ebp", RegisterI32 },
- { "esi", RegisterI32 },
- { "edi", RegisterI32 },
- { "eip", RegisterI32 },
- { "eflags", RegisterFlags32 },
- { "cs", RegisterI32 },
- { "ss", RegisterI32 },
- { "ds", RegisterI32 },
- { "es", RegisterI32 },
- { "fs", RegisterI32 },
- { "gs", RegisterI32 },
- { "st0", RegisterF80 },
- { "st1", RegisterF80 },
- { "st2", RegisterF80 },
- { "st3", RegisterF80 },
- { "st4", RegisterF80 },
- { "st5", RegisterF80 },
- { "st6", RegisterF80 },
- { "st7", RegisterF80 },
- { "fctrl", RegisterFlags32 },
- { "fstat", RegisterFlags32 },
- { "ftag", RegisterFlags32 },
- { "fiseg", RegisterFlags32 },
- { "fioff", RegisterFlags32 },
- { "foseg", RegisterFlags32 },
- { "fooff", RegisterFlags32 },
- { "fop", RegisterFlags32 },
- { "xmm0", RegisterXMM },
- { "xmm1", RegisterXMM },
- { "xmm2", RegisterXMM },
- { "xmm3", RegisterXMM },
- { "xmm4", RegisterXMM },
- { "xmm5", RegisterXMM },
- { "xmm6", RegisterXMM },
- { "xmm7", RegisterXMM },
- { "mxcsr", RegisterFlags32 },
- { "orig_eax", RegisterI32 },
- { "al", RegisterI8 },
- { "cl", RegisterI8 },
- { "dl", RegisterI8 },
- { "bl", RegisterI8 },
- { "ah", RegisterI8 },
- { "ch", RegisterI8 },
- { "dh", RegisterI8 },
- { "bh", RegisterI8 },
- { "ax", RegisterI16 },
- { "cx", RegisterI16 },
- { "dx", RegisterI16 },
- { "bx", RegisterI16 },
- { "bp", RegisterI16 },
- { "si", RegisterI16 },
- { "di", RegisterI16 },
- { "mm0", RegisterMMX },
- { "mm1", RegisterMMX },
- { "mm2", RegisterMMX },
- { "mm3", RegisterMMX },
- { "mm4", RegisterMMX },
- { "mm5", RegisterMMX },
- { "mm6", RegisterMMX },
- { "mm7", RegisterMMX }
+ { "eax", IntegerRegister, 4 },
+ { "ecx", IntegerRegister, 4 },
+ { "edx", IntegerRegister, 4 },
+ { "ebx", IntegerRegister, 4 },
+ { "esp", IntegerRegister, 4 },
+ { "ebp", IntegerRegister, 4 },
+ { "esi", IntegerRegister, 4 },
+ { "edi", IntegerRegister, 4 },
+ { "eip", IntegerRegister, 4 },
+ { "rax", IntegerRegister, 8 },
+ { "rcx", IntegerRegister, 8 },
+ { "rdx", IntegerRegister, 8 },
+ { "rbx", IntegerRegister, 8 },
+ { "rsp", IntegerRegister, 8 },
+ { "rbp", IntegerRegister, 8 },
+ { "rsi", IntegerRegister, 8 },
+ { "rdi", IntegerRegister, 8 },
+ { "rip", IntegerRegister, 8 },
+ { "eflags", FlagRegister, 4 },
+ { "cs", IntegerRegister, 2 },
+ { "ss", IntegerRegister, 2 },
+ { "ds", IntegerRegister, 2 },
+ { "es", IntegerRegister, 2 },
+ { "fs", IntegerRegister, 2 },
+ { "gs", IntegerRegister, 2 },
+ { "st0", FloatRegister, 10 },
+ { "st1", FloatRegister, 10 },
+ { "st2", FloatRegister, 10 },
+ { "st3", FloatRegister, 10 },
+ { "st4", FloatRegister, 10 },
+ { "st5", FloatRegister, 10 },
+ { "st6", FloatRegister, 10 },
+ { "st7", FloatRegister, 10 },
+ { "fctrl", FlagRegister, 4 },
+ { "fstat", FlagRegister, 4 },
+ { "ftag", FlagRegister, 4 },
+ { "fiseg", FlagRegister, 4 },
+ { "fioff", FlagRegister, 4 },
+ { "foseg", FlagRegister, 4 },
+ { "fooff", FlagRegister, 4 },
+ { "fop", FlagRegister, 4 },
+ { "mxcsr", FlagRegister, 4 },
+ { "orig_eax", IntegerRegister, 4 },
+ { "al", IntegerRegister, 1 },
+ { "cl", IntegerRegister, 1 },
+ { "dl", IntegerRegister, 1 },
+ { "bl", IntegerRegister, 1 },
+ { "ah", IntegerRegister, 1 },
+ { "ch", IntegerRegister, 1 },
+ { "dh", IntegerRegister, 1 },
+ { "bh", IntegerRegister, 1 },
+ { "ax", IntegerRegister, 2 },
+ { "cx", IntegerRegister, 2 },
+ { "dx", IntegerRegister, 2 },
+ { "bx", IntegerRegister, 2 },
+ { "bp", IntegerRegister, 2 },
+ { "si", IntegerRegister, 2 },
+ { "di", IntegerRegister, 2 }
};
-static RegisterType guessType(const QByteArray &name)
+//////////////////////////////////////////////////////////////////
+//
+// RegisterValue
+//
+//////////////////////////////////////////////////////////////////
+
+// FIXME: This should not really be needed. Instead the guessing, if any,
+// should done by the engines.
+static void fixup(Register *reg, RegisterKind kind, int size)
{
- static QHash<QByteArray, RegisterType> theTypes;
- if (theTypes.isEmpty()) {
- for (int i = 0; i != sizeof(theNameAndType) / sizeof(theNameAndType[0]); ++i)
- theTypes[theNameAndType[i].name] = theNameAndType[i].type;
- }
- return theTypes.value(name, RegisterUnknown);
+ reg->kind = kind;
+ if (!reg->size)
+ reg->size = size;
}
-static int childCountFromType(int type)
+void Register::guessMissingData()
{
- switch (type) {
- case RegisterUnknown: return 0;
- case RegisterI8: return 0;
- case RegisterI16: return 1;
- case RegisterI32: return 2;
- case RegisterI64: return 3;
- case RegisterI128: return 4;
- case RegisterF32: return 0;
- case RegisterF64: return 0;
- case RegisterF80: return 0;
- case RegisterXMM: return 3;
- case RegisterMMX: return 3;
- case RegisterNeon: return 3;
- case RegisterFlags32: return 0;
+ if (name.startsWith("xmm")) {
+ fixup(this, VectorRegister, 16);
+ return;
}
+
+ for (int i = 0; i != sizeof(theNameAndType) / sizeof(theNameAndType[0]); ++i) {
+ if (theNameAndType[i].name == name) {
+ fixup(this, theNameAndType[i].kind, theNameAndType[i].size);
+ return;
+ }
+ }
+
+ if (reportedType == "int")
+ fixup(this, IntegerRegister, 4);
+ else if (reportedType == "float")
+ fixup(this, IntegerRegister, 8);
+ else if (reportedType == "_i387_ext")
+ fixup(this, IntegerRegister, 10);
+ else if (reportedType == "*1" || reportedType == "long")
+ fixup(this, IntegerRegister, 0);
+ else if (reportedType.contains("vec"))
+ fixup(this, VectorRegister, 0);
+ else if (reportedType.startsWith("int"))
+ fixup(this, IntegerRegister, 0);
+}
+
+static QString subTypeName(RegisterKind kind, int size)
+{
+ if (kind == IntegerRegister)
+ return QString::fromLatin1("[i%1]").arg(size * 8);
+ if (kind == FloatRegister)
+ return QString::fromLatin1("[f%1]").arg(size * 8);
QTC_ASSERT(false, /**/);
- return 0;
+ return QString();
}
-static int bitWidthFromType(int type, int subType)
+static uint decodeHexChar(unsigned char c)
{
- const uint integer[] = { 8, 16, 32, 64, 128 };
- const uint xmm[] = { 8, 16, 32, 64, 128 };
- const uint mmx[] = { 8, 16, 32, 64, 128 };
- const uint neon[] = { 8, 16, 32, 64, 128 };
-
- switch (type) {
- case RegisterUnknown: return 0;
- case RegisterI8: return 8;
- case RegisterI16: return integer[subType];
- case RegisterI32: return integer[subType];
- case RegisterI64: return integer[subType];
- case RegisterI128: return integer[subType];
- case RegisterF32: return 0;
- case RegisterF64: return 0;
- case RegisterF80: return 0;
- case RegisterXMM: return xmm[subType];
- case RegisterMMX: return mmx[subType];
- case RegisterNeon: return neon[subType];
- case RegisterFlags32: return 0;
+ c -= '0';
+ if (c < 10)
+ return c;
+ c -= 'A' - '0';
+ if (c < 6)
+ return 10 + c;
+ c -= 'a' - 'A';
+ if (c < 6)
+ return 10 + c;
+ return uint(-1);
+}
+
+void RegisterValue::operator=(const QByteArray &ba)
+{
+ uint shift = 0;
+ int j = 0;
+ v.u64[1] = v.u64[0] = 0;
+ for (int i = ba.size(); --i >= 0 && j < 16; ++j) {
+ quint64 d = decodeHexChar(ba.at(i));
+ if (d == uint(-1))
+ return;
+ v.u64[0] |= (d << shift);
+ shift += 4;
+ }
+ j = 0;
+ shift = 0;
+ for (int i = ba.size() - 16; --i >= 0 && j < 16; ++j) {
+ quint64 d = decodeHexChar(ba.at(i));
+ if (d == uint(-1))
+ return;
+ v.u64[1] |= (d << shift);
+ shift += 4;
}
- QTC_ASSERT(false, /**/);
- return 0;
}
-static const uint TopLevelId = UINT_MAX;
-static bool isTopLevelItem(const QModelIndex &index)
+bool RegisterValue::operator==(const RegisterValue &other)
{
- return quintptr(index.internalId()) == quintptr(TopLevelId);
+ return v.u64[0] == other.v.u64[0] && v.u64[1] == other.v.u64[1];
}
-Register::Register(const QByteArray &name_)
- : name(name_), changed(true)
+static QByteArray format(quint64 v, int base, int size)
{
- type = guessType(name);
+ QByteArray result = QByteArray::number(v, base);
+ if (base == 16)
+ result.prepend(QByteArray(2*size - result.size(), '0'));
+ return result;
}
+QByteArray RegisterValue::toByteArray(int base, RegisterKind kind, int size) const
+{
+ if (kind == FloatRegister) {
+ if (size == 4)
+ return QByteArray::number(v.f[0]);
+ if (size == 8)
+ return QByteArray::number(v.d[0]);
+ }
+
+ QByteArray result;
+ if (size > 8) {
+ result += format(v.u64[1], base, size - 8);
+ size = 8;
+ if (base != 16)
+ result += ',';
+ }
+ result += format(v.u64[0], base, size);
+ if (base == 16)
+ result.prepend("0x");
+ return result;
+}
+
+RegisterValue RegisterValue::subValue(int size, int index) const
+{
+ RegisterValue value;
+ switch (size) {
+ case 1:
+ value.v.u8[0] = v.u8[index];
+ break;
+ case 2:
+ value.v.u16[0] = v.u16[index];
+ break;
+ case 4:
+ value.v.u32[0] = v.u32[index];
+ break;
+ case 8:
+ value.v.u64[0] = v.u64[index];
+ break;
+ }
+ return value;
+}
//////////////////////////////////////////////////////////////////
//
-// RegisterHandler
+// RegisterSubItem and RegisterItem
//
//////////////////////////////////////////////////////////////////
-RegisterHandler::RegisterHandler()
+class RegisterSubItem : public Utils::TreeItem
{
- setObjectName(QLatin1String("RegisterModel"));
- m_base = 16;
- calculateWidth();
-#if USE_REGISTER_MODEL_TEST
- new ModelTest(this, 0);
-#endif
-}
+public:
+ RegisterSubItem(RegisterKind subKind, int subSize, int count)
+ : m_subKind(subKind), m_subSize(subSize), m_count(count), m_changed(false)
+ {}
+
+ QVariant data(int column, int role) const;
+
+ Qt::ItemFlags flags(int column) const
+ {
+ //return column == 1 ? Qt::ItemIsSelectable|Qt::ItemIsEnabled|Qt::ItemIsEditable
+ // : Qt::ItemIsSelectable|Qt::ItemIsEnabled;
+ Q_UNUSED(column);
+ return Qt::ItemIsSelectable|Qt::ItemIsEnabled;
+ }
-int RegisterHandler::rowCount(const QModelIndex &idx) const
-{
- if (idx.column() > 0)
- return 0;
- if (!idx.isValid())
- return m_registers.size(); // Top level.
- if (!isTopLevelItem(idx))
- return 0; // Sub-Items don't have children.
- if (idx.row() >= m_registers.size())
- return 0;
- return childCountFromType(m_registers[idx.row()].type);
-}
+ RegisterKind m_subKind;
+ int m_subSize;
+ int m_count;
+ bool m_changed;
+};
-int RegisterHandler::columnCount(const QModelIndex &idx) const
+class RegisterItem : public Utils::TreeItem
{
- if (idx.column() > 0)
- return 0;
- if (!idx.isValid())
- return 2;
- if (!isTopLevelItem(idx))
- return 0; // Sub-Items don't have children.
- return 2;
-}
+public:
+ explicit RegisterItem(const Register &reg);
-QModelIndex RegisterHandler::index(int row, int col, const QModelIndex &parent) const
-{
- if (row < 0 || col < 0 || col >= 2)
- return QModelIndex();
- if (!parent.isValid()) // Top level.
- return createIndex(row, col, TopLevelId);
- if (!isTopLevelItem(parent)) // Sub-Item has no children.
- return QModelIndex();
- if (parent.column() > 0)
- return QModelIndex();
- return createIndex(row, col, parent.row());
-}
+ QVariant data(int column, int role) const;
+ Qt::ItemFlags flags(int column) const;
-QModelIndex RegisterHandler::parent(const QModelIndex &idx) const
+ quint64 addressValue() const;
+
+ Register m_reg;
+ int m_base;
+ bool m_changed;
+};
+
+RegisterItem::RegisterItem(const Register &reg) :
+ m_reg(reg), m_base(16), m_changed(true)
{
- if (!idx.isValid())
- return QModelIndex();
- if (!isTopLevelItem(idx))
- return createIndex(idx.internalId(), 0, TopLevelId);
- return QModelIndex();
+ if (m_reg.kind == UnknownRegister)
+ m_reg.guessMissingData();
+
+ if (m_reg.kind == IntegerRegister || m_reg.kind == VectorRegister) {
+ for (int s = m_reg.size / 2; s; s = s / 2)
+ appendChild(new RegisterSubItem(IntegerRegister, s, m_reg.size / s));
+ }
+ if (m_reg.kind == IntegerRegister || m_reg.kind == VectorRegister) {
+ for (int s = m_reg.size; s >= 4; s = s / 2)
+ appendChild(new RegisterSubItem(FloatRegister, s, m_reg.size / s));
+ }
}
-// Editor value: Preferably number, else string.
-QVariant Register::editValue() const
+Qt::ItemFlags RegisterItem::flags(int column) const
{
- bool ok = true;
- // Try to convert to number?
- const qulonglong v = value.toULongLong(&ok, 0); // Autodetect format
- if (ok)
- return QVariant(v);
- return QVariant(value);
+ const Qt::ItemFlags notEditable = Qt::ItemIsSelectable|Qt::ItemIsEnabled;
+ // Can edit registers if they are hex numbers and not arrays.
+ if (column == 1) // && IntegerWatchLineEdit::isUnsignedHexNumber(QLatin1String(m_reg.display)))
+ return notEditable | Qt::ItemIsEditable;
+ return notEditable;
}
-// Editor value: Preferably padded number, else padded string.
-QString Register::displayValue(int base, int strlen) const
+quint64 RegisterItem::addressValue() const
{
- const QVariant editV = editValue();
- if (editV.type() == QVariant::ULongLong)
- return QString::fromLatin1("%1").arg(editV.toULongLong(), strlen, base);
- const QString stringValue = editV.toString();
- if (stringValue.size() < strlen)
- return QString(strlen - stringValue.size(), QLatin1Char(' ')) + QLatin1String(value);
- return stringValue;
+ return m_reg.value.v.u64[0];
}
-QVariant RegisterHandler::data(const QModelIndex &index, int role) const
+QVariant RegisterItem::data(int column, int role) const
{
- if (!index.isValid())
- return QVariant();
+ switch (role) {
+ case RegisterNameRole:
+ return m_reg.name;
- QModelIndex topLevel = index.parent();
- const int mainRow = topLevel.isValid() ? topLevel.row() : index.row();
+ case RegisterIsBigRole:
+ return m_reg.value.v.u64[1] > 0;
- if (mainRow >= m_registers.size())
- return QVariant();
+ case RegisterChangedRole:
+ return m_changed;
+ case RegisterNumberBaseRole:
+ return m_base;
- const Register &reg = m_registers.at(mainRow);
+ case RegisterAsAddressRole:
+ return addressValue();
- if (topLevel.isValid()) {
- //
- // Nested
- //
- int subType = index.row();
- int bitWidth = bitWidthFromType(reg.type, subType);
-
- switch (role) {
case Qt::DisplayRole:
- switch (index.column()) {
- case 0: {
- switch (bitWidth) {
- case 8: return QLatin1String("[Bytes]");
- case 16: return QLatin1String("[Words]");
- case 32: return QLatin1String("[DWords]");
- case 64: return QLatin1String("[QWords]");
- case 128: return QLatin1String("[TWords]");
- case -32: return QLatin1String("[Single]");
- case -64: return QLatin1String("[Double]");
- return QVariant(bitWidth);
+ switch (column) {
+ case 0: {
+ QByteArray res = m_reg.name;
+ if (!m_reg.description.isEmpty())
+ res += " (" + m_reg.description + ')';
+ return res;
+ }
+ case 1: {
+ return m_reg.value.toByteArray(m_base, m_reg.kind, m_reg.size);
}
}
- }
- default:
- break;
- }
- } else {
- //
- // Toplevel
- //
+ case Qt::ToolTipRole:
+ return QString::fromLatin1("Current Value: %1\nPreviousValue: %2")
+ .arg(QString::fromLatin1(m_reg.value.toByteArray(m_base, m_reg.kind, m_reg.size)))
+ .arg(QString::fromLatin1(m_reg.previousValue.toByteArray(m_base, m_reg.kind, m_reg.size)));
- switch (role) {
- case Qt::DisplayRole:
- switch (index.column()) {
- case 0: {
- const QString padding = QLatin1String(" ");
- return QVariant(padding + QLatin1String(reg.name) + padding);
- //return QVariant(reg.name);
- }
- case 1: // Display: Pad value for alignment
- return reg.displayValue(m_base, m_strlen);
- } // switch column
case Qt::EditRole: // Edit: Unpadded for editing
- return reg.editValue();
+ return m_reg.value.toByteArray(m_base, m_reg.kind, m_reg.size);
+
case Qt::TextAlignmentRole:
- return index.column() == 1 ? QVariant(Qt::AlignRight) : QVariant();
+ return column == 1 ? QVariant(Qt::AlignRight) : QVariant();
+
default:
break;
- }
}
return QVariant();
}
-QVariant RegisterHandler::headerData(int section, Qt::Orientation orientation,
- int role) const
+QVariant RegisterSubItem::data(int column, int role) const
{
- if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
- switch (section) {
- case 0: return tr("Name");
- case 1: return tr("Value (Base %1)").arg(m_base);
- };
- }
- return QVariant();
-}
+ switch (role) {
+ case RegisterChangedRole:
+ return m_changed;
-Qt::ItemFlags RegisterHandler::flags(const QModelIndex &idx) const
-{
- if (!idx.isValid())
- return Qt::ItemFlags();
+ case RegisterNumberBaseRole:
+ return 16;
- const Qt::ItemFlags notEditable = Qt::ItemIsSelectable|Qt::ItemIsEnabled;
- // Can edit registers if they are hex numbers and not arrays.
- if (idx.column() == 1
- && IntegerWatchLineEdit::isUnsignedHexNumber(QLatin1String(m_registers.at(idx.row()).value)))
- return notEditable | Qt::ItemIsEditable;
- return notEditable;
-}
+ case RegisterAsAddressRole:
+ return 0;
-void RegisterHandler::removeAll()
-{
- beginResetModel();
- m_registers.clear();
- endResetModel();
-}
+ case Qt::DisplayRole:
+ switch (column) {
+ case 0:
+ return subTypeName(m_subKind, m_subSize);
+ case 1: {
+ QTC_ASSERT(parent(), return QVariant());
+ RegisterItem *registerItem = static_cast<RegisterItem *>(parent());
+ RegisterValue value = registerItem->m_reg.value;
+ QByteArray ba;
+ for (int i = 0; i != m_count; ++i) {
+ ba += value.subValue(m_subSize, i).toByteArray(16, m_subKind, m_subSize);
+ int tab = 5 * (i + 1) * m_subSize;
+ ba += QByteArray(tab - ba.size(), ' ');
+ }
+ return ba;
+ }
+ }
+ default:
+ break;
+ }
-bool RegisterHandler::isEmpty() const
-{
- return m_registers.isEmpty();
+ return QVariant();
}
-// Compare register sets by name
-static inline bool compareRegisterSet(const Registers &r1, const Registers &r2)
-{
- if (r1.size() != r2.size())
- return false;
- const int size = r1.size();
- for (int r = 0; r < size; r++)
- if (r1.at(r).name != r2.at(r).name)
- return false;
- return true;
-}
+//////////////////////////////////////////////////////////////////
+//
+// RegisterHandler
+//
+//////////////////////////////////////////////////////////////////
-void RegisterHandler::setRegisters(const Registers &registers)
+RegisterHandler::RegisterHandler()
{
- beginResetModel();
- m_registers = registers;
- const int size = m_registers.size();
- for (int r = 0; r < size; r++)
- m_registers[r].changed = false;
- calculateWidth();
- endResetModel();
+ setObjectName(QLatin1String("RegisterModel"));
+ setHeader(QStringList() << tr("Name") << tr("Value"));
+
+#if USE_REGISTER_MODEL_TEST
+ new ModelTest(this, 0);
+#endif
}
-void RegisterHandler::setAndMarkRegisters(const Registers &registers)
+void RegisterHandler::updateRegister(const Register &r)
{
- if (!compareRegisterSet(m_registers, registers)) {
- setRegisters(registers);
+ RegisterItem *reg = m_registerByName.value(r.name, 0);
+ if (!reg) {
+ reg = new RegisterItem(r);
+ m_registerByName[r.name] = reg;
+ rootItem()->appendChild(reg);
return;
}
- const int size = m_registers.size();
- for (int r = 0; r != size; ++r) {
- const QModelIndex regIndex = index(r, 1, QModelIndex());
- if (m_registers.at(r).value != registers.at(r).value) {
- // Indicate red if values change, keep changed.
- m_registers[r].changed = m_registers.at(r).changed
- || !m_registers.at(r).value.isEmpty();
- m_registers[r].value = registers.at(r).value;
- emit dataChanged(regIndex, regIndex);
- }
- emit registerSet(regIndex); // Notify attached memory views.
- }
-}
-Registers RegisterHandler::registers() const
-{
- return m_registers;
+ if (r.size > 0)
+ reg->m_reg.size = r.size;
+ if (!r.description.isEmpty())
+ reg->m_reg.description = r.description;
+ if (reg->m_reg.value != r.value) {
+ // Indicate red if values change, keep changed.
+ reg->m_changed = true;
+ reg->m_reg.previousValue = reg->m_reg.value;
+ reg->m_reg.value = r.value;
+ emit registerChanged(reg->m_reg.name, reg->addressValue()); // Notify attached memory views.
+ } else {
+ reg->m_changed = false;
+ }
}
-void RegisterHandler::calculateWidth()
+void RegisterHandler::setNumberBase(const QByteArray &name, int base)
{
- m_strlen = (m_base == 2 ? 64 : m_base == 8 ? 32 : m_base == 10 ? 26 : 16);
+ RegisterItem *reg = m_registerByName.value(name, 0);
+ QTC_ASSERT(reg, return);
+ reg->m_base = base;
+ QModelIndex index = indexFromItem(reg);
+ emit dataChanged(index, index);
}
-void RegisterHandler::setNumberBase(int base)
+RegisterMap RegisterHandler::registerMap() const
{
- if (m_base != base) {
- beginResetModel();
- m_base = base;
- calculateWidth();
- endResetModel();
+ RegisterMap result;
+ Utils::TreeItem *root = rootItem();
+ for (int i = 0, n = root->rowCount(); i != n; ++i) {
+ RegisterItem *reg = static_cast<RegisterItem *>(root->child(i));
+ quint64 value = reg->addressValue();
+ if (value)
+ result.insert(value, reg->m_reg.name);
}
+ return result;
}
} // namespace Internal
diff --git a/src/plugins/debugger/registerhandler.h b/src/plugins/debugger/registerhandler.h
index a2c843dd6e1..f22b52a14d1 100644
--- a/src/plugins/debugger/registerhandler.h
+++ b/src/plugins/debugger/registerhandler.h
@@ -31,35 +31,73 @@
#ifndef DEBUGGER_REGISTERHANDLER_H
#define DEBUGGER_REGISTERHANDLER_H
+#include <utils/treemodel.h>
+
#include <QAbstractTableModel>
+#include <QHash>
#include <QVector>
namespace Debugger {
namespace Internal {
-class Register
+enum RegisterDataRole
{
-public:
- Register() : type(0), changed(true) {}
- Register(const QByteArray &name_);
+ RegisterNameRole = Qt::UserRole,
+ RegisterIsBigRole,
+ RegisterChangedRole,
+ RegisterNumberBaseRole,
+ RegisterAsAddressRole
+};
+
+enum RegisterKind
+{
+ UnknownRegister,
+ IntegerRegister,
+ FloatRegister,
+ VectorRegister,
+ FlagRegister,
+ OtherRegister
+};
- QVariant editValue() const;
- QString displayValue(int base, int strlen) const;
+class RegisterValue
+{
+public:
+ RegisterValue() { v.u64[1] = v.u64[0] = 0; }
+ void operator=(const QByteArray &ba);
+ bool operator==(const RegisterValue &other);
+ bool operator!=(const RegisterValue &other) { return !operator==(other); }
+ QByteArray toByteArray(int base, RegisterKind kind, int size) const;
+ RegisterValue subValue(int size, int index) const;
+
+ union {
+ quint8 u8[16];
+ quint16 u16[8];
+ quint32 u32[4];
+ quint64 u64[2];
+ float f[4];
+ double d[2];
+ } v;
+};
+class Register
+{
public:
+ Register() { size = 0; kind = UnknownRegister; }
+ void guessMissingData();
+
QByteArray name;
- /* Value should be an integer for which autodetection by passing
- * base=0 to QString::toULongLong() should work (C-language conventions).
- * Values that cannot be converted (such as 128bit MMX-registers) are
- * passed through. */
- QByteArray value;
- int type;
- bool changed;
+ QByteArray reportedType;
+ RegisterValue value;
+ RegisterValue previousValue;
+ QByteArray description;
+ int size;
+ RegisterKind kind;
};
-typedef QVector<Register> Registers;
+class RegisterItem;
+typedef QMap<quint64, QByteArray> RegisterMap;
-class RegisterHandler : public QAbstractTableModel
+class RegisterHandler : public Utils::TreeModel
{
Q_OBJECT
@@ -68,34 +106,17 @@ public:
QAbstractItemModel *model() { return this; }
- bool isEmpty() const; // nothing known so far?
- // Set up register names (gdb)
- void setRegisters(const Registers &registers);
- // Set register values
- void setAndMarkRegisters(const Registers &registers);
- Registers registers() const;
- Register registerAt(int i) const { return m_registers.at(i); }
- void removeAll();
- Q_SLOT void setNumberBase(int base);
- int numberBase() const { return m_base; }
+ void updateRegister(const Register &reg);
+
+ void setNumberBase(const QByteArray &name, int base);
+ void commitUpdates() { emit layoutChanged(); }
+ RegisterMap registerMap() const;
signals:
- void registerSet(const QModelIndex &r); // Register was set, for memory views
+ void registerChanged(const QByteArray &name, quint64 value); // For memory views
private:
- void calculateWidth();
- int rowCount(const QModelIndex &idx = QModelIndex()) const;
- int columnCount(const QModelIndex &idx = QModelIndex()) const;
- QModelIndex index(int row, int col, const QModelIndex &parent) const;
- QModelIndex parent(const QModelIndex &idx) const;
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- QVariant headerData(int section, Qt::Orientation orientation,
- int role = Qt::DisplayRole) const;
- Qt::ItemFlags flags(const QModelIndex &idx) const;
-
- Registers m_registers;
- int m_base;
- int m_strlen; // approximate width of a value in chars.
+ QHash<QByteArray, RegisterItem *> m_registerByName;
};
} // namespace Internal
diff --git a/src/plugins/debugger/registerwindow.cpp b/src/plugins/debugger/registerwindow.cpp
index c75af5547af..724feeb8eba 100644
--- a/src/plugins/debugger/registerwindow.cpp
+++ b/src/plugins/debugger/registerwindow.cpp
@@ -30,6 +30,7 @@
#include "registerwindow.h"
#include "memoryview.h"
+#include "memoryagent.h"
#include "debuggeractions.h"
#include "debuggerdialogs.h"
#include "debuggercore.h"
@@ -42,22 +43,13 @@
#include <utils/qtcassert.h>
#include <QDebug>
-
#include <QItemDelegate>
#include <QMenu>
#include <QPainter>
-
namespace Debugger {
namespace Internal {
-static RegisterHandler *currentHandler()
-{
- DebuggerEngine *engine = currentEngine();
- QTC_ASSERT(engine, return 0);
- return engine->registerHandler();
-}
-
///////////////////////////////////////////////////////////////////////
//
// RegisterDelegate
@@ -74,10 +66,9 @@ public:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &,
const QModelIndex &index) const
{
- Register reg = currentHandler()->registerAt(index.row());
IntegerWatchLineEdit *lineEdit = new IntegerWatchLineEdit(parent);
- const int base = currentHandler()->numberBase();
- const bool big = reg.value.size() > 16;
+ const int base = index.data(RegisterNumberBaseRole).toInt();
+ const bool big = index.data(RegisterIsBigRole).toBool();
// Big integers are assumed to be hexadecimal.
lineEdit->setBigInt(big);
lineEdit->setBase(big ? 16 : base);
@@ -101,11 +92,11 @@ public:
return;
IntegerWatchLineEdit *lineEdit = qobject_cast<IntegerWatchLineEdit*>(editor);
QTC_ASSERT(lineEdit, return);
- const int base = currentHandler()->numberBase();
+ const int base = index.data(RegisterNumberBaseRole).toInt();
QString value = lineEdit->text();
if (base == 16 && !value.startsWith(QLatin1String("0x")))
value.insert(0, QLatin1String("0x"));
- currentEngine()->setRegisterValue(index.row(), value);
+ currentEngine()->setRegisterValue(index.data(RegisterNameRole).toByteArray(), value);
}
void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
@@ -118,28 +109,38 @@ public:
const QModelIndex &index) const
{
if (index.column() == 1) {
- bool paintRed = currentHandler()->registerAt(index.row()).changed;
+ const bool paintRed = index.data(RegisterChangedRole).toBool();
QPen oldPen = painter->pen();
+ const QColor lightColor(140, 140, 140);
if (paintRed)
painter->setPen(QColor(200, 0, 0));
+ else
+ painter->setPen(lightColor);
// FIXME: performance? this changes only on real font changes.
QFontMetrics fm(option.font);
- int charWidth = fm.width(QLatin1Char('x'));
- for (int i = '1'; i <= '9'; ++i)
- charWidth = qMax(charWidth, fm.width(QLatin1Char(i)));
- for (int i = 'a'; i <= 'f'; ++i)
- charWidth = qMax(charWidth, fm.width(QLatin1Char(i)));
+ int charWidth = qMax(fm.width(QLatin1Char('x')), fm.width(QLatin1Char('0')));
QString str = index.data(Qt::DisplayRole).toString();
int x = option.rect.x();
+ bool light = !paintRed;
for (int i = 0; i < str.size(); ++i) {
- QRect r = option.rect;
- r.setX(x);
- r.setWidth(charWidth);
+ const QChar c = str.at(i);
+ const int uc = c.unicode();
+ if (light && (uc != 'x' && uc != '0')) {
+ light = false;
+ painter->setPen(oldPen.color());
+ }
+ if (uc == ' ') {
+ light = true;
+ painter->setPen(lightColor);
+ } else {
+ QRect r = option.rect;
+ r.setX(x);
+ r.setWidth(charWidth);
+ painter->drawText(r, Qt::AlignHCenter, c);
+ }
x += charWidth;
- painter->drawText(r, Qt::AlignHCenter, QString(str.at(i)));
}
- if (paintRed)
- painter->setPen(oldPen);
+ painter->setPen(oldPen);
} else {
QItemDelegate::paint(painter, option, index);
}
@@ -156,6 +157,7 @@ public:
RegisterTreeView::RegisterTreeView()
{
setItemDelegate(new RegisterDelegate(this));
+ setRootIsDecorated(true);
}
void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
@@ -164,7 +166,8 @@ void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
DebuggerEngine *engine = currentEngine();
QTC_ASSERT(engine, return);
- RegisterHandler *handler = currentHandler();
+ RegisterHandler *handler = engine->registerHandler();
+
const bool actionsEnabled = engine->debuggerActionsEnabled();
const DebuggerState state = engine->state();
@@ -174,13 +177,8 @@ void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
menu.addSeparator();
- Register aRegister;
const QModelIndex idx = indexAt(ev->pos());
- if (idx.isValid())
- aRegister = handler->registers().at(idx.row());
- const QVariant addressV = aRegister.editValue();
- const quint64 address = addressV.type() == QVariant::ULongLong
- ? addressV.toULongLong() : 0;
+ const quint64 address = idx.data(RegisterAsAddressRole).toULongLong();
QAction *actViewMemory = menu.addAction(QString());
QAction *actEditMemory = menu.addAction(QString());
@@ -188,12 +186,14 @@ void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
QAction *actShowDisassembler = menu.addAction(tr("Open Disassembler..."));
actShowDisassembler->setEnabled(engine->hasCapability(DisassemblerCapability));
+ const QByteArray registerName = idx.data(RegisterNameRole).toByteArray();
+ const QString registerNameStr = QString::fromUtf8(registerName);
if (address) {
const bool canShow = actionsEnabled && engine->hasCapability(ShowMemoryCapability);
actEditMemory->setText(tr("Open Memory Editor at 0x%1").arg(address, 0, 16));
actEditMemory->setEnabled(canShow);
actViewMemory->setText(tr("Open Memory View at Value of Register %1 0x%2")
- .arg(QString::fromLatin1(aRegister.name)).arg(address, 0, 16));
+ .arg(registerNameStr).arg(address, 0, 16));
actShowDisassemblerAt->setText(tr("Open Disassembler at 0x%1")
.arg(address, 0, 16));
actShowDisassemblerAt->setEnabled(engine->hasCapability(DisassemblerCapability));
@@ -207,7 +207,7 @@ void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
}
menu.addSeparator();
- const int base = handler->numberBase();
+ const int base = idx.data(RegisterNumberBaseRole).toInt();
QAction *act16 = menu.addAction(tr("Hexadecimal"));
act16->setCheckable(true);
act16->setChecked(base == 16);
@@ -230,14 +230,20 @@ void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
if (act == actReload) {
engine->reloadRegisters();
} else if (act == actEditMemory) {
- const QString registerName = QString::fromLatin1(aRegister.name);
- engine->openMemoryView(address, 0,
- RegisterMemoryView::registerMarkup(address, registerName),
- QPoint(), RegisterMemoryView::title(registerName), 0);
+ MemoryViewSetupData data;
+ data.startAddress = address;
+ data.registerName = registerName;
+ data.markup = RegisterMemoryView::registerMarkup(address, registerName);
+ data.title = RegisterMemoryView::title(registerName);
+ engine->openMemoryView(data);
} else if (act == actViewMemory) {
- engine->openMemoryView(idx.row(),
- DebuggerEngine::MemoryTrackRegister|DebuggerEngine::MemoryView,
- QList<MemoryMarkup>(), position, QString(), this);
+ MemoryViewSetupData data;
+ data.startAddress = address;
+ data.flags = DebuggerEngine::MemoryTrackRegister|DebuggerEngine::MemoryView,
+ data.registerName = registerName;
+ data.pos = position;
+ data.parent = this;
+ engine->openMemoryView(data);
} else if (act == actShowDisassembler) {
AddressDialog dialog;
if (address)
@@ -247,13 +253,13 @@ void RegisterTreeView::contextMenuEvent(QContextMenuEvent *ev)
} else if (act == actShowDisassemblerAt) {
engine->openDisassemblerView(Location(address));
} else if (act == act16)
- handler->setNumberBase(16);
+ handler->setNumberBase(registerName, 16);
else if (act == act10)
- handler->setNumberBase(10);
+ handler->setNumberBase(registerName, 10);
else if (act == act8)
- handler->setNumberBase(8);
+ handler->setNumberBase(registerName, 8);
else if (act == act2)
- handler->setNumberBase(2);
+ handler->setNumberBase(registerName, 2);
}
void RegisterTreeView::reloadRegisters()
diff --git a/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp b/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp
index 020837c7189..7e0628120a9 100644
--- a/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp
+++ b/src/plugins/debugger/shared/cdbsymbolpathlisteditor.cpp
@@ -31,6 +31,7 @@
#include "cdbsymbolpathlisteditor.h"
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <utils/pathchooser.h>
#include <utils/checkablemessagebox.h>
@@ -67,8 +68,8 @@ CacheDirectoryDialog::CacheDirectoryDialog(QWidget *parent) :
setLayout(mainLayout);
- connect(m_buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
- connect(m_buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
+ connect(m_buttonBox, &QDialogButtonBox::accepted, this, &CacheDirectoryDialog::accept);
+ connect(m_buttonBox, &QDialogButtonBox::rejected, this, &CacheDirectoryDialog::reject);
}
void CacheDirectoryDialog::setPath(const QString &p)
@@ -98,15 +99,15 @@ void CacheDirectoryDialog::accept()
}
// Does a file of the same name exist?
if (fi.exists()) {
- QMessageBox::warning(this, tr("Already Exists"),
- tr("A file named \"%1\" already exists.").arg(cache));
+ Core::AsynchronousMessageBox::warning(tr("Already Exists"),
+ tr("A file named \"%1\" already exists.").arg(cache));
return;
}
// Create
QDir root(QDir::root());
if (!root.mkpath(cache)) {
- QMessageBox::warning(this, tr("Cannot Create"),
- tr("The folder \"%1\" could not be created.").arg(cache));
+ Core::AsynchronousMessageBox::warning(tr("Cannot Create"),
+ tr("The folder \"%1\" could not be created.").arg(cache));
return;
}
QDialog::accept();
diff --git a/src/plugins/debugger/snapshothandler.h b/src/plugins/debugger/snapshothandler.h
index 9cd3ee35e9f..0a7c0f0441f 100644
--- a/src/plugins/debugger/snapshothandler.h
+++ b/src/plugins/debugger/snapshothandler.h
@@ -35,18 +35,16 @@
#include <QPointer>
namespace Debugger {
+namespace Internal {
class DebuggerEngine;
-namespace Internal {
-
////////////////////////////////////////////////////////////////////////
//
// SnapshotModel
//
////////////////////////////////////////////////////////////////////////
-
class SnapshotHandler : public QAbstractTableModel
{
Q_OBJECT
diff --git a/src/plugins/debugger/sourceagent.cpp b/src/plugins/debugger/sourceagent.cpp
index 69e438d8954..937836c2299 100644
--- a/src/plugins/debugger/sourceagent.cpp
+++ b/src/plugins/debugger/sourceagent.cpp
@@ -40,16 +40,16 @@
#include <cppeditor/cppeditorconstants.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QDebug>
-#include <QFileInfo>
-
#include <QTextBlock>
#include <limits.h>
using namespace Core;
+using namespace TextEditor;
namespace Debugger {
namespace Internal {
@@ -61,9 +61,9 @@ public:
~SourceAgentPrivate();
public:
- QPointer<TextEditor::BaseTextEditor> editor;
+ QPointer<BaseTextEditor> editor;
QPointer<DebuggerEngine> engine;
- TextEditor::TextMark *locationMark;
+ TextMark *locationMark;
QString path;
QString producer;
};
@@ -73,7 +73,6 @@ SourceAgentPrivate::SourceAgentPrivate()
, locationMark(0)
, producer(QLatin1String("remote"))
{
-
}
SourceAgentPrivate::~SourceAgentPrivate()
@@ -104,14 +103,11 @@ void SourceAgent::setSourceProducerName(const QString &name)
void SourceAgent::setContent(const QString &filePath, const QString &content)
{
QTC_ASSERT(d, return);
- using namespace Core;
- using namespace TextEditor;
-
d->path = filePath;
if (!d->editor) {
QString titlePattern = d->producer + QLatin1String(": ")
- + QFileInfo(filePath).fileName();
+ + Utils::FileName::fromString(filePath).fileName();
d->editor = qobject_cast<BaseTextEditor *>(
EditorManager::openEditorWithContents(
CppEditor::Constants::CPPEDITOR_ID,
@@ -143,9 +139,11 @@ void SourceAgent::updateLocationMarker()
d->locationMark = 0;
if (d->engine->stackHandler()->currentFrame().file == d->path) {
int lineNumber = d->engine->stackHandler()->currentFrame().line;
- d->locationMark = new TextEditor::TextMark(QString(), lineNumber);
- d->locationMark->setIcon(Internal::locationMarkIcon());
- d->locationMark->setPriority(TextEditor::TextMark::HighPriority);
+
+ d->locationMark = new TextMark(QString(), lineNumber);
+ d->locationMark->setIcon(locationMarkIcon());
+ d->locationMark->setPriority(TextMark::HighPriority);
+
d->editor->textDocument()->addMark(d->locationMark);
QTextCursor tc = d->editor->textCursor();
QTextBlock block = tc.document()->findBlockByNumber(lineNumber - 1);
diff --git a/src/plugins/debugger/sourceagent.h b/src/plugins/debugger/sourceagent.h
index c2c301d59f1..3727023e7d3 100644
--- a/src/plugins/debugger/sourceagent.h
+++ b/src/plugins/debugger/sourceagent.h
@@ -34,16 +34,15 @@
#include <QString>
namespace Debugger {
-
-class DebuggerEngine;
-
namespace Internal {
+class DebuggerEngine;
class SourceAgentPrivate;
+
class SourceAgent
{
public:
- explicit SourceAgent(Debugger::DebuggerEngine *engine);
+ explicit SourceAgent(DebuggerEngine *engine);
~SourceAgent();
void setSourceProducerName(const QString &name);
void resetLocation();
diff --git a/src/plugins/debugger/sourceutils.cpp b/src/plugins/debugger/sourceutils.cpp
index 0c6e96e5021..9e1d80bf9b6 100644
--- a/src/plugins/debugger/sourceutils.cpp
+++ b/src/plugins/debugger/sourceutils.cpp
@@ -264,7 +264,7 @@ bool getUninitializedVariables(const Snapshot &snapshot,
bool isCppEditor(TextEditorWidget *editorWidget)
{
const TextDocument *document = editorWidget->textDocument();
- return ProjectFile::classify(document->filePath()) != ProjectFile::Unclassified;
+ return ProjectFile::classify(document->filePath().toString()) != ProjectFile::Unclassified;
}
QString cppFunctionAt(const QString &fileName, int line, int column)
@@ -282,7 +282,6 @@ QString cppExpressionAt(TextEditorWidget *editorWidget, int pos,
int *line, int *column, QString *function,
int *scopeFromLine, int *scopeToLine)
{
- *line = *column = 0;
if (function)
function->clear();
@@ -297,15 +296,13 @@ QString cppExpressionAt(TextEditorWidget *editorWidget, int pos,
// Fetch the expression's code.
ExpressionUnderCursor expressionUnderCursor;
expr = expressionUnderCursor(tc);
- *column = tc.positionInBlock();
- *line = tc.blockNumber();
- } else {
- *column = tc.positionInBlock();
- *line = tc.blockNumber();
}
+ *column = tc.positionInBlock();
+ *line = tc.blockNumber() + 1;
+
if (!expr.isEmpty()) {
- QString fileName = editorWidget->textDocument()->filePath();
+ QString fileName = editorWidget->textDocument()->filePath().toString();
const Snapshot snapshot = CppModelManager::instance()->snapshot();
if (const Document::Ptr document = snapshot.document(fileName)) {
QString func = document->functionAt(*line, *column, scopeFromLine, scopeToLine);
diff --git a/src/plugins/debugger/stackhandler.cpp b/src/plugins/debugger/stackhandler.cpp
index dfeeb660849..ec5fe966416 100644
--- a/src/plugins/debugger/stackhandler.cpp
+++ b/src/plugins/debugger/stackhandler.cpp
@@ -34,11 +34,11 @@
#include "debuggercore.h"
#include "simplifytype.h"
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
#include <QDebug>
-#include <QFileInfo>
namespace Debugger {
namespace Internal {
@@ -64,8 +64,8 @@ StackHandler::StackHandler()
m_contentsValid = false;
m_currentIndex = -1;
m_canExpand = false;
- connect(action(OperateByInstruction), SIGNAL(triggered()),
- this, SLOT(resetModel()));
+ connect(action(OperateByInstruction), &QAction::triggered,
+ this, &StackHandler::resetModel);
}
StackHandler::~StackHandler()
@@ -80,7 +80,7 @@ int StackHandler::rowCount(const QModelIndex &parent) const
int StackHandler::columnCount(const QModelIndex &parent) const
{
- return parent.isValid() ? 0 : 5;
+ return parent.isValid() ? 0 : StackColumnCount;
}
QVariant StackHandler::data(const QModelIndex &index, int role) const
@@ -89,11 +89,11 @@ QVariant StackHandler::data(const QModelIndex &index, int role) const
return QVariant();
if (index.row() == m_stackFrames.size()) {
- if (role == Qt::DisplayRole && index.column() == 0)
+ if (role == Qt::DisplayRole && index.column() == StackLevelColumn)
return tr("...");
- if (role == Qt::DisplayRole && index.column() == 1)
+ if (role == Qt::DisplayRole && index.column() == StackFunctionNameColumn)
return tr("<More>");
- if (role == Qt::DecorationRole && index.column() == 0)
+ if (role == Qt::DecorationRole && index.column() == StackLevelColumn)
return m_emptyIcon;
return QVariant();
}
@@ -102,15 +102,15 @@ QVariant StackHandler::data(const QModelIndex &index, int role) const
if (role == Qt::DisplayRole) {
switch (index.column()) {
- case 0: // Stack frame level
+ case StackLevelColumn:
return QString::number(frame.level);
- case 1: // Function name
+ case StackFunctionNameColumn:
return simplifyType(frame.function);
- case 2: // File name
- return frame.file.isEmpty() ? frame.from : QFileInfo(frame.file).fileName();
- case 3: // Line number
+ case StackFileNameColumn:
+ return frame.file.isEmpty() ? frame.from : Utils::FileName::fromString(frame.file).fileName();
+ case StackLineNumberColumn:
return frame.line > 0 ? QVariant(frame.line) : QVariant();
- case 4: // Address
+ case StackAddressColumn:
if (frame.address)
return QString::fromLatin1("0x%1").arg(frame.address, 0, 16);
return QString();
@@ -118,7 +118,7 @@ QVariant StackHandler::data(const QModelIndex &index, int role) const
return QVariant();
}
- if (role == Qt::DecorationRole && index.column() == 0) {
+ if (role == Qt::DecorationRole && index.column() == StackLevelColumn) {
// Return icon that indicates whether this is the active stack frame
return (m_contentsValid && index.row() == m_currentIndex)
? m_positionIcon : m_emptyIcon;
diff --git a/src/plugins/debugger/stackhandler.h b/src/plugins/debugger/stackhandler.h
index 3e8bcbf57f9..26d94bff4cc 100644
--- a/src/plugins/debugger/stackhandler.h
+++ b/src/plugins/debugger/stackhandler.h
@@ -38,21 +38,16 @@
namespace Debugger {
namespace Internal {
-////////////////////////////////////////////////////////////////////////
-//
-// StackCookie
-//
-////////////////////////////////////////////////////////////////////////
-
-struct StackCookie
+enum StackColumns
{
- StackCookie() : isFull(true), gotoLocation(false) {}
- StackCookie(bool full, bool jump) : isFull(full), gotoLocation(jump) {}
- bool isFull;
- bool gotoLocation;
+ StackLevelColumn,
+ StackFunctionNameColumn,
+ StackFileNameColumn,
+ StackLineNumberColumn,
+ StackAddressColumn,
+ StackColumnCount = StackAddressColumn,
};
-
////////////////////////////////////////////////////////////////////////
//
// StackModel
@@ -110,7 +105,4 @@ private:
} // namespace Internal
} // namespace Debugger
-Q_DECLARE_METATYPE(Debugger::Internal::StackCookie)
-
-
#endif // DEBUGGER_STACKHANDLER_H
diff --git a/src/plugins/debugger/stackwindow.cpp b/src/plugins/debugger/stackwindow.cpp
index 15db90da047..4c863307c01 100644
--- a/src/plugins/debugger/stackwindow.cpp
+++ b/src/plugins/debugger/stackwindow.cpp
@@ -37,6 +37,7 @@
#include "debuggerdialogs.h"
#include "memoryagent.h"
+#include <coreplugin/messagebox.h>
#include <utils/savedaction.h>
@@ -50,7 +51,6 @@
#include <QContextMenuEvent>
#include <QInputDialog>
#include <QFileDialog>
-#include <QMessageBox>
#include <QMenu>
namespace Debugger {
@@ -71,7 +71,7 @@ StackTreeView::StackTreeView()
void StackTreeView::showAddressColumn(bool on)
{
- setColumnHidden(4, !on);
+ setColumnHidden(StackAddressColumn, !on);
}
void StackTreeView::rowActivated(const QModelIndex &index)
@@ -82,8 +82,8 @@ void StackTreeView::rowActivated(const QModelIndex &index)
void StackTreeView::setModel(QAbstractItemModel *model)
{
BaseTreeView::setModel(model);
- resizeColumnToContents(0);
- resizeColumnToContents(3);
+ resizeColumnToContents(StackLevelColumn);
+ resizeColumnToContents(StackLineNumberColumn);
showAddressColumn(action(UseAddressInStackView)->isChecked());
}
@@ -127,7 +127,7 @@ void saveTaskFile(QWidget *parent, const StackHandler *sh)
const QString fileName = fileDialog.selectedFiles().front();
file.setFileName(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
- QMessageBox::warning(parent, StackTreeView::tr("Cannot Open Task File"),
+ Core::AsynchronousMessageBox::warning(StackTreeView::tr("Cannot Open Task File"),
StackTreeView::tr("Cannot open \"%1\": %2").arg(QDir::toNativeSeparators(fileName), file.errorString()));
}
}
@@ -214,12 +214,13 @@ void StackTreeView::contextMenuEvent(QContextMenuEvent *ev)
if (act == actCopyContents) {
copyContentsToClipboard();
} 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;
- ml.push_back(MemoryMarkup(address, 1, QColor(Qt::blue).lighter(),
+ MemoryViewSetupData data;
+ data.startAddress = address;
+ data.title = tr("Memory at Frame #%1 (%2) 0x%3").
+ arg(row).arg(frame.function).arg(address, 0, 16);
+ data.markup.push_back(MemoryMarkup(address, 1, QColor(Qt::blue).lighter(),
tr("Frame #%1 (%2)").arg(row).arg(frame.function)));
- engine->openMemoryView(address, 0, ml, QPoint(), title);
+ engine->openMemoryView(data);
} else if (act == actShowDisassemblerAtAddress) {
AddressDialog dialog;
if (address)
diff --git a/src/plugins/debugger/terminal.cpp b/src/plugins/debugger/terminal.cpp
new file mode 100644
index 00000000000..e133f365724
--- /dev/null
+++ b/src/plugins/debugger/terminal.cpp
@@ -0,0 +1,169 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "terminal.h"
+
+#include <QDebug>
+#include <QIODevice>
+#include <QSocketNotifier>
+
+#include <utils/qtcassert.h>
+
+#ifdef Q_OS_UNIX
+# define DEBUGGER_USE_TERMINAL
+#endif
+
+#ifdef DEBUGGER_USE_TERMINAL
+# include <errno.h>
+# include <fcntl.h>
+# include <stdlib.h>
+# include <string.h>
+# include <unistd.h>
+# include <sys/ioctl.h>
+# include <sys/stat.h>
+#endif
+
+namespace Debugger {
+namespace Internal {
+
+static QString currentError()
+{
+ int err = errno;
+ return QString::fromLatin1(strerror(err));
+}
+
+Terminal::Terminal(QObject *parent)
+ : QObject(parent), m_isUsable(false), m_masterFd(-1), m_masterReader(0)
+{
+}
+
+void Terminal::setup()
+{
+#ifdef DEBUGGER_USE_TERMINAL
+ if (!qEnvironmentVariableIsSet("QTC_USE_PTY"))
+ return;
+
+ m_masterFd = ::open("/dev/ptmx", O_RDWR);
+ if (m_masterFd < 0) {
+ error(tr("Terminal: Cannot open /dev/ptmx: %1").arg(currentError()));
+ return;
+ }
+
+ const char *sName = ptsname(m_masterFd);
+ if (!sName) {
+ error(tr("Terminal: ptsname failed: %1").arg(currentError()));
+ return;
+ }
+ m_slaveName = sName;
+
+ struct stat s;
+ int r = ::stat(m_slaveName.constData(), &s);
+ if (r != 0) {
+ error(tr("Terminal: Error: %1").arg(currentError()));
+ return;
+ }
+ if (!S_ISCHR(s.st_mode)) {
+ error(tr("Terminal: Slave is no character device"));
+ return;
+ }
+
+ m_masterReader = new QSocketNotifier(m_masterFd, QSocketNotifier::Read, this);
+ connect(m_masterReader, &QSocketNotifier::activated,
+ this, &Terminal::onSlaveReaderActivated);
+
+ r = grantpt(m_masterFd);
+ if (r != 0) {
+ error(tr("Terminal: grantpt failed: %1").arg(currentError()));
+ return;
+ }
+
+ r = unlockpt(m_masterFd);
+ if (r != 0) {
+ error(tr("Terminal: unlock failed: %1").arg(currentError()));
+ return;
+ }
+
+ m_isUsable = true;
+#endif
+}
+
+bool Terminal::isUsable() const
+{
+ return m_isUsable;
+}
+
+int Terminal::write(const QByteArray &msg)
+{
+#ifdef DEBUGGER_USE_TERMINAL
+ return ::write(m_masterFd, msg.constData(), msg.size());
+#else
+ Q_UNUSED(msg);
+ return -1;
+#endif
+}
+
+bool Terminal::sendInterrupt()
+{
+#ifdef DEBUGGER_USE_TERMINAL
+ if (!m_isUsable)
+ return false;
+ ssize_t written = ::write(m_masterFd, "\003", 1);
+ return written == 1;
+#else
+ return false;
+#endif
+}
+
+void Terminal::onSlaveReaderActivated(int fd)
+{
+#ifdef DEBUGGER_USE_TERMINAL
+ ssize_t available = 0;
+ int ret = ::ioctl(fd, FIONREAD, (char *) &available);
+ if (ret != 0)
+ return;
+
+ QByteArray buffer(available, Qt::Uninitialized);
+ ssize_t got = ::read(fd, buffer.data(), available);
+ int err = errno;
+ if (got < 0) {
+ error(tr("Terminal: Read failed: %1").arg(QString::fromLatin1(strerror(err))));
+ return;
+ }
+ buffer.resize(got);
+ if (got >= 0)
+ stdOutReady(QString::fromUtf8(buffer));
+#else
+ Q_UNUSED(fd);
+#endif
+}
+
+} // namespace Internal
+} // namespace Debugger
+
diff --git a/src/plugins/debugger/breakpointmarker.h b/src/plugins/debugger/terminal.h
index fee89edd657..3ddfffe2f5c 100644
--- a/src/plugins/debugger/breakpointmarker.h
+++ b/src/plugins/debugger/terminal.h
@@ -28,36 +28,45 @@
**
****************************************************************************/
-#ifndef DEBUGGER_BREAKPOINTMARKER_H
-#define DEBUGGER_BREAKPOINTMARKER_H
+#ifndef DEBUGGER_TERMINAL_H
+#define DEBUGGER_TERMINAL_H
-#include "breakpoint.h"
-
-#include <texteditor/textmark.h>
+#include <QCoreApplication>
+#include <QSocketNotifier>
namespace Debugger {
namespace Internal {
-// The red blob on the left side in the cpp editor.
-class BreakpointMarker : public TextEditor::TextMark
+class Terminal : public QObject
{
+ Q_OBJECT
+
public:
- BreakpointMarker(BreakpointModelId id, const QString &fileName, int lineNumber);
- ~BreakpointMarker();
- void removedFromEditor();
- void updateLineNumber(int lineNumber);
- void updateFileName(const QString &fileName);
- bool isDraggable() const { return true; }
- void dragToLine(int lineNumber);
- bool isClickable() const { return true; }
- void clicked();
+ Terminal(QObject *parent = 0);
+
+ void setup();
+ bool isUsable() const;
+
+ QByteArray slaveDevice() const { return m_slaveName; }
+
+ int write(const QByteArray &msg);
+ bool sendInterrupt();
+
+signals:
+ void stdOutReady(const QString &);
+ void stdErrReady(const QString &);
+ void error(const QString &);
private:
- BreakpointModelId m_id;
- friend class BreakHandler;
+ void onSlaveReaderActivated(int fd);
+
+ bool m_isUsable;
+ int m_masterFd;
+ QSocketNotifier *m_masterReader;
+ QByteArray m_slaveName;
};
} // namespace Internal
} // namespace Debugger
-#endif
+#endif // DEBUGGER_TERMINAL_H
diff --git a/src/plugins/debugger/unstartedappwatcherdialog.cpp b/src/plugins/debugger/unstartedappwatcherdialog.cpp
index 9c9aa3741e8..5c683aa40ed 100644
--- a/src/plugins/debugger/unstartedappwatcherdialog.cpp
+++ b/src/plugins/debugger/unstartedappwatcherdialog.cpp
@@ -39,7 +39,7 @@
#include <projectexplorer/target.h>
#include <projectexplorer/project.h>
#include <projectexplorer/kitmanager.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/localapplicationrunconfiguration.h>
@@ -88,7 +88,7 @@ UnstartedAppWatcherDialog::UnstartedAppWatcherDialog(QWidget *parent)
m_kitChooser->populate();
m_kitChooser->setVisible(true);
- Project *project = ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
if (project && project->activeTarget() && project->activeTarget()->kit())
m_kitChooser->setCurrentKitId(project->activeTarget()->kit()->id());
else if (KitManager::defaultKit())
@@ -147,12 +147,17 @@ UnstartedAppWatcherDialog::UnstartedAppWatcherDialog(QWidget *parent)
mainLayout->addRow(buttonsLine);
setLayout(mainLayout);
- connect(m_pathChooser, SIGNAL(beforeBrowsing()), this, SLOT(selectExecutable()));
- connect(m_watchingPushButton, SIGNAL(toggled(bool)), this, SLOT(startStopWatching(bool)));
- connect(m_pathChooser, SIGNAL(pathChanged(QString)), this, SLOT(stopAndCheckExecutable()));
- connect(m_closePushButton, SIGNAL(clicked()), this, SLOT(reject()));
- connect(&m_timer, SIGNAL(timeout()), this, SLOT(findProcess()));
- connect(m_kitChooser, &ProjectExplorer::KitChooser::currentIndexChanged,
+ connect(m_pathChooser, &Utils::PathChooser::beforeBrowsing,
+ this, &UnstartedAppWatcherDialog::selectExecutable);
+ connect(m_watchingPushButton, &QAbstractButton::toggled,
+ this, &UnstartedAppWatcherDialog::startStopWatching);
+ connect(m_pathChooser, &Utils::PathChooser::pathChanged, this,
+ &UnstartedAppWatcherDialog::stopAndCheckExecutable);
+ connect(m_closePushButton, &QAbstractButton::clicked,
+ this, &QDialog::reject);
+ connect(&m_timer, &QTimer::timeout,
+ this, &UnstartedAppWatcherDialog::findProcess);
+ connect(m_kitChooser, &KitChooser::currentIndexChanged,
this, &UnstartedAppWatcherDialog::kitChanged);
kitChanged();
@@ -163,7 +168,7 @@ void UnstartedAppWatcherDialog::selectExecutable()
{
QString path;
- Project *project = ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
if (project && project->activeTarget() && project->activeTarget()->activeRunConfiguration()) {
diff --git a/src/plugins/debugger/unstartedappwatcherdialog.h b/src/plugins/debugger/unstartedappwatcherdialog.h
index 618a9f63812..5edb21781fa 100644
--- a/src/plugins/debugger/unstartedappwatcherdialog.h
+++ b/src/plugins/debugger/unstartedappwatcherdialog.h
@@ -62,20 +62,19 @@ public:
ProjectExplorer::DeviceProcessItem currentProcess() const;
bool hideOnAttach() const;
bool continueOnAttach() const;
+ void startWatching();
-public slots:
+signals:
+ void processFound();
+
+private:
void selectExecutable();
- void startWatching();
void pidFound(const ProjectExplorer::DeviceProcessItem &p);
void startStopWatching(bool start);
void findProcess();
void stopAndCheckExecutable();
void kitChanged();
-signals:
- void processFound();
-
-private:
enum UnstartedAppWacherState
{
InvalidWacherState,
diff --git a/src/plugins/debugger/watchdata.cpp b/src/plugins/debugger/watchdata.cpp
index 08647b04ffb..197677caf0d 100644
--- a/src/plugins/debugger/watchdata.cpp
+++ b/src/plugins/debugger/watchdata.cpp
@@ -156,6 +156,15 @@ bool WatchData::isEqual(const WatchData &other) const
&& error == other.error;
}
+bool WatchData::isAncestorOf(const QByteArray &childIName) const
+{
+ if (iname.size() >= childIName.size())
+ return false;
+ if (!childIName.startsWith(iname))
+ return false;
+ return childIName.at(iname.size()) == '.';
+}
+
bool WatchData::isVTablePointer() const
{
// First case: Cdb only. No user type can be named like this, this is safe.
@@ -526,7 +535,7 @@ QString decodeItemHelper(const double &t)
}
template <class T>
-void decodeArrayHelper(QList<WatchData> *list, const WatchData &tmplate,
+void decodeArrayHelper(std::function<void(const WatchData &)> itemHandler, const WatchData &tmplate,
const QByteArray &rawData)
{
const QByteArray ba = QByteArray::fromHex(rawData);
@@ -542,62 +551,59 @@ void decodeArrayHelper(QList<WatchData> *list, const WatchData &tmplate,
data.address += i * sizeof(T);
data.exp = exp + QByteArray::number(data.address, 16);
data.setAllUnneeded();
- list->append(data);
+ itemHandler(data);
}
}
-static void decodeArray(QList<WatchData> *list, const WatchData &tmplate,
+void decodeArrayData(std::function<void(const WatchData &)> itemHandler, const WatchData &tmplate,
const QByteArray &rawData, int encoding)
{
switch (encoding) {
case Hex2EncodedInt1:
- decodeArrayHelper<signed char>(list, tmplate, rawData);
+ decodeArrayHelper<signed char>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedInt2:
- decodeArrayHelper<short>(list, tmplate, rawData);
+ decodeArrayHelper<short>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedInt4:
- decodeArrayHelper<int>(list, tmplate, rawData);
+ decodeArrayHelper<int>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedInt8:
- decodeArrayHelper<qint64>(list, tmplate, rawData);
+ decodeArrayHelper<qint64>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedUInt1:
- decodeArrayHelper<uchar>(list, tmplate, rawData);
+ decodeArrayHelper<uchar>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedUInt2:
- decodeArrayHelper<ushort>(list, tmplate, rawData);
+ decodeArrayHelper<ushort>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedUInt4:
- decodeArrayHelper<uint>(list, tmplate, rawData);
+ decodeArrayHelper<uint>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedUInt8:
- decodeArrayHelper<quint64>(list, tmplate, rawData);
+ decodeArrayHelper<quint64>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedFloat4:
- decodeArrayHelper<float>(list, tmplate, rawData);
+ decodeArrayHelper<float>(itemHandler, tmplate, rawData);
break;
case Hex2EncodedFloat8:
- decodeArrayHelper<double>(list, tmplate, rawData);
+ decodeArrayHelper<double>(itemHandler, tmplate, rawData);
break;
default:
qDebug() << "ENCODING ERROR: " << encoding;
}
}
-void parseWatchData(const QSet<QByteArray> &expandedINames,
- const WatchData &data0, const GdbMi &item,
- QList<WatchData> *list)
+void parseChildrenData(const WatchData &data0, const GdbMi &item,
+ std::function<void(const WatchData &)> itemHandler,
+ std::function<void(const WatchData &, const GdbMi &)> childHandler,
+ std::function<void(const WatchData &childTemplate, const QByteArray &encodedData, int encoding)> arrayDecoder)
{
//qDebug() << "HANDLE CHILDREN: " << data0.toString() << item.toString();
WatchData data = data0;
- bool isExpanded = expandedINames.contains(data.iname);
- if (!isExpanded)
- data.setChildrenUnneeded();
+ data.setChildrenUnneeded();
GdbMi children = item["children"];
- if (children.isValid() || !isExpanded)
- data.setChildrenUnneeded();
data.updateType(item["type"]);
GdbMi mi = item["editvalue"];
@@ -640,7 +646,7 @@ void parseWatchData(const QSet<QByteArray> &expandedINames,
setWatchDataValueEditable(data, item["valueeditable"]);
data.updateChildCount(item["numchild"]);
//qDebug() << "\nAPPEND TO LIST: " << data.toString() << "\n";
- list->append(data);
+ itemHandler(data);
bool ok = false;
qulonglong addressBase = item["addrbase"].data().toULongLong(&ok, 0);
@@ -657,7 +663,7 @@ void parseWatchData(const QSet<QByteArray> &expandedINames,
int encoding = item["arrayencoding"].toInt();
childtemplate.iname = data.iname + '.';
childtemplate.address = addressBase;
- decodeArray(list, childtemplate, mi.data(), encoding);
+ arrayDecoder(childtemplate, mi.data(), encoding);
} else {
for (int i = 0, n = children.children().size(); i != n; ++i) {
const GdbMi &child = children.children().at(i);
@@ -687,11 +693,28 @@ void parseWatchData(const QSet<QByteArray> &expandedINames,
int encoding = child["keyencoded"].toInt();
data1.name = decodeData(key, encoding);
}
- parseWatchData(expandedINames, data1, child, list);
+ childHandler(data1, child);
}
}
}
+void parseWatchData(const WatchData &data0, const GdbMi &input,
+ QList<WatchData> *list)
+{
+ auto itemHandler = [list](const WatchData &data) {
+ list->append(data);
+ };
+ auto childHandler = [list](const WatchData &innerData, const GdbMi &innerInput) {
+ parseWatchData(innerData, innerInput, list);
+ };
+ auto arrayDecoder = [itemHandler](const WatchData &childTemplate,
+ const QByteArray &encodedData, int encoding) {
+ decodeArrayData(itemHandler, childTemplate, encodedData, encoding);
+ };
+
+ parseChildrenData(data0, input, itemHandler, childHandler, arrayDecoder);
+}
+
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/watchdata.h b/src/plugins/debugger/watchdata.h
index cef0a6095d4..b00de932205 100644
--- a/src/plugins/debugger/watchdata.h
+++ b/src/plugins/debugger/watchdata.h
@@ -34,6 +34,8 @@
#include <QCoreApplication>
#include <QMetaType>
+#include <functional>
+
namespace Debugger {
namespace Internal {
@@ -96,6 +98,7 @@ public:
bool isVTablePointer() const;
bool isEqual(const WatchData &other) const;
+ bool isAncestorOf(const QByteArray &childIName) const;
void setError(const QString &);
void setValue(const QString &);
@@ -151,9 +154,20 @@ public:
qint32 source; // Originated from dumper or symbol evaluation? (CDB only)
};
-void parseWatchData(const QSet<QByteArray> &expandedINames,
- const WatchData &parent, const GdbMi &child,
- QList<WatchData> *insertions);
+void decodeArrayData(std::function<void(const WatchData &)> itemHandler,
+ const WatchData &tmplate,
+ const QByteArray &rawData,
+ int encoding);
+
+void parseChildrenData(const WatchData &parent, const GdbMi &child,
+ std::function<void(const WatchData &)> itemHandler,
+ std::function<void(const WatchData &, const GdbMi &)> childHandler,
+ std::function<void(const WatchData &childTemplate,
+ const QByteArray &encodedData,
+ int encoding)> arrayDecoder);
+
+void parseWatchData(const WatchData &parent, const GdbMi &child,
+ QList<WatchData> *insertions);
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/watchhandler.cpp b/src/plugins/debugger/watchhandler.cpp
index a45a9dee197..cb5ac6f30d9 100644
--- a/src/plugins/debugger/watchhandler.cpp
+++ b/src/plugins/debugger/watchhandler.cpp
@@ -41,10 +41,13 @@
#include "imageviewer.h"
#include "watchutils.h"
+#include <coreplugin/icore.h>
+
#include <utils/algorithm.h>
#include <utils/basetreeview.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
+#include <utils/checkablemessagebox.h>
#include <QDebug>
#include <QFile>
@@ -55,12 +58,7 @@
#include <cstring>
#include <ctype.h>
-//#define USE_WATCH_MODEL_TEST 0
-//#define USE_EXPENSIVE_CHECKS 0
-
-#if USE_WATCH_MODEL_TEST
-#include <modeltest.h>
-#endif
+using namespace Utils;
namespace Debugger {
namespace Internal {
@@ -70,13 +68,6 @@ enum { debugModel = 0 };
#define MODEL_DEBUG(s) do { if (debugModel) qDebug() << s; } while (0)
-#if USE_EXPENSIVE_CHECKS
-#define CHECK(s) s
-#else
-#define CHECK(s)
-#endif
-
-
static QHash<QByteArray, int> theWatcherNames;
static QHash<QByteArray, int> theTypeFormats;
static QHash<QByteArray, int> theIndividualFormats;
@@ -109,36 +100,6 @@ static QByteArray stripForFormat(const QByteArray &ba)
return res;
}
-////////////////////////////////////////////////////////////////////
-//
-// WatchItem
-//
-////////////////////////////////////////////////////////////////////
-
-// Used to make sure the item cache is notified of construction and
-// destruction of items.
-
-class WatchItem;
-typedef QList<WatchItem *> WatchItems;
-
-WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname);
-void itemDestructor(WatchModel *model, WatchItem *item);
-
-class WatchItem : public WatchData
-{
-public:
- WatchItem *parent; // Not owned.
- WatchItems children; // Not owned. Handled via itemDestructor().
-
-private:
- friend WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname);
- friend void itemDestructor(WatchModel *model, WatchItem *item);
-
- WatchItem() { parent = 0; }
- ~WatchItem() { parent = 0; }
- WatchItem(const WatchItem &); // Not implemented.
-};
-
///////////////////////////////////////////////////////////////////////
//
// SeparatedView
@@ -232,79 +193,33 @@ public:
class WatchModel : public WatchModelBase
{
-private:
- explicit WatchModel(WatchHandler *handler);
- ~WatchModel();
-
- friend WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname);
- friend void itemDestructor(WatchModel *model, WatchItem *item);
-
public:
- int rowCount(const QModelIndex &idx = QModelIndex()) const;
- int columnCount(const QModelIndex &idx) const;
+ explicit WatchModel(WatchHandler *handler);
static QString nameForFormat(int format);
TypeFormatList typeFormatList(const WatchData &value) const;
-private:
- QVariant data(const QModelIndex &idx, int role) const;
bool setData(const QModelIndex &idx, const QVariant &value, int role);
- QModelIndex index(int, int, const QModelIndex &idx) const;
- QModelIndex parent(const QModelIndex &idx) const;
- bool hasChildren(const QModelIndex &idx) const;
- Qt::ItemFlags flags(const QModelIndex &idx) const;
- QVariant headerData(int section, Qt::Orientation orientation,
- int role = Qt::DisplayRole) const;
- bool canFetchMore(const QModelIndex &parent) const;
- void fetchMore(const QModelIndex &parent);
-
- void invalidateAll(const QModelIndex &parentIndex = QModelIndex());
- void resetValueCacheRecursively(WatchItem *item);
-
- WatchItem *createItem(const QByteArray &iname, const QString &name, WatchItem *parent);
-
- friend class WatchHandler;
-
- WatchItem *watchItem(const QModelIndex &) const;
- QModelIndex watchIndex(const WatchItem *needle) const;
- QModelIndex watchIndexHelper(const WatchItem *needle,
- const WatchItem *parentItem, const QModelIndex &parentIndex) const;
void insertDataItem(const WatchData &data, bool destructive);
void reinsertAllData();
void reinsertAllDataHelper(WatchItem *item, QList<WatchData> *data);
- bool ancestorChanged(const QSet<QByteArray> &parentINames, WatchItem *item) const;
void insertBulkData(const QList<WatchData> &data);
QString displayForAutoTest(const QByteArray &iname) const;
void reinitialize(bool includeInspectData = false);
- void destroyItem(WatchItem *item); // With model notification.
- void destroyChildren(WatchItem *item); // With model notification.
- void destroyHelper(const WatchItems &items); // Without model notification.
- void emitDataChanged(int column,
- const QModelIndex &parentIndex = QModelIndex());
friend QDebug operator<<(QDebug d, const WatchModel &m);
- void dump();
- void dumpHelper(WatchItem *item);
- void emitAllChanged();
-
void showInEditorHelper(QString *contents, WatchItem *item, int level);
void setCurrentItem(const QByteArray &iname);
- QString displayType(const WatchData &typeIn) const;
- QString displayName(const WatchItem *item) const;
- QString displayValue(const WatchData &data) const;
- QString formattedValue(const WatchData &data) const;
QString removeNamespaces(QString str) const;
- void formatRequests(QByteArray *out, const WatchItem *item) const;
DebuggerEngine *engine() const;
- int itemFormat(const WatchData &data) const;
bool contentIsValid() const;
WatchHandler *m_handler; // Not owned.
- WatchItem *m_root; // Owned.
+ WatchItem *root() const { return static_cast<WatchItem *>(rootItem()); }
WatchItem *m_localsRoot; // Not owned.
WatchItem *m_inspectorRoot; // Not owned.
WatchItem *m_watchRoot; // Not owned.
@@ -312,110 +227,51 @@ private:
WatchItem *m_tooltipRoot; // Not owned.
QSet<QByteArray> m_expandedINames;
- QSet<QByteArray> m_fetchTriggered;
TypeFormatList builtinTypeFormatList(const WatchData &data) const;
QStringList dumperTypeFormatList(const WatchData &data) const;
DumperTypeFormats m_reportedTypeFormats;
WatchItem *createItem(const QByteArray &iname);
- WatchItem *createItem(const WatchData &data);
- void assignData(WatchItem *item, const WatchData &data);
WatchItem *findItem(const QByteArray &iname) const;
friend class WatchItem;
- typedef QHash<QByteArray, WatchItem *> Cache;
- Cache m_cache;
typedef QHash<QByteArray, QString> ValueCache;
ValueCache m_valueCache;
- #if USE_EXPENSIVE_CHECKS
- QHash<const WatchItem *, QByteArray> m_cache2;
- void checkTree();
- void checkItem(const WatchItem *item) const;
- void checkTree(WatchItem *item, QSet<QByteArray> *inames);
- #endif
- void checkIndex(const QModelIndex &index) const;
+ void insertItem(WatchItem *item);
+ void reexpandItems();
};
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);
- m_inspectorRoot = createItem("inspect", tr("Inspector"), m_root);
- m_watchRoot = createItem("watch", tr("Expressions"), m_root);
- m_returnRoot = createItem("return", tr("Return Value"), m_root);
- m_tooltipRoot = createItem("tooltip", tr("Tooltip"), m_root);
-
- connect(action(SortStructMembers), &Utils::SavedAction::valueChanged,
+
+ setHeader(QStringList() << tr("Name") << tr("Value") << tr("Type"));
+ auto root = new WatchItem;
+ root->appendChild(m_localsRoot = new WatchItem("local", tr("Locals")));
+ root->appendChild(m_inspectorRoot = new WatchItem("inspect", tr("Inspector")));
+ root->appendChild(m_watchRoot = new WatchItem("watch", tr("Expressions")));
+ root->appendChild(m_returnRoot = new WatchItem("return", tr("Return Value")));
+ root->appendChild(m_tooltipRoot = new WatchItem("tooltip", tr("Tooltip")));
+ setRootItem(root);
+
+ connect(action(SortStructMembers), &SavedAction::valueChanged,
this, &WatchModel::reinsertAllData);
- connect(action(ShowStdNamespace), &Utils::SavedAction::valueChanged,
+ connect(action(ShowStdNamespace), &SavedAction::valueChanged,
this, &WatchModel::reinsertAllData);
- connect(action(ShowQtNamespace), &Utils::SavedAction::valueChanged,
+ connect(action(ShowQtNamespace), &SavedAction::valueChanged,
this, &WatchModel::reinsertAllData);
}
-WatchModel::~WatchModel()
-{
- CHECK(checkItem(m_root));
- destroyChildren(m_root);
- itemDestructor(this, m_root);
- QTC_CHECK(m_cache.isEmpty());
-}
-
-WatchItem *itemConstructor(WatchModel *model, const QByteArray &iname)
-{
- QTC_CHECK(!model->m_cache.contains(iname));
- WatchItem *item = new WatchItem();
- item->iname = iname;
- model->m_cache[iname] = item;
- CHECK(model->m_cache2[item] = iname);
- CHECK(model->checkItem(item));
- return item;
-}
-
-void itemDestructor(WatchModel *model, WatchItem *item)
-{
- QTC_ASSERT(model->m_cache.value(item->iname) == item, return);
- CHECK(model->checkItem(item));
- CHECK(model->m_cache2.remove(item));
- model->m_cache.remove(item->iname);
- delete item;
-}
-
-WatchItem *WatchModel::createItem(const QByteArray &iname, const QString &name, WatchItem *parent)
-{
- WatchItem *item = itemConstructor(this, iname);
- item->name = name;
- item->hasChildren = true; // parent == 0;
- item->state = 0;
- item->parent = parent;
- if (parent)
- parent->children.append(item);
- return item;
-}
-
void WatchModel::reinitialize(bool includeInspectData)
{
- CHECK(checkTree());
- //MODEL_DEBUG("REMOVING " << n << " CHILDREN OF " << m_root->iname);
- QTC_CHECK(m_root->children.size() == 5);
- destroyChildren(m_localsRoot);
- destroyChildren(m_watchRoot);
- destroyChildren(m_returnRoot);
- destroyChildren(m_tooltipRoot);
- if (includeInspectData) {
- destroyChildren(m_inspectorRoot);
- QTC_CHECK(m_cache.size() == 6);
- }
- CHECK(checkTree());
-}
-
-void WatchModel::emitAllChanged()
-{
- emit layoutChanged();
+ m_localsRoot->removeChildren();
+ m_watchRoot->removeChildren();
+ m_returnRoot->removeChildren();
+ m_tooltipRoot->removeChildren();
+ if (includeInspectData)
+ m_inspectorRoot->removeChildren();
}
DebuggerEngine *WatchModel::engine() const
@@ -423,122 +279,40 @@ DebuggerEngine *WatchModel::engine() const
return m_handler->m_engine;
}
-void WatchModel::dump()
-{
- qDebug() << "\n";
- foreach (WatchItem *child, m_root->children)
- dumpHelper(child);
-}
-
-void WatchModel::dumpHelper(WatchItem *item)
-{
- qDebug() << "ITEM: " << item->iname
- << (item->parent ? item->parent->iname : "<none>");
- foreach (WatchItem *child, item->children)
- dumpHelper(child);
-}
-
-void WatchModel::destroyHelper(const WatchItems &items)
-{
- for (int i = items.size(); --i >= 0; ) {
- WatchItem *item = items.at(i);
- destroyHelper(item->children);
- itemDestructor(this, item);
- }
-}
-
-void WatchModel::destroyItem(WatchItem *item)
-{
- const QByteArray iname = item->iname;
- CHECK(checkTree());
- QTC_ASSERT(m_cache.contains(iname), return);
-
- // Deregister from model and parent.
- // It's sufficient to do this non-recursively.
- WatchItem *parent = item->parent;
- QTC_ASSERT(parent, return);
- QModelIndex parentIndex = watchIndex(parent);
- checkIndex(parentIndex);
- const int i = parent->children.indexOf(item);
- //MODEL_DEBUG("NEED TO REMOVE: " << item->iname << "AT" << n);
- beginRemoveRows(parentIndex, i, i);
- parent->children.removeAt(i);
- endRemoveRows();
-
- // Destroy contents.
- destroyHelper(item->children);
- itemDestructor(this, item);
- QTC_ASSERT(!m_cache.contains(iname), return);
- CHECK(checkTree());
-}
-
-void WatchModel::destroyChildren(WatchItem *item)
-{
- CHECK(checkTree());
- QTC_ASSERT(m_cache.contains(item->iname), return);
- if (item->children.isEmpty())
- return;
-
- WatchItems items = item->children;
-
- // Deregister from model and parent.
- // It's sufficient to do this non-recursively.
- QModelIndex idx = watchIndex(item);
- checkIndex(idx);
- beginRemoveRows(idx, 0, items.size() - 1);
- item->children.clear();
- endRemoveRows();
-
- // Destroy contents.
- destroyHelper(items);
- CHECK(checkTree());
-}
-
WatchItem *WatchModel::findItem(const QByteArray &iname) const
{
- return m_cache.value(iname, 0);
+ return root()->findItem(iname);
}
-void WatchModel::checkIndex(const QModelIndex &index) const
+WatchItem *WatchItem::findItem(const QByteArray &iname)
{
- if (index.isValid()) {
- QTC_CHECK(index.model() == this);
- } else {
- QTC_CHECK(index.model() == 0);
+ if (d.iname == iname)
+ return this;
+ foreach (TreeItem *child, children()) {
+ auto witem = static_cast<WatchItem *>(child);
+ if (witem->d.iname == iname)
+ return witem;
+ if (witem->d.isAncestorOf(iname))
+ return witem->findItem(iname);
}
-}
-
-WatchItem *WatchModel::createItem(const WatchData &data)
-{
- WatchItem *item = itemConstructor(this, data.iname);
- static_cast<WatchData &>(*item) = data;
- return item;
-}
-
-void WatchModel::assignData(WatchItem *item, const WatchData &data)
-{
- CHECK(checkItem(item));
- QTC_ASSERT(data.iname == item->iname,
- m_cache.remove(item->iname);
- m_cache[data.iname] = item);
- static_cast<WatchData &>(*item) = data;
- CHECK(checkItem(item));
+ return 0;
}
void WatchModel::reinsertAllData()
{
QList<WatchData> list;
- reinsertAllDataHelper(m_root, &list);
+ foreach (TreeItem *child, rootItem()->children())
+ reinsertAllDataHelper(static_cast<WatchItem *>(child), &list);
reinitialize(true);
insertBulkData(list);
}
void WatchModel::reinsertAllDataHelper(WatchItem *item, QList<WatchData> *data)
{
- data->append(*item);
+ data->append(item->d);
data->back().setAllUnneeded();
- foreach (WatchItem *child, item->children)
- reinsertAllDataHelper(child, data);
+ foreach (TreeItem *child, item->children())
+ reinsertAllDataHelper(static_cast<WatchItem *>(child), data);
}
static QByteArray parentName(const QByteArray &iname)
@@ -714,68 +488,66 @@ static QString translate(const QString &str)
return quoteUnprintable(str);
}
-QString WatchModel::formattedValue(const WatchData &data) const
+QString WatchItem::formattedValue() const
{
- const QString &value = data.value;
-
- if (data.type == "bool") {
- if (value == QLatin1String("0"))
+ if (d.type == "bool") {
+ if (d.value == QLatin1String("0"))
return QLatin1String("false");
- if (value == QLatin1String("1"))
+ if (d.value == QLatin1String("1"))
return QLatin1String("true");
- return value;
+ return d.value;
}
- const int format = itemFormat(data);
+ const int format = itemFormat();
// Append quoted, printable character also for decimal.
- if (data.type.endsWith("char") || data.type.endsWith("QChar")) {
+ if (d.type.endsWith("char") || d.type.endsWith("QChar")) {
bool ok;
- const int code = value.toInt(&ok);
- return ok ? reformatCharacter(code, format) : value;
+ const int code = d.value.toInt(&ok);
+ return ok ? reformatCharacter(code, format) : d.value;
}
if (format == HexadecimalIntegerFormat
|| format == DecimalIntegerFormat
|| format == OctalIntegerFormat
|| format == BinaryIntegerFormat) {
- bool isSigned = value.startsWith(QLatin1Char('-'));
- quint64 raw = isSigned ? quint64(value.toLongLong()): value.toULongLong();
- return reformatInteger(raw, format, data.size, isSigned);
+ bool isSigned = d.value.startsWith(QLatin1Char('-'));
+ quint64 raw = isSigned ? quint64(d.value.toLongLong()) : d.value.toULongLong();
+ return reformatInteger(raw, format, d.size, isSigned);
}
if (format == ScientificFloatFormat) {
- double d = value.toDouble();
- return QString::number(d, 'e');
+ double dd = d.value.toDouble();
+ return QString::number(dd, 'e');
}
if (format == CompactFloatFormat) {
- double d = value.toDouble();
- return QString::number(d, 'g');
+ double dd = d.value.toDouble();
+ return QString::number(dd, 'g');
}
- if (data.type == "va_list")
- return value;
+ if (d.type == "va_list")
+ return d.value;
- if (!isPointerType(data.type) && !data.isVTablePointer()) {
+ if (!isPointerType(d.type) && !d.isVTablePointer()) {
bool ok = false;
- qulonglong integer = value.toULongLong(&ok, 0);
+ qulonglong integer = d.value.toULongLong(&ok, 0);
if (ok) {
- const int format = itemFormat(data);
- return reformatInteger(integer, format, data.size, false);
+ const int format = itemFormat();
+ return reformatInteger(integer, format, d.size, false);
}
}
- if (data.elided) {
- QString v = value;
+ if (d.elided) {
+ QString v = d.value;
v.chop(1);
v = translate(v);
- QString len = data.elided > 0 ? QString::number(data.elided)
+ QString len = d.elided > 0 ? QString::number(d.elided)
: QLatin1String("unknown length");
return v + QLatin1String("\"... (") + len + QLatin1Char(')');
}
- return translate(value);
+ return translate(d.value);
}
// Get a pointer address from pointer values reported by the debugger.
@@ -791,7 +563,7 @@ static inline quint64 pointerValue(QString data)
}
// Return the type used for editing
-static inline int editType(const WatchData &d)
+int WatchItem::editType() const
{
if (d.type == "bool")
return QVariant::Bool;
@@ -806,9 +578,9 @@ static inline int editType(const WatchData &d)
}
// Convert to editable (see above)
-static inline QVariant editValue(const WatchData &d)
+QVariant WatchItem::editValue() const
{
- switch (editType(d)) {
+ switch (editType()) {
case QVariant::Bool:
return d.value != QLatin1String("0") && d.value != QLatin1String("false");
case QVariant::ULongLong:
@@ -836,161 +608,28 @@ static inline QVariant editValue(const WatchData &d)
return QVariant(translate(stringValue));
}
-bool WatchModel::canFetchMore(const QModelIndex &idx) const
+bool WatchItem::canFetchMore() const
{
- if (!idx.isValid())
+ if (!d.hasChildren)
return false;
- WatchItem *item = watchItem(idx);
- QTC_ASSERT(item, return false);
- if (!contentIsValid() && !item->isInspect())
+ if (!watchModel())
return false;
- if (!item->iname.contains('.'))
+ if (!watchModel()->contentIsValid() && !d.isInspect())
return false;
- return !m_fetchTriggered.contains(item->iname);
+ return !fetchTriggered;
}
-void WatchModel::fetchMore(const QModelIndex &idx)
+void WatchItem::fetchMore()
{
- checkIndex(idx);
- if (!idx.isValid())
- return; // Triggered by ModelTester.
- WatchItem *item = watchItem(idx);
- QTC_ASSERT(item, return);
- QTC_ASSERT(!m_fetchTriggered.contains(item->iname), return);
- m_expandedINames.insert(item->iname);
- m_fetchTriggered.insert(item->iname);
- if (item->children.isEmpty()) {
- WatchData data = *item;
- data.setChildrenNeeded();
+ QTC_ASSERT(!fetchTriggered, return);
+ watchModel()->m_expandedINames.insert(d.iname);
+ fetchTriggered = true;
+ if (children().isEmpty()) {
+ d.setChildrenNeeded();
WatchUpdateFlags flags;
flags.tryIncremental = true;
- engine()->updateWatchData(data, flags);
- }
-}
-
-QModelIndex WatchModel::index(int row, int column, const QModelIndex &parent) const
-{
- checkIndex(parent);
- if (!hasIndex(row, column, parent))
- return QModelIndex();
-
- const WatchItem *item = watchItem(parent);
- QTC_ASSERT(item, return QModelIndex());
- if (row >= item->children.size())
- return QModelIndex();
- return createIndex(row, column, (void*)(item->children.at(row)));
-}
-
-QModelIndex WatchModel::parent(const QModelIndex &idx) const
-{
- checkIndex(idx);
- if (!idx.isValid())
- return QModelIndex();
-
- const WatchItem *item = watchItem(idx);
- const WatchItem *parent = item->parent;
- if (!parent || parent == m_root)
- return QModelIndex();
-
- const WatchItem *grandparent = parent->parent;
- if (!grandparent)
- return QModelIndex();
-
- const auto &uncles = grandparent->children;
- for (int i = 0, n = uncles.size(); i < n; ++i)
- if (uncles.at(i) == parent)
- return createIndex(i, 0, (void*) parent);
-
- return QModelIndex();
-}
-
-int WatchModel::rowCount(const QModelIndex &idx) const
-{
- checkIndex(idx);
- if (!idx.isValid())
- return m_root->children.size();
- if (idx.column() > 0)
- return 0;
- return watchItem(idx)->children.size();
-}
-
-int WatchModel::columnCount(const QModelIndex &idx) const
-{
- checkIndex(idx);
- return 3;
-}
-
-bool WatchModel::hasChildren(const QModelIndex &parent) const
-{
- checkIndex(parent);
- WatchItem *item = watchItem(parent);
- return !item || item->hasChildren;
-}
-
-WatchItem *WatchModel::watchItem(const QModelIndex &idx) const
-{
- checkIndex(idx);
- WatchItem *item = idx.isValid()
- ? static_cast<WatchItem*>(idx.internalPointer()) : m_root;
- CHECK(checkItem(item));
- return item;
-}
-
-QModelIndex WatchModel::watchIndex(const WatchItem *item) const
-{
- CHECK(checkItem(item));
- return watchIndexHelper(item, m_root, QModelIndex());
-}
-
-QModelIndex WatchModel::watchIndexHelper(const WatchItem *needle,
- const WatchItem *parentItem, const QModelIndex &parentIndex) const
-{
- checkIndex(parentIndex);
- if (needle == parentItem)
- return parentIndex;
- for (int i = parentItem->children.size(); --i >= 0; ) {
- const WatchItem *childItem = parentItem->children.at(i);
- QModelIndex childIndex = index(i, 0, parentIndex);
- QModelIndex idx = watchIndexHelper(needle, childItem, childIndex);
- checkIndex(idx);
- if (idx.isValid())
- return idx;
+ watchModel()->engine()->updateWatchData(d, flags);
}
- return QModelIndex();
-}
-
-void WatchModel::emitDataChanged(int column, const QModelIndex &parentIndex)
-{
- checkIndex(parentIndex);
- QModelIndex idx1 = index(0, column, parentIndex);
- QModelIndex idx2 = index(rowCount(parentIndex) - 1, column, parentIndex);
- if (idx1.isValid() && idx2.isValid())
- emit dataChanged(idx1, idx2);
- //qDebug() << "CHANGING:\n" << idx1 << "\n" << idx2 << "\n"
- // << data(parentIndex, INameRole).toString();
- checkIndex(idx1);
- checkIndex(idx2);
- for (int i = rowCount(parentIndex); --i >= 0; )
- emitDataChanged(column, index(i, 0, parentIndex));
-}
-
-void WatchModel::invalidateAll(const QModelIndex &parentIndex)
-{
- checkIndex(parentIndex);
- QModelIndex idx1 = index(0, 0, parentIndex);
- QModelIndex idx2 = index(rowCount(parentIndex) - 1, columnCount(parentIndex) - 1, parentIndex);
- checkIndex(idx1);
- checkIndex(idx2);
- if (idx1.isValid() && idx2.isValid())
- emit dataChanged(idx1, idx2);
-}
-
-void WatchModel::resetValueCacheRecursively(WatchItem *item)
-{
- m_valueCache[item->iname] = item->value;
- const WatchItems &items = item->children;
- for (int i = items.size(); --i >= 0; )
- resetValueCacheRecursively(items.at(i));
}
// Truncate value for item view, maintaining quotes.
@@ -1005,12 +644,12 @@ static QString truncateValue(QString v)
return v;
}
-int WatchModel::itemFormat(const WatchData &data) const
+int WatchItem::itemFormat() const
{
- const int individualFormat = theIndividualFormats.value(data.iname, AutomaticFormat);
+ const int individualFormat = theIndividualFormats.value(d.iname, AutomaticFormat);
if (individualFormat != AutomaticFormat)
return individualFormat;
- return theTypeFormats.value(stripForFormat(data.type), AutomaticFormat);
+ return theTypeFormats.value(stripForFormat(d.type), AutomaticFormat);
}
bool WatchModel::contentIsValid() const
@@ -1022,57 +661,32 @@ bool WatchModel::contentIsValid() const
return m_handler->m_contentsValid;
}
-#if USE_EXPENSIVE_CHECKS
-void WatchModel::checkTree()
-{
- QSet<QByteArray> inames;
- checkTree(m_root, &inames);
- QSet<QByteArray> current = m_cache.keys().toSet();
- Q_ASSERT(inames == current);
-}
-
-void WatchModel::checkTree(WatchItem *item, QSet<QByteArray> *inames)
-{
- checkItem(item);
- inames->insert(item->iname);
- for (int i = 0, n = item->children.size(); i != n; ++i)
- checkTree(item->children.at(i), inames);
-}
-
-void WatchModel::checkItem(const WatchItem *item) const
-{
- Q_ASSERT(item->children.size() < 1000 * 1000);
- Q_ASSERT(m_cache2.contains(item));
- Q_ASSERT(m_cache2.value(item) == item->iname);
- Q_ASSERT(m_cache.value(item->iname) == item);
-}
-#endif
-
-static QString expression(const WatchItem *item)
+QString WatchItem::expression() const
{
- if (!item->exp.isEmpty())
- return QString::fromLatin1(item->exp);
- if (item->address && !item->type.isEmpty()) {
+ if (!d.exp.isEmpty())
+ return QString::fromLatin1(d.exp);
+ if (d.address && !d.type.isEmpty()) {
return QString::fromLatin1("*(%1*)%2").
- arg(QLatin1String(item->type), QLatin1String(item->hexAddress()));
+ arg(QLatin1String(d.type), QLatin1String(d.hexAddress()));
}
- if (const WatchItem *parent = item->parent) {
- if (!parent->exp.isEmpty())
- return QString::fromLatin1("(%1).%2")
- .arg(QString::fromLatin1(parent->exp), item->name);
+ if (const WatchItem *p = parentItem()) {
+ if (!p->d.exp.isEmpty())
+ return QString::fromLatin1("(%1).%2").arg(QString::fromLatin1(p->d.exp), d.name);
}
return QString();
}
-QString WatchModel::displayName(const WatchItem *item) const
+QString WatchItem::displayName() const
{
QString result;
- if (item->parent == m_returnRoot)
- result = tr("returned value");
- else if (item->name == QLatin1String("*"))
- result = QLatin1Char('*') + item->parent->name;
+ if (!parentItem())
+ return result;
+ if (d.iname.startsWith("return"))
+ result = WatchModel::tr("returned value");
+ else if (parentItem()->d.name == QLatin1String("*"))
+ result = QLatin1Char('*') + parentItem()->d.name;
else
- result = removeNamespaces(item->name);
+ result = watchModel()->removeNamespaces(d.name);
// Simplyfy names that refer to base classes.
if (result.startsWith(QLatin1Char('['))) {
@@ -1084,144 +698,142 @@ QString WatchModel::displayName(const WatchItem *item) const
return result;
}
-QString WatchModel::displayValue(const WatchData &data) const
+QString WatchItem::displayValue() const
{
- QString result = removeNamespaces(truncateValue(formattedValue(data)));
- if (result.isEmpty() && data.address)
- result += QString::fromLatin1("@0x" + QByteArray::number(data.address, 16));
-// if (data.origaddr)
-// result += QString::fromLatin1(" (0x" + QByteArray::number(data.origaddr, 16) + ')');
+ QString result = watchModel()->removeNamespaces(truncateValue(formattedValue()));
+ if (result.isEmpty() && d.address)
+ result += QString::fromLatin1("@0x" + QByteArray::number(d.address, 16));
+// if (d.origaddr)
+// result += QString::fromLatin1(" (0x" + QByteArray::number(d.origaddr, 16) + ')');
return result;
}
-QString WatchModel::displayType(const WatchData &data) const
+QString WatchItem::displayType() const
{
- QString result = data.displayedType.isEmpty()
- ? niceTypeHelper(data.type)
- : data.displayedType;
- if (data.bitsize)
- result += QString::fromLatin1(":%1").arg(data.bitsize);
+ QString result = d.displayedType.isEmpty()
+ ? niceTypeHelper(d.type)
+ : d.displayedType;
+ if (d.bitsize)
+ result += QString::fromLatin1(":%1").arg(d.bitsize);
result.remove(QLatin1Char('\''));
- result = removeNamespaces(result);
+ result = watchModel()->removeNamespaces(result);
return result;
}
-QVariant WatchModel::data(const QModelIndex &idx, int role) const
+QColor WatchItem::color() const
{
- checkIndex(idx);
- if (!idx.isValid())
- return QVariant(); // Triggered by ModelTester.
-
- const WatchItem *item = watchItem(idx);
- const WatchItem &data = *item;
+ static const QColor red(200, 0, 0);
+ static const QColor gray(140, 140, 140);
+ if (watchModel()) {
+ if (!d.valueEnabled)
+ return gray;
+ if (!watchModel()->contentIsValid() && !d.isInspect())
+ return gray;
+ if (d.value.isEmpty()) // This might still show 0x...
+ return gray;
+ if (d.value != watchModel()->m_valueCache.value(d.iname))
+ return red;
+ }
+ return QColor();
+}
+QVariant WatchItem::data(int column, int role) const
+{
switch (role) {
case LocalsEditTypeRole:
- return QVariant(editType(data));
+ return QVariant(editType());
case LocalsNameRole:
- return QVariant(data.name);
+ return QVariant(d.name);
case LocalsIntegerBaseRole:
- if (isPointerType(data.type)) // Pointers using 0x-convention
+ if (isPointerType(d.type)) // Pointers using 0x-convention
return QVariant(16);
- return QVariant(formatToIntegerBase(itemFormat(data)));
+ return QVariant(formatToIntegerBase(itemFormat()));
case Qt::EditRole: {
- switch (idx.column()) {
+ switch (column) {
case 0:
- return QVariant(expression(item));
+ return QVariant(expression());
case 1:
- return editValue(data);
+ return editValue();
case 2:
// FIXME:: To be tested: Can debuggers handle those?
- if (!data.displayedType.isEmpty())
- return data.displayedType;
- return QString::fromUtf8(data.type);
+ if (!d.displayedType.isEmpty())
+ return d.displayedType;
+ return QString::fromUtf8(d.type);
}
}
case Qt::DisplayRole: {
- switch (idx.column()) {
+ switch (column) {
case 0:
- return displayName(item);
+ return displayName();
case 1:
- return displayValue(data);
+ return displayValue();
case 2:
- return displayType(data);
+ return displayType();
}
}
case Qt::ToolTipRole:
return boolSetting(UseToolTipsInLocalsView)
- ? data.toToolTip() : QVariant();
-
- case Qt::ForegroundRole: {
- static const QVariant red(QColor(200, 0, 0));
- static const QVariant gray(QColor(140, 140, 140));
- if (idx.column() == 1) {
- if (!data.valueEnabled)
- return gray;
- if (!contentIsValid() && !data.isInspect())
- return gray;
- if (data.value.isEmpty()) // This might still show 0x...
- return gray;
- if (data.value != m_valueCache.value(data.iname))
- return red;
- }
- break;
- }
+ ? d.toToolTip() : QVariant();
+
+ case Qt::ForegroundRole:
+ if (column == 1)
+ return color();
case LocalsExpressionRole:
- return QVariant(expression(item));
+ return QVariant(expression());
case LocalsRawExpressionRole:
- return data.exp;
+ return d.exp;
case LocalsINameRole:
- return data.iname;
+ return d.iname;
case LocalsExpandedRole:
- return m_expandedINames.contains(data.iname);
+ return watchModel()->m_expandedINames.contains(d.iname);
case LocalsTypeFormatListRole:
- return QVariant::fromValue(typeFormatList(data));
+ return QVariant::fromValue(watchModel()->typeFormatList(d));
case LocalsTypeRole:
- return removeNamespaces(displayType(data));
+ return watchModel()->removeNamespaces(displayType());
case LocalsRawTypeRole:
- return QString::fromLatin1(data.type);
+ return QString::fromLatin1(d.type);
case LocalsTypeFormatRole:
- return theTypeFormats.value(stripForFormat(data.type), AutomaticFormat);
+ return theTypeFormats.value(stripForFormat(d.type), AutomaticFormat);
case LocalsIndividualFormatRole:
- return theIndividualFormats.value(data.iname, AutomaticFormat);
+ return theIndividualFormats.value(d.iname, AutomaticFormat);
case LocalsRawValueRole:
- return data.value;
+ return d.value;
case LocalsObjectAddressRole:
- return data.address;
+ return d.address;
case LocalsPointerAddressRole:
- return data.origaddr;
+ return d.origaddr;
case LocalsIsWatchpointAtObjectAddressRole: {
BreakpointParameters bp(WatchpointAtAddress);
- bp.address = data.address;
- return engine()->breakHandler()->findWatchpoint(bp) != 0;
+ bp.address = d.address;
+ return watchModel()->engine()->breakHandler()->findWatchpoint(bp) != 0;
}
case LocalsSizeRole:
- return QVariant(data.size);
+ return QVariant(d.size);
case LocalsIsWatchpointAtPointerAddressRole:
- if (isPointerType(data.type)) {
+ if (isPointerType(d.type)) {
BreakpointParameters bp(WatchpointAtAddress);
- bp.address = pointerValue(data.value);
- return engine()->breakHandler()->findWatchpoint(bp) != 0;
+ bp.address = pointerValue(d.value);
+ return watchModel()->engine()->breakHandler()->findWatchpoint(bp) != 0;
}
return false;
@@ -1233,12 +845,12 @@ QVariant WatchModel::data(const QModelIndex &idx, int role) const
bool WatchModel::setData(const QModelIndex &idx, const QVariant &value, int role)
{
- checkIndex(idx);
-
if (!idx.isValid())
return false; // Triggered by ModelTester.
- WatchItem &data = *watchItem(idx);
+ WatchItem *item = static_cast<WatchItem *>(itemFromIndex(idx));
+ QTC_ASSERT(item, return false);
+ const WatchData &data = item->d;
switch (role) {
case Qt::EditRole:
@@ -1246,10 +858,10 @@ bool WatchModel::setData(const QModelIndex &idx, const QVariant &value, int role
case 0: // Watch expression: See delegate.
break;
case 1: // Change value
- engine()->assignValueInDebugger(&data, expression(&data), value);
+ engine()->assignValueInDebugger(&data, item->expression(), value);
break;
case 2: // TODO: Implement change type.
- engine()->assignValueInDebugger(&data, expression(&data), value);
+ engine()->assignValueInDebugger(&data, item->expression(), value);
break;
}
case LocalsExpandedRole:
@@ -1283,66 +895,46 @@ bool WatchModel::setData(const QModelIndex &idx, const QVariant &value, int role
return true;
}
-Qt::ItemFlags WatchModel::flags(const QModelIndex &idx) const
+Qt::ItemFlags WatchItem::flags(int column) const
{
- checkIndex(idx);
- if (!idx.isValid())
- return Qt::ItemFlags();
-
- WatchItem *item = watchItem(idx);
- QTC_ASSERT(item, return Qt::ItemFlags());
- const WatchData &data = *item;
- if (!contentIsValid() && !data.isInspect())
+ QTC_ASSERT(model(), return Qt::ItemFlags());
+ if (!watchModel()->contentIsValid() && !d.isInspect())
return Qt::ItemFlags();
// Enabled, editable, selectable, checkable, and can be used both as the
// source of a drag and drop operation and as a drop target.
- static const Qt::ItemFlags notEditable
- = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
- static const Qt::ItemFlags editable = notEditable | Qt::ItemIsEditable;
+ const Qt::ItemFlags notEditable = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
+ const Qt::ItemFlags editable = notEditable | Qt::ItemIsEditable;
// Disable editing if debuggee is positively running except for Inspector data
- const bool isRunning = engine() && engine()->state() == InferiorRunOk;
- if (isRunning && engine() && !engine()->hasCapability(AddWatcherWhileRunningCapability) &&
- !data.isInspect())
+ DebuggerEngine *engine = watchModel()->engine();
+ const bool isRunning = engine && engine->state() == InferiorRunOk;
+ if (isRunning && engine && !engine->hasCapability(AddWatcherWhileRunningCapability) &&
+ !d.isInspect())
return notEditable;
- if (data.isWatcher()) {
- if (idx.column() == 0 && data.iname.count('.') == 1)
+ if (d.isWatcher()) {
+ if (column == 0 && d.iname.count('.') == 1)
return editable; // Watcher names are editable.
- if (!data.name.isEmpty()) {
+ if (!d.name.isEmpty()) {
// FIXME: Forcing types is not implemented yet.
//if (idx.column() == 2)
// return editable; // Watcher types can be set by force.
- if (idx.column() == 1 && data.valueEditable)
+ if (column == 1 && d.valueEditable)
return editable; // Watcher values are sometimes editable.
}
- } else if (data.isLocal()) {
- if (idx.column() == 1 && data.valueEditable)
+ } else if (d.isLocal()) {
+ if (column == 1 && d.valueEditable)
return editable; // Locals values are sometimes editable.
- } else if (data.isInspect()) {
- if (idx.column() == 1 && data.valueEditable)
+ } else if (d.isInspect()) {
+ if (column == 1 && d.valueEditable)
return editable; // Inspector values are sometimes editable.
}
return notEditable;
}
-QVariant WatchModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (orientation == Qt::Vertical)
- return QVariant();
- if (role == Qt::DisplayRole) {
- switch (section) {
- case 0: return QString(tr("Name") + QLatin1String(" "));
- case 1: return QString(tr("Value") + QLatin1String(" "));
- case 2: return QString(tr("Type") + QLatin1String(" "));
- }
- }
- return QVariant();
-}
-
static inline QString msgArrayFormat(int n)
{
return WatchModel::tr("Array of %n items", 0, n);
@@ -1486,148 +1078,85 @@ inline bool operator<(const WatchDataSortKey &k1, const WatchDataSortKey &k2)
return watchDataLessThan(k1.iname, k1.sortId, k2.iname, k2.sortId);
}
-bool watchItemSorter(const WatchItem *item1, const WatchItem *item2)
+bool watchItemSorter(const TreeItem *item1, const TreeItem *item2)
{
- return watchDataLessThan(item1->iname, item1->sortId, item2->iname, item2->sortId);
+ const WatchItem *it1 = static_cast<const WatchItem *>(item1);
+ const WatchItem *it2 = static_cast<const WatchItem *>(item2);
+ return watchDataLessThan(it1->d.iname, it1->d.sortId, it2->d.iname, it2->d.sortId);
}
-static int findInsertPosition(const QList<WatchItem *> &list, const WatchItem *item)
+static int findInsertPosition(const QVector<TreeItem *> &list, const WatchItem *item)
{
sortWatchDataAlphabetically = boolSetting(SortStructMembers);
- const QList<WatchItem *>::const_iterator it =
- qLowerBound(list.begin(), list.end(), item, watchItemSorter);
+ const auto it = qLowerBound(list.begin(), list.end(), item, watchItemSorter);
return it - list.begin();
}
void WatchModel::insertDataItem(const WatchData &data, bool destructive)
{
-#if USE_WATCH_MODEL_TEST
- (void) new ModelTest(this, this);
-#endif
- m_fetchTriggered.remove(data.iname);
- CHECK(checkTree());
-
QTC_ASSERT(!data.iname.isEmpty(), qDebug() << data.toString(); return);
if (WatchItem *item = findItem(data.iname)) {
// Remove old children.
+ item->fetchTriggered = false;
if (destructive)
- destroyChildren(item);
+ item->removeChildren();
// Overwrite old entry.
- assignData(item, data);
- QModelIndex idx = watchIndex(item);
- checkIndex(idx);
- emit dataChanged(idx, idx.sibling(idx.row(), 2));
+ item->d = data;
+ item->update();
} else {
// Add new entry.
WatchItem *parent = findItem(parentName(data.iname));
QTC_ASSERT(parent, return);
- WatchItem *newItem = createItem(data);
- newItem->parent = parent;
- const int row = findInsertPosition(parent->children, newItem);
- QModelIndex idx = watchIndex(parent);
- checkIndex(idx);
- beginInsertRows(idx, row, row);
- parent->children.insert(row, newItem);
- endInsertRows();
- if (m_expandedINames.contains(parent->iname))
- emit itemIsExpanded(idx);
+ WatchItem *newItem = new WatchItem;
+ newItem->d = data;
+ const int row = findInsertPosition(parent->children(), newItem);
+ parent->insertChild(row, newItem);
+ if (m_expandedINames.contains(parent->d.iname)) {
+ emit inameIsExpanded(parent->d.iname);
+ emit itemIsExpanded(indexFromItem(parent));
+ }
}
}
-// Identify items that have to be removed, i.e. current items that
-// have an ancestor in the list, but do not appear in the list themselves.
-bool WatchModel::ancestorChanged(const QSet<QByteArray> &inames, WatchItem *item) const
-{
- if (item == m_root)
- return false;
- WatchItem *parent = item->parent;
- if (inames.contains(parent->iname))
- return true;
- return ancestorChanged(inames, parent);
-}
-
void WatchModel::insertBulkData(const QList<WatchData> &list)
{
-#if 1
for (int i = 0, n = list.size(); i != n; ++i) {
const WatchData &data = list.at(i);
insertDataItem(data, true);
m_handler->showEditValue(data);
}
-#else
- // Destroy unneeded items.
- QSet<QByteArray> inames;
- for (int i = list.size(); --i >= 0; )
- inames.insert(list.at(i).iname);
-
- QList<QByteArray> toDestroy;
- for (Cache::const_iterator it = m_cache.begin(), et = m_cache.end(); it != et; ++it)
- if (!inames.contains(it.key()) && ancestorChanged(inames, it.value()))
- toDestroy.append(it.key());
-
- for (int i = 0, n = toDestroy.size(); i != n; ++i) {
- // Can be destroyed as child of a previous item.
- WatchItem *item = findItem(toDestroy.at(i));
- if (item)
- destroyItem(item);
- }
-
- // All remaining items are changed or new.
- for (int i = 0, n = list.size(); i != n; ++i)
- insertDataItem(list.at(i), false);
-#endif
- CHECK(checkTree());
emit columnAdjustmentRequested();
}
-static void debugRecursion(QDebug &d, const WatchItem *item, int depth)
-{
- d << QString(2 * depth, QLatin1Char(' ')) << item->toString() << '\n';
- foreach (const WatchItem *child, item->children)
- debugRecursion(d, child, depth + 1);
-}
-
-QDebug operator<<(QDebug d, const WatchModel &m)
+int WatchItem::requestedFormat() const
{
- QDebug nospace = d.nospace();
- if (m.m_root)
- debugRecursion(nospace, m.m_root, 0);
- return d;
-}
-
-void WatchModel::formatRequests(QByteArray *out, const WatchItem *item) const
-{
- int format = theIndividualFormats.value(item->iname, AutomaticFormat);
+ int format = theIndividualFormats.value(d.iname, AutomaticFormat);
if (format == AutomaticFormat)
- format = theTypeFormats.value(stripForFormat(item->type), AutomaticFormat);
- if (format != AutomaticFormat)
- *out += item->iname + ":format=" + QByteArray::number(format) + ',';
- foreach (const WatchItem *child, item->children)
- formatRequests(out, child);
+ format = theTypeFormats.value(stripForFormat(d.type), AutomaticFormat);
+ return format;
}
-void WatchModel::showInEditorHelper(QString *contents, WatchItem *item, int depth)
+void WatchItem::showInEditorHelper(QString *contents, int depth) const
{
const QChar tab = QLatin1Char('\t');
const QChar nl = QLatin1Char('\n');
contents->append(QString(depth, tab));
- contents->append(item->name);
+ contents->append(d.name);
contents->append(tab);
- contents->append(item->value);
+ contents->append(d.value);
contents->append(tab);
- contents->append(QString::fromLatin1(item->type));
+ contents->append(QString::fromLatin1(d.type));
contents->append(nl);
- foreach (WatchItem *child, item->children)
- showInEditorHelper(contents, child, depth + 1);
+ foreach (const TreeItem *child, children())
+ static_cast<const WatchItem *>(child)->showInEditorHelper(contents, depth + 1);
}
void WatchModel::setCurrentItem(const QByteArray &iname)
{
if (WatchItem *item = findItem(iname)) {
- QModelIndex idx = watchIndex(item);
- checkIndex(idx);
+ QModelIndex idx = indexFromItem(item);
emit currentIndexRequested(idx);
}
}
@@ -1664,7 +1193,6 @@ void WatchHandler::cleanup()
m_model->m_expandedINames.clear();
theWatcherNames.remove(QByteArray());
m_model->reinitialize();
- m_model->m_fetchTriggered.clear();
m_separatedView->hide();
}
@@ -1698,6 +1226,32 @@ void WatchHandler::insertIncompleteData(const WatchData &data)
}
}
+void WatchHandler::insertItem(WatchItem *item)
+{
+ m_model->insertItem(item);
+}
+
+void WatchModel::insertItem(WatchItem *item)
+{
+ WatchItem *existing = findItem(item->d.iname);
+ if (existing)
+ removeItem(existing);
+
+ WatchItem *parent = findItem(parentName(item->d.iname));
+ QTC_ASSERT(parent, return);
+ const int row = findInsertPosition(parent->children(), item);
+ parent->insertChild(row, item);
+}
+
+void WatchModel::reexpandItems()
+{
+ foreach (const QByteArray &iname, m_expandedINames) {
+ WatchItem *item = findItem(iname);
+ emit itemIsExpanded(indexFromItem(item));
+ emit inameIsExpanded(iname);
+ }
+}
+
void WatchHandler::insertData(const WatchData &data)
{
QList<WatchData> list;
@@ -1722,7 +1276,24 @@ void WatchHandler::removeAllData(bool includeInspectData)
void WatchHandler::resetValueCache()
{
m_model->m_valueCache.clear();
- m_model->resetValueCacheRecursively(m_model->m_root);
+ TreeItem *root = m_model->rootItem();
+ root->walkTree([this, root](TreeItem *item) {
+ auto watchItem = static_cast<WatchItem *>(item);
+ m_model->m_valueCache[watchItem->d.iname] = watchItem->d.value;
+ });
+}
+
+void WatchHandler::purgeOutdatedItems(const QSet<QByteArray> &inames)
+{
+ foreach (const QByteArray &iname, inames) {
+ WatchItem *item = findItem(iname);
+ m_model->removeItem(item);
+ }
+
+ m_model->layoutChanged();
+ m_model->reexpandItems();
+ m_contentsValid = true;
+ updateWatchersWindow();
}
void WatchHandler::removeData(const QByteArray &iname)
@@ -1730,11 +1301,12 @@ void WatchHandler::removeData(const QByteArray &iname)
WatchItem *item = m_model->findItem(iname);
if (!item)
return;
- if (item->isWatcher()) {
- theWatcherNames.remove(item->exp);
+ if (item->d.isWatcher()) {
+ theWatcherNames.remove(item->d.exp);
saveWatchers();
}
- m_model->destroyItem(item);
+ m_model->removeItem(item);
+ delete item;
updateWatchersWindow();
}
@@ -1742,7 +1314,7 @@ void WatchHandler::removeChildren(const QByteArray &iname)
{
WatchItem *item = m_model->findItem(iname);
if (item)
- m_model->destroyChildren(item);
+ item->removeChildren();
updateWatchersWindow();
}
@@ -1883,7 +1455,15 @@ void WatchHandler::clearWatches()
{
if (theWatcherNames.isEmpty())
return;
- m_model->destroyChildren(m_model->m_watchRoot);
+
+ const QDialogButtonBox::StandardButton ret = CheckableMessageBox::doNotAskAgainQuestion(
+ Core::ICore::mainWindow(), tr("Remove All Expression Evaluators"),
+ tr("Are you sure you want to remove all expression evaluators?"),
+ Core::ICore::settings(), QLatin1String("RemoveAllWatchers"));
+ if (ret != QDialogButtonBox::Yes)
+ return;
+
+ m_model->m_watchRoot->removeChildren();
theWatcherNames.clear();
m_watcherCounter = 0;
updateWatchersWindow();
@@ -1895,8 +1475,8 @@ void WatchHandler::updateWatchersWindow()
// Force show/hide of watchers and return view.
static int previousShowWatch = -1;
static int previousShowReturn = -1;
- int showWatch = !m_model->m_watchRoot->children.isEmpty();
- int showReturn = !m_model->m_returnRoot->children.isEmpty();
+ int showWatch = !m_model->m_watchRoot->children().isEmpty();
+ int showReturn = !m_model->m_returnRoot->children().isEmpty();
if (showWatch == previousShowWatch && showReturn == previousShowReturn)
return;
previousShowWatch = showWatch;
@@ -1981,7 +1561,7 @@ void WatchHandler::loadSessionData()
theWatcherNames.clear();
m_watcherCounter = 0;
QVariant value = sessionValue("Watchers");
- m_model->destroyChildren(m_model->m_watchRoot);
+ m_model->m_watchRoot->removeChildren();
foreach (const QString &exp, value.toStringList())
watchExpression(exp);
}
@@ -1993,18 +1573,25 @@ WatchModelBase *WatchHandler::model() const
const WatchData *WatchHandler::watchData(const QModelIndex &idx) const
{
- return m_model->watchItem(idx);
+ TreeItem *item = m_model->itemFromIndex(idx);
+ return item ? &static_cast<WatchItem *>(item)->d : 0;
}
void WatchHandler::fetchMore(const QByteArray &iname) const
{
- QModelIndex idx = m_model->watchIndex(m_model->findItem(iname));
- m_model->checkIndex(idx);
- model()->fetchMore(idx);
+ WatchItem *item = m_model->findItem(iname);
+ if (item)
+ item->fetchMore();
}
const WatchData *WatchHandler::findData(const QByteArray &iname) const
{
+ const WatchItem *item = m_model->findItem(iname);
+ return item ? &item->d : 0;
+}
+
+WatchItem *WatchHandler::findItem(const QByteArray &iname) const
+{
return m_model->findItem(iname);
}
@@ -2035,36 +1622,20 @@ void WatchHandler::setFormat(const QByteArray &type0, int format)
else
theTypeFormats[type] = format;
saveFormats();
- m_model->emitDataChanged(1);
+ m_model->reinsertAllData();
}
int WatchHandler::format(const QByteArray &iname) const
{
int result = AutomaticFormat;
- if (const WatchData *item = m_model->findItem(iname)) {
- int result = theIndividualFormats.value(item->iname, AutomaticFormat);
+ if (const WatchItem *item = m_model->findItem(iname)) {
+ int result = theIndividualFormats.value(item->d.iname, AutomaticFormat);
if (result == AutomaticFormat)
- result = theTypeFormats.value(stripForFormat(item->type), AutomaticFormat);
+ result = theTypeFormats.value(stripForFormat(item->d.type), AutomaticFormat);
}
return result;
}
-QByteArray WatchHandler::expansionRequests() const
-{
- QByteArray ba;
- m_model->formatRequests(&ba, m_model->m_root);
- if (!m_model->m_expandedINames.isEmpty()) {
- QSetIterator<QByteArray> jt(m_model->m_expandedINames);
- while (jt.hasNext()) {
- QByteArray iname = jt.next();
- ba.append(iname);
- ba.append(',');
- }
- ba.chop(1);
- }
- return ba;
-}
-
QByteArray WatchHandler::typeFormatRequests() const
{
QByteArray ba;
@@ -2105,6 +1676,55 @@ QByteArray WatchHandler::individualFormatRequests() const
return ba;
}
+void WatchHandler::appendFormatRequests(DebuggerCommand *cmd)
+{
+ cmd->beginList("expanded");
+ QSetIterator<QByteArray> jt(m_model->m_expandedINames);
+ while (jt.hasNext()) {
+ QByteArray iname = jt.next();
+ //WatchItem *item = m_model->findItem(iname);
+ cmd->arg(iname);
+ //cmd->arg("format", item->requestedFormat());
+ }
+ cmd->endList();
+
+ cmd->beginGroup("typeformats");
+ QHashIterator<QByteArray, int> it(theTypeFormats);
+ while (it.hasNext()) {
+ it.next();
+ const int format = it.value();
+ if (format >= RawFormat && format < ArtificialFormatBase)
+ cmd->arg(it.key(), format);
+ }
+ cmd->endGroup();
+
+ cmd->beginGroup("formats");
+ QHashIterator<QByteArray, int> it2(theIndividualFormats);
+ while (it2.hasNext()) {
+ it2.next();
+ const int format = it2.value();
+ if (format >= RawFormat && format < ArtificialFormatBase)
+ cmd->arg(it2.key(), format);
+ }
+ cmd->endGroup();
+}
+
+void WatchHandler::addDumpers(const GdbMi &dumpers)
+{
+ foreach (const GdbMi &dumper, dumpers.children()) {
+ QStringList formats(tr("Raw structure"));
+ foreach (const QByteArray &format, dumper["formats"].data().split(',')) {
+ if (format == "Normal")
+ formats.append(tr("Normal"));
+ else if (format == "Displayed")
+ formats.append(tr("Displayed"));
+ else if (!format.isEmpty())
+ formats.append(QString::fromLatin1(format));
+ }
+ addTypeFormats(dumper["type"].data(), formats);
+ }
+}
+
void WatchHandler::addTypeFormats(const QByteArray &type, const QStringList &formats)
{
m_model->m_reportedTypeFormats.insert(QLatin1String(stripForFormat(type)), formats);
@@ -2113,7 +1733,7 @@ void WatchHandler::addTypeFormats(const QByteArray &type, const QStringList &for
QString WatchHandler::editorContents()
{
QString contents;
- m_model->showInEditorHelper(&contents, m_model->m_root, 0);
+ m_model->root()->showInEditorHelper(&contents, 0);
return contents;
}
@@ -2152,16 +1772,7 @@ void WatchHandler::scheduleResetLocation()
void WatchHandler::resetLocation()
{
- if (m_resetLocationScheduled) {
- m_resetLocationScheduled = false;
- //m_model->invalidateAll(); FIXME
- }
-}
-
-bool WatchHandler::isValidToolTip(const QByteArray &iname) const
-{
- WatchItem *item = m_model->findItem(iname);
- return item && !item->type.trimmed().isEmpty();
+ m_resetLocationScheduled = false;
}
void WatchHandler::setCurrentItem(const QByteArray &iname)
@@ -2177,7 +1788,7 @@ QHash<QByteArray, int> WatchHandler::watcherNames()
void WatchHandler::setUnprintableBase(int base)
{
theUnprintableBase = base;
- m_model->emitAllChanged();
+ m_model->layoutChanged();
}
int WatchHandler::unprintableBase()
@@ -2219,6 +1830,83 @@ TypeFormatItem TypeFormatList::find(int format) const
return TypeFormatItem();
}
+////////////////////////////////////////////////////////////////////
+//
+// WatchItem
+//
+////////////////////////////////////////////////////////////////////
+
+WatchItem::WatchItem()
+ : fetchTriggered(false)
+{}
+
+WatchItem::WatchItem(const QByteArray &i, const QString &n)
+{
+ fetchTriggered = false;
+ d.iname = i;
+ d.name = n;
+}
+
+WatchItem::WatchItem(const WatchData &data)
+ : d(data), fetchTriggered(false)
+{
+}
+
+WatchItem::WatchItem(const GdbMi &data)
+ : fetchTriggered(false)
+{
+ d.iname = data["iname"].data();
+
+ GdbMi wname = data["wname"];
+ if (wname.isValid()) // Happens (only) for watched expressions.
+ d.name = QString::fromUtf8(QByteArray::fromHex(wname.data()));
+ else
+ d.name = QString::fromLatin1(data["name"].data());
+
+ parseWatchData(data);
+
+ if (wname.isValid())
+ d.exp = d.name.toUtf8();
+}
+
+WatchItem *WatchItem::parentItem() const
+{
+ return dynamic_cast<WatchItem *>(parent());
+}
+
+const WatchModel *WatchItem::watchModel() const
+{
+ return static_cast<const WatchModel *>(model());
+}
+
+WatchModel *WatchItem::watchModel()
+{
+ return static_cast<WatchModel *>(model());
+}
+
+void WatchItem::parseWatchData(const GdbMi &input)
+{
+ auto itemHandler = [this](const WatchData &data) {
+ d = data;
+ };
+ auto childHandler = [this](const WatchData &innerData, const GdbMi &innerInput) {
+ WatchItem *item = new WatchItem(innerData);
+ item->parseWatchData(innerInput);
+ appendChild(item);
+ };
+
+ auto itemAdder = [this](const WatchData &data) {
+ appendChild(new WatchItem(data));
+ };
+
+ auto arrayDecoder = [itemAdder](const WatchData &childTemplate,
+ const QByteArray &encodedData, int encoding) {
+ decodeArrayData(itemAdder, childTemplate, encodedData, encoding);
+ };
+
+ parseChildrenData(d, input, itemHandler, childHandler, arrayDecoder);
+}
+
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/watchhandler.h b/src/plugins/debugger/watchhandler.h
index e5f5f9b9a43..444bef881ff 100644
--- a/src/plugins/debugger/watchhandler.h
+++ b/src/plugins/debugger/watchhandler.h
@@ -33,16 +33,58 @@
#include "watchdata.h"
-#include <QAbstractItemModel>
+#include <utils/treemodel.h>
+
#include <QPointer>
#include <QVector>
namespace Debugger {
namespace Internal {
+class DebuggerCommand;
class SeparatedView;
class WatchModel;
+class WatchItem : public Utils::TreeItem
+{
+public:
+ WatchItem();
+ WatchItem(const QByteArray &i, const QString &n);
+ explicit WatchItem(const WatchData &data);
+ explicit WatchItem(const GdbMi &data);
+
+ WatchItem *parentItem() const;
+ const WatchModel *watchModel() const;
+ WatchModel *watchModel();
+
+ QVariant data(int column, int role) const;
+ Qt::ItemFlags flags(int column) const;
+
+ bool canFetchMore() const;
+ void fetchMore();
+
+ QString displayName() const;
+ QString displayType() const;
+ QString displayValue() const;
+ QString formattedValue() const;
+ QString expression() const;
+
+ int itemFormat() const;
+
+ QVariant editValue() const;
+ int editType() const;
+ QColor color() const;
+
+ int requestedFormat() const;
+ void showInEditorHelper(QString *contents, int depth) const;
+ WatchItem *findItem(const QByteArray &iname);
+ void parseWatchData(const GdbMi &input);
+
+public:
+ WatchData d;
+ bool fetchTriggered;
+};
+
// Special formats. Keep in sync with dumper.py.
enum DisplayFormat
{
@@ -108,25 +150,22 @@ public:
Q_DECLARE_METATYPE(Debugger::Internal::TypeFormatList)
namespace Debugger {
+namespace Internal {
class DebuggerEngine;
-namespace Internal {
-
class UpdateParameters
{
public:
- UpdateParameters() { tryPartial = tooltipOnly = false; }
+ UpdateParameters() { tryPartial = false; }
bool tryPartial;
- bool tooltipOnly;
QByteArray varList;
- QString tooltipExpression;
};
typedef QHash<QString, QStringList> DumperTypeFormats; // Type name -> Dumper Formats
-class WatchModelBase : public QAbstractItemModel
+class WatchModelBase : public Utils::TreeModel
{
Q_OBJECT
@@ -136,6 +175,7 @@ public:
signals:
void currentIndexRequested(const QModelIndex &idx);
void itemIsExpanded(const QModelIndex &idx);
+ void inameIsExpanded(const QByteArray &iname);
void columnAdjustmentRequested();
};
@@ -159,6 +199,7 @@ public:
const WatchData *watchData(const QModelIndex &) const;
void fetchMore(const QByteArray &iname) const;
const WatchData *findData(const QByteArray &iname) const;
+ WatchItem *findItem(const QByteArray &iname) const;
const WatchData *findCppLocalVariable(const QString &name) const;
bool hasItem(const QByteArray &iname) const;
@@ -171,12 +212,12 @@ public:
static QStringList watchedExpressions();
static QHash<QByteArray, int> watcherNames();
- QByteArray expansionRequests() const;
QByteArray typeFormatRequests() const;
QByteArray individualFormatRequests() const;
int format(const QByteArray &iname) const;
+ void addDumpers(const GdbMi &dumpers);
void addTypeFormats(const QByteArray &type, const QStringList &formats);
void setTypeFormats(const DumperTypeFormats &typeFormats);
DumperTypeFormats typeFormats() const;
@@ -190,18 +231,20 @@ public:
void scheduleResetLocation();
void resetLocation();
- bool isValidToolTip(const QByteArray &iname) const;
void setCurrentItem(const QByteArray &iname);
void updateWatchersWindow();
+ void appendFormatRequests(DebuggerCommand *cmd);
void insertData(const WatchData &data); // Convenience.
void insertData(const QList<WatchData> &list);
void insertIncompleteData(const WatchData &data);
+ void insertItem(WatchItem *item);
void removeData(const QByteArray &iname);
void removeChildren(const QByteArray &iname);
void removeAllData(bool includeInspectData = false);
void resetValueCache();
+ void purgeOutdatedItems(const QSet<QByteArray> &inames);
private:
friend class WatchModel;
diff --git a/src/plugins/debugger/watchwindow.cpp b/src/plugins/debugger/watchwindow.cpp
index 55b2e7da4ed..2ea8632e58e 100644
--- a/src/plugins/debugger/watchwindow.cpp
+++ b/src/plugins/debugger/watchwindow.cpp
@@ -44,9 +44,12 @@
#include <texteditor/syntaxhighlighter.h>
+#include <coreplugin/messagebox.h>
+
+#include <utils/fancylineedit.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
-#include <utils/fancylineedit.h>
+#include <utils/treemodel.h>
#include <QApplication>
#include <QClipboard>
@@ -55,11 +58,11 @@
#include <QInputDialog>
#include <QItemDelegate>
#include <QMenu>
-#include <QMessageBox>
#include <QMetaProperty>
#include <QMimeData>
#include <QScrollBar>
#include <QTimer>
+#include <QTextStream>
// For InputDialog, move to Utils?
#include <coreplugin/helpmanager.h>
@@ -68,14 +71,6 @@
#include <QButtonGroup>
#include <QDialogButtonBox>
-//#define USE_WATCH_MODEL_TEST 1
-
-#if USE_WATCH_MODEL_TEST
-#include <modeltest.h>
-#endif
-
-Q_DECLARE_METATYPE(QModelIndex)
-
/////////////////////////////////////////////////////////////////////
//
// WatchDelegate
@@ -85,8 +80,6 @@ Q_DECLARE_METATYPE(QModelIndex)
namespace Debugger {
namespace Internal {
-const char CurrentIndex[] = "CurrentIndex";
-
class WatchDelegate : public QItemDelegate
{
public:
@@ -177,21 +170,6 @@ static inline uint sizeOf(const QModelIndex &m)
return m.data(LocalsSizeRole).toUInt();
}
-// Create a map of value->name for register markup.
-typedef QMap<quint64, QString> RegisterMap;
-typedef RegisterMap::const_iterator RegisterMapConstIt;
-
-RegisterMap registerMap(const DebuggerEngine *engine)
-{
- RegisterMap result;
- foreach (const Register &reg, engine->registerHandler()->registers()) {
- const QVariant v = reg.editValue();
- if (v.type() == QVariant::ULongLong)
- result.insert(v.toULongLong(), QString::fromLatin1(reg.name));
- }
- return result;
-}
-
// Helper functionality to indicate the area of a member variable in
// a vector representing the memory area by a unique color
// number and tooltip. Parts of it will be overwritten when recursing
@@ -313,13 +291,12 @@ static MemoryMarkupList
if (sizeIsEstimate && !childCount)
return result; // Fixme: Exact size not known, no point in filling if no children.
// Punch in registers as 1-byte markers on top.
- const RegisterMapConstIt regcEnd = registerMap.constEnd();
- for (RegisterMapConstIt it = registerMap.constBegin(); it != regcEnd; ++it) {
+ for (auto it = registerMap.constBegin(), end = registerMap.constEnd(); it != end; ++it) {
if (it.key() >= address) {
const quint64 offset = it.key() - address;
if (offset < size) {
ranges[offset] = ColorNumberToolTip(registerColorNumber,
- WatchTreeView::tr("Register <i>%1</i>").arg(it.value()));
+ WatchTreeView::tr("Register <i>%1</i>").arg(QString::fromUtf8(it.value())));
} else {
break; // Sorted.
}
@@ -380,27 +357,27 @@ static void addVariableMemoryView(DebuggerEngine *engine, bool separateView,
const QPoint &p, QWidget *parent)
{
const QColor background = parent->palette().color(QPalette::Normal, QPalette::Base);
- const quint64 address = atPointerAddress ? pointerAddressOf(m) : addressOf(m);
+ MemoryViewSetupData data;
+ data.startAddress = atPointerAddress ? pointerAddressOf(m) : addressOf(m);
+ if (!data.startAddress)
+ return;
// Fixme: Get the size of pointee (see variableMemoryMarkup())?
const QString rootToolTip = variableToolTip(nameOf(m), typeOf(m), 0);
const quint64 typeSize = sizeOf(m);
const bool sizeIsEstimate = atPointerAddress || !typeSize;
const quint64 size = sizeIsEstimate ? 1024 : typeSize;
- if (!address)
- return;
- const QList<MemoryMarkup> markup =
- variableMemoryMarkup(m.model(), m, nameOf(m), rootToolTip,
- address, size,
- registerMap(engine),
+ data.markup = variableMemoryMarkup(m.model(), m, nameOf(m), rootToolTip,
+ data.startAddress, size,
+ engine->registerHandler()->registerMap(),
sizeIsEstimate, background);
- const unsigned flags = separateView
- ? DebuggerEngine::MemoryView|DebuggerEngine::MemoryReadOnly : 0;
- const QString title = atPointerAddress
+ data.flags = separateView ? DebuggerEngine::MemoryView|DebuggerEngine::MemoryReadOnly : 0;
+ QString pat = atPointerAddress
? WatchTreeView::tr("Memory at Pointer's Address \"%1\" (0x%2)")
- .arg(nameOf(m)).arg(address, 0, 16)
- : WatchTreeView::tr("Memory at Object's Address \"%1\" (0x%2)")
- .arg(nameOf(m)).arg(address, 0, 16);
- engine->openMemoryView(address, flags, markup, p, title, parent);
+ : WatchTreeView::tr("Memory at Object's Address \"%1\" (0x%2)");
+ data.title = pat.arg(nameOf(m)).arg(data.startAddress, 0, 16);
+ data.pos = p;
+ data.parent = parent;
+ engine->openMemoryView(data);
}
// Add a memory view of the stack layout showing local variables
@@ -436,16 +413,15 @@ static void addStackLayoutMemoryView(DebuggerEngine *engine, bool separateView,
end += 8 - remainder;
// Anything found and everything in a sensible range (static data in-between)?
if (end <= start || end - start > 100 * 1024) {
- QMessageBox::information(parent,
+ Core::AsynchronousMessageBox::information(
WatchTreeView::tr("Cannot Display Stack Layout"),
WatchTreeView::tr("Could not determine a suitable address range."));
return;
}
// Take a look at the register values. Extend the range a bit if suitable
// to show stack/stack frame pointers.
- const RegisterMap regMap = registerMap(engine);
- const RegisterMapConstIt regcEnd = regMap.constEnd();
- for (RegisterMapConstIt it = regMap.constBegin(); it != regcEnd; ++it) {
+ const RegisterMap regMap = engine->registerHandler()->registerMap();
+ for (auto it = regMap.constBegin(), cend = regMap.constEnd(); it != cend; ++it) {
const quint64 value = it.key();
if (value < start && start - value < 512)
start = value;
@@ -453,16 +429,18 @@ static void addStackLayoutMemoryView(DebuggerEngine *engine, bool separateView,
end = value + 1;
}
// Indicate all variables.
+ MemoryViewSetupData data;
const QColor background = parent->palette().color(QPalette::Normal, QPalette::Base);
- const MemoryMarkupList markup =
- variableMemoryMarkup(m, localsIndex, QString(),
+ data.startAddress = start;
+ data.markup = variableMemoryMarkup(m, localsIndex, QString(),
QString(), start, end - start,
regMap, true, background);
- const unsigned flags = separateView
+ data.flags = separateView
? (DebuggerEngine::MemoryView|DebuggerEngine::MemoryReadOnly) : 0;
- const QString title =
- WatchTreeView::tr("Memory Layout of Local Variables at 0x%1").arg(start, 0, 16);
- engine->openMemoryView(start, flags, markup, p, title, parent);
+ data.title = WatchTreeView::tr("Memory Layout of Local Variables at 0x%1").arg(start, 0, 16);
+ data.pos = p;
+ data.parent = parent;
+ engine->openMemoryView(data);
}
/////////////////////////////////////////////////////////////////////
@@ -484,10 +462,8 @@ WatchTreeView::WatchTreeView(WatchType type)
setAcceptDrops(true);
setDropIndicatorShown(true);
- connect(this, SIGNAL(expanded(QModelIndex)),
- SLOT(expandNode(QModelIndex)));
- connect(this, SIGNAL(collapsed(QModelIndex)),
- SLOT(collapseNode(QModelIndex)));
+ connect(this, &QTreeView::expanded, this, &WatchTreeView::expandNode);
+ connect(this, &QTreeView::collapsed, this, &WatchTreeView::collapseNode);
}
void WatchTreeView::expandNode(const QModelIndex &idx)
@@ -615,28 +591,23 @@ void WatchTreeView::fillFormatMenu(QMenu *formatMenu, const QModelIndex &mi)
formatMenu->addAction(tr("Treat All Characters as Printable"));
showUnprintableUnicode->setCheckable(true);
showUnprintableUnicode->setChecked(unprintableBase == 0);
- showUnprintableUnicode->setData(0);
showUnprintableEscape =
formatMenu->addAction(tr("Show Unprintable Characters as Escape Sequences"));
showUnprintableEscape->setCheckable(true);
showUnprintableEscape->setChecked(unprintableBase == -1);
- showUnprintableEscape->setData(-1);
showUnprintableOctal =
formatMenu->addAction(tr("Show Unprintable Characters as Octal"));
showUnprintableOctal->setCheckable(true);
showUnprintableOctal->setChecked(unprintableBase == 8);
- showUnprintableOctal->setData(8);
showUnprintableHexadecimal =
formatMenu->addAction(tr("Show Unprintable Characters as Hexadecimal"));
showUnprintableHexadecimal->setCheckable(true);
showUnprintableHexadecimal->setChecked(unprintableBase == 16);
- showUnprintableHexadecimal->setData(16);
-
- connect(showUnprintableUnicode, SIGNAL(triggered()), SLOT(onShowUnprintable()));
- connect(showUnprintableEscape, SIGNAL(triggered()), SLOT(onShowUnprintable()));
- connect(showUnprintableOctal, SIGNAL(triggered()), SLOT(onShowUnprintable()));
- connect(showUnprintableHexadecimal, SIGNAL(triggered()), SLOT(onShowUnprintable()));
+ connect(showUnprintableUnicode, &QAction::triggered, [this] { showUnprintable(0); });
+ connect(showUnprintableEscape, &QAction::triggered, [this] { showUnprintable(-1); });
+ connect(showUnprintableOctal, &QAction::triggered, [this] { showUnprintable(8); });
+ connect(showUnprintableHexadecimal, &QAction::triggered, [this] { showUnprintable(16); });
const QString spacer = QLatin1String(" ");
formatMenu->addSeparator();
@@ -651,19 +622,22 @@ void WatchTreeView::fillFormatMenu(QMenu *formatMenu, const QModelIndex &mi)
QAction *clearIndividualFormatAction = formatMenu->addAction(spacer + msg);
clearIndividualFormatAction->setCheckable(true);
clearIndividualFormatAction->setChecked(individualFormat == AutomaticFormat);
- connect(clearIndividualFormatAction, SIGNAL(triggered()),
- SLOT(onClearIndividualFormat()));
+ connect(clearIndividualFormatAction, &QAction::triggered, [this] {
+ const QModelIndexList active = activeRows();
+ foreach (const QModelIndex &idx, active)
+ setModelData(LocalsIndividualFormatRole, AutomaticFormat, idx);
+ });
for (int i = 0; i != alternativeFormats.size(); ++i) {
const QString display = spacer + alternativeFormats.at(i).display;
const int format = alternativeFormats.at(i).format;
QAction *act = new QAction(display, formatMenu);
- act->setData(format);
act->setCheckable(true);
act->setChecked(format == individualFormat);
- act->setProperty(CurrentIndex, QVariant::fromValue(mi));
formatMenu->addAction(act);
- connect(act, SIGNAL(triggered()), SLOT(onIndividualFormatChange()));
+ connect(act, &QAction::triggered, [this, act, format, mi] {
+ setModelData(LocalsIndividualFormatRole, format, mi);
+ });
}
formatMenu->addSeparator();
@@ -673,58 +647,30 @@ void WatchTreeView::fillFormatMenu(QMenu *formatMenu, const QModelIndex &mi)
QAction *clearTypeFormatAction = formatMenu->addAction(spacer + tr("Automatic"));
clearTypeFormatAction->setCheckable(true);
clearTypeFormatAction->setChecked(typeFormat == AutomaticFormat);
- connect(clearTypeFormatAction, SIGNAL(triggered()), SLOT(onClearTypeFormat()));
+ connect(clearTypeFormatAction, &QAction::triggered, [this] {
+ const QModelIndexList active = activeRows();
+ foreach (const QModelIndex &idx, active)
+ setModelData(LocalsTypeFormatRole, AutomaticFormat, idx);
+ });
for (int i = 0; i != alternativeFormats.size(); ++i) {
const QString display = spacer + alternativeFormats.at(i).display;
QAction *act = new QAction(display, formatMenu);
const int format = alternativeFormats.at(i).format;
- act->setData(format);
act->setCheckable(true);
act->setChecked(format == typeFormat);
- act->setProperty(CurrentIndex, QVariant::fromValue(mi));
formatMenu->addAction(act);
- connect(act, SIGNAL(triggered()), SLOT(onTypeFormatChange()));
+ connect(act, &QAction::triggered, [this, act, format, mi] {
+ setModelData(LocalsTypeFormatRole, format, mi);
+ });
}
}
-void WatchTreeView::onClearTypeFormat()
+void WatchTreeView::showUnprintable(int base)
{
- const QModelIndexList active = activeRows();
- foreach (const QModelIndex &idx, active)
- setModelData(LocalsTypeFormatRole, AutomaticFormat, idx);
-}
-
-void WatchTreeView::onClearIndividualFormat()
-{
- const QModelIndexList active = activeRows();
- foreach (const QModelIndex &idx, active)
- setModelData(LocalsIndividualFormatRole, AutomaticFormat, idx);
-}
-
-void WatchTreeView::onShowUnprintable()
-{
- QAction *act = qobject_cast<QAction *>(sender());
- QTC_ASSERT(act, return);
DebuggerEngine *engine = currentEngine();
WatchHandler *handler = engine->watchHandler();
- handler->setUnprintableBase(act->data().toInt());
-}
-
-void WatchTreeView::onTypeFormatChange()
-{
- QAction *act = qobject_cast<QAction *>(sender());
- QTC_ASSERT(act, return);
- QModelIndex idx = act->property(CurrentIndex).value<QModelIndex>();
- setModelData(LocalsTypeFormatRole, act->data(), idx);
-}
-
-void WatchTreeView::onIndividualFormatChange()
-{
- QAction *act = qobject_cast<QAction *>(sender());
- QTC_ASSERT(act, return);
- QModelIndex idx = act->property(CurrentIndex).value<QModelIndex>();
- setModelData(LocalsIndividualFormatRole, act->data(), idx);
+ handler->setUnprintableBase(base);
}
void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
@@ -810,11 +756,16 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
break;
p = pp;
}
+
+ bool showExpressionActions = (canHandleWatches || state == DebuggerNotReady) && m_type == WatchersType;
+
QString removeExp = p.data(LocalsExpressionRole).toString();
QAction actRemoveWatchExpression(removeWatchActionText(removeExp), 0);
- actRemoveWatchExpression.setEnabled(
- (canHandleWatches || state == DebuggerNotReady)
- && !exp.isEmpty() && m_type == WatchersType);
+ actRemoveWatchExpression.setEnabled(showExpressionActions && !exp.isEmpty());
+
+ QAction actRemoveAllWatchExpression(tr("Remove All Expression Evaluators"), 0);
+ actRemoveAllWatchExpression.setEnabled(showExpressionActions
+ && !handler->watchedExpressions().isEmpty());
QMenu formatMenu(tr("Change Local Display Format..."));
if (mi0.isValid())
@@ -891,6 +842,7 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
menu.addAction(&actInsertNewWatchItem);
menu.addAction(&actWatchExpression);
menu.addAction(&actRemoveWatchExpression);
+ menu.addAction(&actRemoveAllWatchExpression);
menu.addAction(&actSelectWidgetToWatch);
menu.addSeparator();
@@ -929,8 +881,11 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
AddressDialog dialog;
if (address)
dialog.setAddress(address);
- if (dialog.exec() == QDialog::Accepted)
- currentEngine()->openMemoryView(dialog.address(), false, MemoryMarkupList(), QPoint());
+ if (dialog.exec() == QDialog::Accepted) {
+ MemoryViewSetupData data;
+ data.startAddress = dialog.address();
+ currentEngine()->openMemoryView(data);
+ }
} else if (act == &actOpenMemoryViewAtObjectAddress) {
addVariableMemoryView(currentEngine(), true, mi0, false, ev->globalPos(), this);
} else if (act == &actOpenMemoryViewAtPointerAddress) {
@@ -950,8 +905,20 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
watchExpression(exp, name);
} else if (act == &actRemoveWatchExpression) {
handler->removeData(p.data(LocalsINameRole).toByteArray());
+ } else if (act == &actRemoveAllWatchExpression) {
+ handler->clearWatches();
} else if (act == &actCopy) {
- copyToClipboard(DebuggerToolTipManager::treeModelClipboardContents(model()));
+ QString text;
+ QTextStream str(&text);
+ handler->model()->rootItem()->walkTree([&str](Utils::TreeItem *item) {
+ str << QString(item->level(), QLatin1Char('\t'))
+ << item->data(0, Qt::DisplayRole).toString() << '\t'
+ << item->data(1, Qt::DisplayRole).toString() << '\t'
+ << item->data(2, Qt::DisplayRole).toString() << '\n';
+ });
+ QClipboard *clipboard = QApplication::clipboard();
+ clipboard->setText(text, QClipboard::Selection);
+ clipboard->setText(text, QClipboard::Clipboard);
} else if (act == &actCopyValue) {
copyToClipboard(mi1.data().toString());
} else if (act == &actShowInEditor) {
@@ -995,14 +962,14 @@ void WatchTreeView::setModel(QAbstractItemModel *model)
header()->hide();
}
- connect(model, SIGNAL(layoutChanged()), SLOT(resetHelper()));
- connect(model, SIGNAL(currentIndexRequested(QModelIndex)),
- SLOT(setCurrentIndex(QModelIndex)));
- connect(model, SIGNAL(itemIsExpanded(QModelIndex)),
- SLOT(handleItemIsExpanded(QModelIndex)));
-#if USE_WATCH_MODEL_TEST
- (void) new ModelTest(&m_filter, this);
-#endif
+ auto watchModel = qobject_cast<WatchModelBase *>(model);
+ QTC_ASSERT(watchModel, return);
+ connect(model, &QAbstractItemModel::layoutChanged,
+ this, &WatchTreeView::resetHelper);
+ connect(watchModel, &WatchModelBase::currentIndexRequested,
+ this, &QAbstractItemView::setCurrentIndex);
+ connect(watchModel, &WatchModelBase::itemIsExpanded,
+ this, &WatchTreeView::handleItemIsExpanded);
}
void WatchTreeView::rowActivated(const QModelIndex &index)
@@ -1046,8 +1013,10 @@ void WatchTreeView::resetHelper()
void WatchTreeView::reset()
{
BaseTreeView::reset();
- setRootIndex(model()->index(m_type, 0));
- resetHelper();
+ if (model()) {
+ setRootIndex(model()->index(m_type, 0));
+ resetHelper();
+ }
}
void WatchTreeView::doItemsLayout()
@@ -1106,8 +1075,8 @@ public:
setLayout(layout);
connect(m_buttons, SIGNAL(accepted()), m_lineEdit, SLOT(onEditingFinished()));
- connect(m_buttons, SIGNAL(accepted()), SLOT(accept()));
- connect(m_buttons, SIGNAL(rejected()), SLOT(reject()));
+ connect(m_buttons, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(m_buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
connect(m_hint, SIGNAL(linkActivated(QString)),
Core::HelpManager::instance(), SLOT(handleHelpRequest(QString)));
}
diff --git a/src/plugins/debugger/watchwindow.h b/src/plugins/debugger/watchwindow.h
index 21bc41c607d..8ba2a76ab94 100644
--- a/src/plugins/debugger/watchwindow.h
+++ b/src/plugins/debugger/watchwindow.h
@@ -67,20 +67,13 @@ public slots:
signals:
void currentIndexChanged(const QModelIndex &currentIndex);
-private slots:
+private:
void resetHelper();
void expandNode(const QModelIndex &idx);
void collapseNode(const QModelIndex &idx);
- void adjustSlider();
-
- void onClearIndividualFormat();
- void onClearTypeFormat();
- void onShowUnprintable();
+ Q_SLOT void adjustSlider(); // Used by single-shot timer.
- void onTypeFormatChange();
- void onIndividualFormatChange();
-
-private:
+ void showUnprintable(int base);
void doItemsLayout();
void keyPressEvent(QKeyEvent *ev);
void contextMenuEvent(QContextMenuEvent *ev);
diff --git a/src/plugins/designer/formeditorplugin.cpp b/src/plugins/designer/formeditorplugin.cpp
index f1a3f73ef6f..4d95d3d67ae 100644
--- a/src/plugins/designer/formeditorplugin.cpp
+++ b/src/plugins/designer/formeditorplugin.cpp
@@ -114,9 +114,9 @@ void FormEditorPlugin::extensionsInitialized()
mformtools->menu()->setTitle(tr("For&m Editor"));
mtools->addMenu(mformtools);
- connect(m_actionSwitchSource, SIGNAL(triggered()), this, SLOT(switchSourceForm()));
- Core::Context context(Designer::Constants::C_FORMEDITOR, Core::Constants::C_EDITORMANAGER);
- Core::Command *cmd = Core::ActionManager::registerAction(m_actionSwitchSource,
+ connect(m_actionSwitchSource, &QAction::triggered, this, &FormEditorPlugin::switchSourceForm);
+ Context context(C_FORMEDITOR, Core::Constants::C_EDITORMANAGER);
+ Command *cmd = ActionManager::registerAction(m_actionSwitchSource,
"FormEditor.FormSwitchSource", context);
cmd->setDefaultKeySequence(tr("Shift+F4"));
mformtools->addAction(cmd, Core::Constants::G_DEFAULT_THREE);
@@ -147,7 +147,7 @@ void FormEditorPlugin::initializeTemplates()
static QString currentFile()
{
if (const IDocument *document = EditorManager::currentDocument()) {
- const QString fileName = document->filePath();
+ const QString fileName = document->filePath().toString();
if (!fileName.isEmpty() && QFileInfo(fileName).isFile())
return fileName;
}
@@ -192,5 +192,5 @@ void FormEditorPlugin::switchSourceForm()
{
const QString fileToOpen = otherFile();
if (!fileToOpen.isEmpty())
- Core::EditorManager::openEditor(fileToOpen);
+ EditorManager::openEditor(fileToOpen);
}
diff --git a/src/plugins/designer/formeditorw.cpp b/src/plugins/designer/formeditorw.cpp
index ad4fbf9b8c9..df5d63ca9b0 100644
--- a/src/plugins/designer/formeditorw.cpp
+++ b/src/plugins/designer/formeditorw.cpp
@@ -130,7 +130,7 @@ class FormWindowEditorFactory : public TextEditor::TextEditorFactory
public:
FormWindowEditorFactory()
{
- setId(Designer::Constants::K_DESIGNER_XML_EDITOR_ID);
+ setId(K_DESIGNER_XML_EDITOR_ID);
setEditorCreator([]() { return new FormWindowEditor; });
setEditorWidgetCreator([]() { return new Internal::DesignerXmlEditorWidget; });
setDuplicatedSupported(false);
@@ -168,29 +168,29 @@ public:
void setupActions();
void setupViewActions();
- void addDockViewAction(Core::ActionContainer *viewMenu,
+ void addDockViewAction(ActionContainer *viewMenu,
int index,
- const Core::Context &context,
- const QString &title, Core::Id id);
+ const Context &context,
+ const QString &title, Id id);
- Core::ActionContainer *createPreviewStyleMenu(QActionGroup *actionGroup);
+ ActionContainer *createPreviewStyleMenu(QActionGroup *actionGroup);
void critical(const QString &errorMessage);
- void bindShortcut(Core::Command *command, QAction *action);
+ void bindShortcut(Command *command, QAction *action);
QAction *createEditModeAction(QActionGroup *ag,
- const Core::Context &context,
- Core::ActionContainer *medit,
+ const Context &context,
+ ActionContainer *medit,
const QString &actionName,
- Core::Id id,
+ Id id,
int toolNumber,
const QString &iconName = QString(),
const QString &keySequence = QString());
- Core::Command *addToolAction(QAction *a,
- const Core::Context &context, Core::Id id,
- Core::ActionContainer *c1, const QString &keySequence = QString(),
- Core::Id groupId = Core::Id());
+ Command *addToolAction(QAction *a,
+ const Context &context, Id id,
+ ActionContainer *c1, const QString &keySequence = QString(),
+ Id groupId = Id());
QToolBar *createEditorToolBar() const;
- Core::IEditor *createEditor();
+ IEditor *createEditor();
public:
QDesignerFormEditorInterface *m_formeditor;
@@ -198,12 +198,12 @@ public:
QDesignerFormWindowManagerInterface *m_fwm;
FormEditorW::InitializationStage m_initStage;
- QWidget *m_designerSubWindows[Designer::Constants::DesignerSubWindowCount];
+ QWidget *m_designerSubWindows[DesignerSubWindowCount];
QAction *m_lockAction;
QAction *m_resetLayoutAction;
- QList<Core::IOptionsPage *> m_settingsPages;
+ QList<IOptionsPage *> m_settingsPages;
QActionGroup *m_actionGroupEditMode;
QAction *m_actionPrint;
QAction *m_actionPreview;
@@ -213,17 +213,17 @@ public:
QSignalMapper m_shortcutMapper;
DesignerContext *m_context;
- Core::Context m_contexts;
+ Context m_contexts;
- QList<Core::Id> m_toolActionIds;
+ QList<Id> m_toolActionIds;
QWidget *m_modeWidget;
EditorWidget *m_editorWidget;
- Core::DesignMode *m_designMode;
+ DesignMode *m_designMode;
QWidget *m_editorToolBar;
- Core::EditorToolBar *m_toolBar;
+ EditorToolBar *m_toolBar;
- QMap<Core::Command *, QAction *> m_commandToDesignerAction;
+ QMap<Command *, QAction *> m_commandToDesignerAction;
FormWindowEditorFactory *m_xmlEditorFactory;
};
@@ -254,7 +254,7 @@ FormEditorData::FormEditorData() :
QTC_ASSERT(!d, return);
d = this;
- qFill(m_designerSubWindows, m_designerSubWindows + Designer::Constants::DesignerSubWindowCount,
+ qFill(m_designerSubWindows, m_designerSubWindows + DesignerSubWindowCount,
static_cast<QWidget *>(0));
m_formeditor->setTopLevel(ICore::mainWindow());
@@ -263,7 +263,7 @@ FormEditorData::FormEditorData() :
m_fwm = m_formeditor->formWindowManager();
QTC_ASSERT(m_fwm, return);
- m_contexts.add(Designer::Constants::C_FORMEDITOR);
+ m_contexts.add(C_FORMEDITOR);
setupActions();
@@ -456,7 +456,7 @@ void FormEditorData::fullInit()
void FormEditorData::initDesignerSubWindows()
{
- qFill(m_designerSubWindows, m_designerSubWindows + Designer::Constants::DesignerSubWindowCount, static_cast<QWidget*>(0));
+ qFill(m_designerSubWindows, m_designerSubWindows + DesignerSubWindowCount, static_cast<QWidget*>(0));
QDesignerWidgetBoxInterface *wb = QDesignerComponents::createWidgetBox(m_formeditor, 0);
wb->setWindowTitle(tr("Widget Box"));
@@ -489,7 +489,7 @@ void FormEditorData::initDesignerSubWindows()
m_initStage = FormEditorW::SubwindowsInitialized;
}
-QList<Core::IOptionsPage *> FormEditorW::optionsPages()
+QList<IOptionsPage *> FormEditorW::optionsPages()
{
return d->m_settingsPages;
}
@@ -760,7 +760,7 @@ QAction *FormEditorData::createEditModeAction(QActionGroup *ag,
if (!iconName.isEmpty())
rc->setIcon(designerIcon(iconName));
Command *command = ActionManager::registerAction(rc, id, context);
- command->setAttribute(Core::Command::CA_Hide);
+ command->setAttribute(Command::CA_Hide);
if (!keySequence.isEmpty())
command->setDefaultKeySequence(QKeySequence(keySequence));
bindShortcut(command, rc);
@@ -773,7 +773,7 @@ QAction *FormEditorData::createEditModeAction(QActionGroup *ag,
// Create a tool action
Command *FormEditorData::addToolAction(QAction *a, const Context &context, Id id,
ActionContainer *c1, const QString &keySequence,
- Core::Id groupId)
+ Id groupId)
{
Command *command = ActionManager::registerAction(a, id, context);
if (!keySequence.isEmpty())
@@ -784,7 +784,7 @@ Command *FormEditorData::addToolAction(QAction *a, const Context &context, Id id
return command;
}
-Core::IEditor *FormEditorData::createEditor()
+IEditor *FormEditorData::createEditor()
{
if (Designer::Constants::Internal::debug)
qDebug() << "FormEditorW::createEditor";
@@ -801,7 +801,7 @@ Core::IEditor *FormEditorData::createEditor()
m_toolBar->addEditor(formWindowEditor);
if (formWindowEditor) {
- Core::InfoBarEntry info(Core::Id(Constants::INFO_READ_ONLY),
+ InfoBarEntry info(Id(Constants::INFO_READ_ONLY),
tr("This file can only be edited in <b>Design</b> mode."));
info.setCustomButtonInfo(tr("Switch Mode"), []() { ModeManager::activateMode(Core::Constants::MODE_DESIGN); });
formWindowEditor->document()->infoBar()->addInfo(info);
diff --git a/src/plugins/designer/formtemplatewizardpage.cpp b/src/plugins/designer/formtemplatewizardpage.cpp
index 596562c7c8d..c29331a813e 100644
--- a/src/plugins/designer/formtemplatewizardpage.cpp
+++ b/src/plugins/designer/formtemplatewizardpage.cpp
@@ -91,10 +91,10 @@ FormTemplateWizardPage::FormTemplateWizardPage(QWidget * parent) :
setTitle(tr("Choose a Form Template"));
QVBoxLayout *layout = new QVBoxLayout;
- connect(m_newFormWidget, SIGNAL(currentTemplateChanged(bool)),
- this, SLOT(slotCurrentTemplateChanged(bool)));
- connect(m_newFormWidget, SIGNAL(templateActivated()),
- this, SIGNAL(templateActivated()));
+ connect(m_newFormWidget, &QDesignerNewFormWidgetInterface::currentTemplateChanged,
+ this, &FormTemplateWizardPage::slotCurrentTemplateChanged);
+ connect(m_newFormWidget, &QDesignerNewFormWidgetInterface::templateActivated,
+ this, &FormTemplateWizardPage::templateActivated);
layout->addWidget(m_newFormWidget);
setLayout(layout);
diff --git a/src/plugins/designer/formwindoweditor.cpp b/src/plugins/designer/formwindoweditor.cpp
index 1569475097a..7dfdaa4396a 100644
--- a/src/plugins/designer/formwindoweditor.cpp
+++ b/src/plugins/designer/formwindoweditor.cpp
@@ -95,7 +95,7 @@ bool FormWindowEditor::open(QString *errorString, const QString &fileName, const
form->setDirty(fileName != realFileName);
document->syncXmlFromFormWindow();
- document->setFilePath(absfileName);
+ document->setFilePath(Utils::FileName::fromString(absfileName));
document->setShouldAutoSave(false);
document->resourceHandler()->updateResources(true);
diff --git a/src/plugins/designer/formwindowfile.cpp b/src/plugins/designer/formwindowfile.cpp
index 025b10f0292..082c3f6462b 100644
--- a/src/plugins/designer/formwindowfile.cpp
+++ b/src/plugins/designer/formwindowfile.cpp
@@ -44,6 +44,8 @@
#include <QDebug>
#include <QTextCodec>
+using namespace Utils;
+
namespace Designer {
namespace Internal {
@@ -64,13 +66,13 @@ FormWindowFile::FormWindowFile(QDesignerFormWindowInterface *form, QObject *pare
connect(m_formWindow, SIGNAL(changed()), SLOT(updateIsModified()));
m_resourceHandler = new ResourceHandler(form);
- connect(this, SIGNAL(filePathChanged(QString,QString)),
+ connect(this, SIGNAL(filePathChanged(Utils::FileName,Utils::FileName)),
m_resourceHandler, SLOT(updateResources()));
}
bool FormWindowFile::save(QString *errorString, const QString &name, bool autoSave)
{
- const QString actualName = name.isEmpty() ? filePath() : name;
+ const FileName actualName = name.isEmpty() ? filePath() : FileName::fromString(name);
if (Designer::Constants::Internal::debug)
qDebug() << Q_FUNC_INFO << name << "->" << actualName;
@@ -80,11 +82,10 @@ bool FormWindowFile::save(QString *errorString, const QString &name, bool autoSa
if (actualName.isEmpty())
return false;
- const QFileInfo fi(actualName);
const QString oldFormName = m_formWindow->fileName();
if (!autoSave)
- m_formWindow->setFileName(fi.absoluteFilePath());
- const bool writeOK = writeFile(actualName, errorString);
+ m_formWindow->setFileName(actualName.toString());
+ const bool writeOK = writeFile(actualName.toString(), errorString);
m_shouldAutoSave = false;
if (autoSave)
return writeOK;
@@ -95,7 +96,7 @@ bool FormWindowFile::save(QString *errorString, const QString &name, bool autoSa
}
m_formWindow->setDirty(false);
- setFilePath(fi.absoluteFilePath());
+ setFilePath(actualName);
updateIsModified();
return true;
@@ -135,9 +136,9 @@ bool FormWindowFile::setContents(const QByteArray &contents)
return true;
}
-void FormWindowFile::setFilePath(const QString &newName)
+void FormWindowFile::setFilePath(const FileName &newName)
{
- m_formWindow->setFileName(newName);
+ m_formWindow->setFileName(newName.toString());
IDocument::setFilePath(newName);
}
@@ -173,7 +174,7 @@ bool FormWindowFile::reload(QString *errorString, ReloadFlag flag, ChangeType ty
emit changed();
} else {
emit aboutToReload();
- emit reloadRequested(errorString, filePath());
+ emit reloadRequested(errorString, filePath().toString());
const bool success = errorString->isEmpty();
emit reloadFinished(success);
return success;
diff --git a/src/plugins/designer/formwindowfile.h b/src/plugins/designer/formwindowfile.h
index b6ca5cee35a..bf26bf505f7 100644
--- a/src/plugins/designer/formwindowfile.h
+++ b/src/plugins/designer/formwindowfile.h
@@ -77,7 +77,7 @@ signals:
void reloadRequested(QString *errorString, const QString &);
public slots:
- void setFilePath(const QString &);
+ void setFilePath(const Utils::FileName &);
void setShouldAutoSave(bool sad = true) { m_shouldAutoSave = sad; }
void updateIsModified();
diff --git a/src/plugins/designer/gotoslot_test.cpp b/src/plugins/designer/gotoslot_test.cpp
index 758d056003b..ffd89b0d27c 100644
--- a/src/plugins/designer/gotoslot_test.cpp
+++ b/src/plugins/designer/gotoslot_test.cpp
@@ -178,12 +178,12 @@ public:
integration->emitNavigateToSlot(QLatin1String("pushButton"), QLatin1String("clicked()"),
QStringList());
- QCOMPARE(EditorManager::currentDocument()->filePath(), cppFile);
+ QCOMPARE(EditorManager::currentDocument()->filePath().toString(), cppFile);
QVERIFY(EditorManager::currentDocument()->isModified());
// Wait for updated documents
foreach (TextEditor::BaseTextEditor *editor, editors) {
- const QString filePath = editor->document()->filePath();
+ const QString filePath = editor->document()->filePath().toString();
if (auto parser = BuiltinEditorDocumentParser::get(filePath)) {
forever {
if (Document::Ptr document = parser->document()) {
@@ -234,15 +234,18 @@ public:
} // anonymous namespace
+namespace Designer {
+namespace Internal {
+
/// Check: Executes "Go To Slot..." on a QPushButton in a *.ui file and checks if the respective
/// header and source files are correctly updated.
-void Designer::Internal::FormEditorPlugin::test_gotoslot()
+void FormEditorPlugin::test_gotoslot()
{
QFETCH(QStringList, files);
(GoToSlotTestCase(files));
}
-void Designer::Internal::FormEditorPlugin::test_gotoslot_data()
+void FormEditorPlugin::test_gotoslot_data()
{
typedef QLatin1String _;
QTest::addColumn<QStringList>("files");
@@ -282,3 +285,6 @@ void Designer::Internal::FormEditorPlugin::test_gotoslot_data()
<< testDataDir.file(_("form.h"))
<< testDataDir.file(_("form.ui")));
}
+
+} // namespace Internal
+} // namespace Designer
diff --git a/src/plugins/designer/qtcreatorintegration.cpp b/src/plugins/designer/qtcreatorintegration.cpp
index 94c2630661e..11bef278584 100644
--- a/src/plugins/designer/qtcreatorintegration.cpp
+++ b/src/plugins/designer/qtcreatorintegration.cpp
@@ -85,10 +85,13 @@ QtCreatorIntegration::QtCreatorIntegration(QDesignerFormEditorInterface *core, Q
f |= SlotNavigationFeature;
f &= ~ResourceEditorFeature;
setFeatures(f);
- connect(this, SIGNAL(navigateToSlot(QString,QString,QStringList)),
- this, SLOT(slotNavigateToSlot(QString,QString,QStringList)));
- connect(this, SIGNAL(helpRequested(QString,QString)),
- this, SLOT(slotDesignerHelpRequested(QString,QString)));
+
+ connect(this, static_cast<void (QDesignerIntegrationInterface::*)
+ (const QString&, const QString&, const QStringList&)>
+ (&QDesignerIntegrationInterface::navigateToSlot),
+ this, &QtCreatorIntegration::slotNavigateToSlot);
+ connect(this, &QtCreatorIntegration::helpRequested,
+ this, &QtCreatorIntegration::slotDesignerHelpRequested);
slotSyncSettingsToDesigner();
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()),
this, SLOT(slotSyncSettingsToDesigner()));
@@ -510,7 +513,7 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
{
typedef QMap<int, Document::Ptr> DocumentMap;
- const QString currentUiFile = FormEditorW::activeEditor()->document()->filePath();
+ const QString currentUiFile = FormEditorW::activeEditor()->document()->filePath().toString();
#if 0
return Designer::Internal::navigateToSlot(currentUiFile, objectName, signalSignature, parameterNames, errorMessage);
#endif
@@ -528,20 +531,21 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
Snapshot newDocTable;
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());
+ for (Snapshot::const_iterator i = docTable.begin(), ei = docTable.end(); i != ei; ++i) {
+ const Project *project = SessionManager::projectForFile(i.key().toString());
if (project == uiProject)
- newDocTable.insert(it.value());
+ newDocTable.insert(i.value());
}
} else {
const CppTools::WorkingCopy workingCopy =
CppTools::CppModelManager::instance()->workingCopy();
- QHashIterator<QString, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
+ const Utils::FileName configFileName =
+ Utils::FileName::fromString(CppTools::CppModelManager::configurationFileName());
+ QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
while (it.hasNext()) {
it.next();
- const QString fileName = it.key();
- if (fileName != CppTools::CppModelManager::configurationFileName())
+ const Utils::FileName &fileName = it.key();
+ if (fileName != configFileName)
newDocTable.insert(docTable.document(fileName));
}
}
diff --git a/src/plugins/designer/resourcehandler.cpp b/src/plugins/designer/resourcehandler.cpp
index c4dc20d5348..7d0814f611b 100644
--- a/src/plugins/designer/resourcehandler.cpp
+++ b/src/plugins/designer/resourcehandler.cpp
@@ -35,6 +35,7 @@
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/nodesvisitor.h>
#include <projectexplorer/project.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/session.h>
#include <resourceeditor/resourcenode.h>
@@ -72,10 +73,10 @@ void QrcFilesVisitor::visitProjectNode(ProjectNode *projectNode)
void QrcFilesVisitor::visitFolderNode(FolderNode *folderNode)
{
foreach (const FileNode *fileNode, folderNode->fileNodes()) {
- if (fileNode->fileType() == ProjectExplorer::ResourceType)
+ if (fileNode->fileType() == ResourceType)
m_qrcFiles.append(fileNode->path());
}
- if (qobject_cast<ResourceEditor::ResourceTopLevelNode *>(folderNode))
+ if (dynamic_cast<ResourceEditor::ResourceTopLevelNode *>(folderNode))
m_qrcFiles.append(folderNode->path());
}
@@ -83,25 +84,23 @@ void QrcFilesVisitor::visitFolderNode(FolderNode *folderNode)
ResourceHandler::ResourceHandler(QDesignerFormWindowInterface *fw) :
QObject(fw),
m_form(fw),
- m_sessionNode(0),
- m_sessionWatcher(0),
+ m_initialized(false),
m_handlingResources(false)
{
}
void ResourceHandler::ensureInitialized()
{
- if (m_sessionNode)
+ if (m_initialized)
return;
- m_sessionNode = ProjectExplorer::SessionManager::sessionNode();
- m_sessionWatcher = new ProjectExplorer::NodesWatcher();
+ m_initialized = true;
+ ProjectTree *tree = ProjectTree::instance();
- connect(m_sessionWatcher, SIGNAL(filesAdded()), this, SLOT(updateResources()));
- connect(m_sessionWatcher, SIGNAL(filesRemoved()), this, SLOT(updateResources()));
- connect(m_sessionWatcher, SIGNAL(foldersAdded()), this, SLOT(updateResources()));
- connect(m_sessionWatcher, SIGNAL(foldersRemoved()), this, SLOT(updateResources()));
- m_sessionNode->registerWatcher(m_sessionWatcher);
+ connect(tree, SIGNAL(filesAdded()), this, SLOT(updateResources()));
+ connect(tree, SIGNAL(filesRemoved()), this, SLOT(updateResources()));
+ connect(tree, SIGNAL(foldersAdded()), this, SLOT(updateResources()));
+ connect(tree, SIGNAL(foldersRemoved()), this, SLOT(updateResources()));
m_originalUiQrcPaths = m_form->activeResourceFilePaths();
if (Designer::Constants::Internal::debug)
qDebug() << "ResourceHandler::ensureInitialized() origPaths=" << m_originalUiQrcPaths;
@@ -109,11 +108,7 @@ void ResourceHandler::ensureInitialized()
ResourceHandler::~ResourceHandler()
{
- // Close: Delete the Designer form window via embedding widget
- if (m_sessionNode && m_sessionWatcher) {
- m_sessionNode->unregisterWatcher(m_sessionWatcher);
- delete m_sessionWatcher;
- }
+
}
void ResourceHandler::updateResources(bool updateProjectResources)
diff --git a/src/plugins/designer/resourcehandler.h b/src/plugins/designer/resourcehandler.h
index 0c722de9deb..4e6db675e69 100644
--- a/src/plugins/designer/resourcehandler.h
+++ b/src/plugins/designer/resourcehandler.h
@@ -38,10 +38,7 @@ QT_BEGIN_NAMESPACE
class QDesignerFormWindowInterface;
QT_END_NAMESPACE
-namespace ProjectExplorer {
-class SessionNode;
-class NodesWatcher;
-}
+namespace ProjectExplorer { class SessionNode; }
namespace Designer {
namespace Internal {
@@ -70,8 +67,7 @@ private:
void ensureInitialized();
QDesignerFormWindowInterface * const m_form;
QStringList m_originalUiQrcPaths;
- ProjectExplorer::SessionNode *m_sessionNode;
- ProjectExplorer::NodesWatcher *m_sessionWatcher;
+ bool m_initialized;
bool m_handlingResources;
};
diff --git a/src/plugins/diffeditor/diffeditor.cpp b/src/plugins/diffeditor/diffeditor.cpp
index ed224c0028e..f0a21fd21a3 100644
--- a/src/plugins/diffeditor/diffeditor.cpp
+++ b/src/plugins/diffeditor/diffeditor.cpp
@@ -44,6 +44,9 @@
#include <texteditor/displaysettings.h>
#include <texteditor/marginsettings.h>
+#include <utils/fileutils.h>
+#include <utils/qtcassert.h>
+
#include <QStackedWidget>
#include <QToolButton>
#include <QSpinBox>
@@ -52,7 +55,6 @@
#include <QHBoxLayout>
#include <QToolBar>
#include <QComboBox>
-#include <QFileInfo>
#include <QDir>
#include <QTextCodec>
#include <QTextBlock>
@@ -79,7 +81,7 @@ public:
virtual QSize sizeHint() const;
signals:
- void expandBranchesRequested();
+ void requestBranchList();
protected:
void mouseMoveEvent(QMouseEvent *e);
@@ -194,7 +196,7 @@ void DescriptionEditorWidget::handleCurrentContents()
m_currentCursor.select(QTextCursor::LineUnderCursor);
m_currentCursor.removeSelectedText();
m_currentCursor.insertText(QLatin1String("Branches: Expanding..."));
- emit expandBranchesRequested();
+ emit requestBranchList();
}
} // namespace Internal
@@ -208,7 +210,6 @@ DiffEditor::DiffEditor(const QSharedPointer<DiffEditorDocument> &doc)
, m_sideBySideEditor(0)
, m_unifiedEditor(0)
, m_currentEditor(0)
- , m_controller(0)
, m_guiController(0)
, m_toolBar(0)
, m_entriesComboBox(0)
@@ -216,6 +217,8 @@ DiffEditor::DiffEditor(const QSharedPointer<DiffEditorDocument> &doc)
, m_reloadAction(0)
, m_diffEditorSwitcher(0)
{
+ QTC_ASSERT(m_document, return);
+
QSplitter *splitter = new Core::MiniSplitter(Qt::Vertical);
m_descriptionWidget = new Internal::DescriptionEditorWidget(splitter);
@@ -233,26 +236,25 @@ DiffEditor::DiffEditor(const QSharedPointer<DiffEditorDocument> &doc)
setWidget(splitter);
- connect(m_descriptionWidget, SIGNAL(expandBranchesRequested()),
- m_document->controller(), SLOT(expandBranchesRequested()));
-
- m_controller = m_document->controller();
- m_guiController = new DiffEditorGuiController(m_controller, this);
-
- connect(m_controller, SIGNAL(cleared(QString)),
- this, SLOT(slotCleared(QString)));
- connect(m_controller, SIGNAL(diffFilesChanged(QList<FileData>,QString)),
- this, SLOT(slotDiffFilesChanged(QList<FileData>,QString)));
- connect(m_controller, SIGNAL(descriptionChanged(QString)),
- this, SLOT(slotDescriptionChanged(QString)));
- connect(m_controller, SIGNAL(descriptionEnablementChanged(bool)),
- this, SLOT(slotDescriptionVisibilityChanged()));
- connect(m_guiController, SIGNAL(descriptionVisibilityChanged(bool)),
- this, SLOT(slotDescriptionVisibilityChanged()));
- connect(m_guiController, SIGNAL(currentDiffFileIndexChanged(int)),
- this, SLOT(activateEntry(int)));
-
- slotDescriptionChanged(m_controller->description());
+
+ DiffEditorController *control = controller();
+ m_guiController = new DiffEditorGuiController(control, this);
+
+ connect(m_descriptionWidget, &Internal::DescriptionEditorWidget::requestBranchList,
+ control, &DiffEditorController::expandBranchesRequested);
+ connect(control, &DiffEditorController::cleared, this, &DiffEditor::slotCleared);
+ connect(control, &DiffEditorController::diffFilesChanged,
+ this, &DiffEditor::slotDiffFilesChanged);
+ connect(control, &DiffEditorController::descriptionChanged,
+ this, &DiffEditor::slotDescriptionChanged);
+ connect(control, &DiffEditorController::descriptionEnablementChanged,
+ this, &DiffEditor::slotDescriptionVisibilityChanged);
+ connect(m_guiController, &DiffEditorGuiController::descriptionVisibilityChanged,
+ this, &DiffEditor::slotDescriptionVisibilityChanged);
+ connect(m_guiController, &DiffEditorGuiController::currentDiffFileIndexChanged,
+ this, &DiffEditor::activateEntry);
+
+ slotDescriptionChanged(control->description());
slotDescriptionVisibilityChanged();
showDiffEditor(readCurrentDiffEditorSetting());
@@ -263,8 +265,7 @@ DiffEditor::DiffEditor(const QSharedPointer<DiffEditorDocument> &doc)
DiffEditor::~DiffEditor()
{
delete m_toolBar;
- if (m_widget)
- delete m_widget;
+ delete m_widget;
}
Core::IEditor *DiffEditor::duplicate()
@@ -277,10 +278,6 @@ bool DiffEditor::open(QString *errorString,
const QString &realFileName)
{
Q_UNUSED(realFileName)
-
- if (!m_document)
- return false;
-
return m_document->open(errorString, fileName);
}
@@ -305,6 +302,8 @@ QWidget *DiffEditor::toolBar()
if (m_toolBar)
return m_toolBar;
+ DiffEditorController *control = controller();
+
// Create
m_toolBar = createToolBar(m_sideBySideEditor);
@@ -314,14 +313,14 @@ QWidget *DiffEditor::toolBar()
QSizePolicy policy = m_entriesComboBox->sizePolicy();
policy.setHorizontalPolicy(QSizePolicy::Expanding);
m_entriesComboBox->setSizePolicy(policy);
- connect(m_entriesComboBox, SIGNAL(activated(int)),
- this, SLOT(entryActivated(int)));
+ connect(m_entriesComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
+ this, &DiffEditor::entryActivated);
m_toolBar->addWidget(m_entriesComboBox);
QToolButton *whitespaceButton = new QToolButton(m_toolBar);
whitespaceButton->setText(tr("Ignore Whitespace"));
whitespaceButton->setCheckable(true);
- whitespaceButton->setChecked(m_controller->isIgnoreWhitespace());
+ whitespaceButton->setChecked(control->isIgnoreWhitespace());
m_whitespaceButtonAction = m_toolBar->addWidget(whitespaceButton);
QLabel *contextLabel = new QLabel(m_toolBar);
@@ -331,7 +330,7 @@ QWidget *DiffEditor::toolBar()
QSpinBox *contextSpinBox = new QSpinBox(m_toolBar);
contextSpinBox->setRange(1, 100);
- contextSpinBox->setValue(m_controller->contextLinesNumber());
+ contextSpinBox->setValue(control->contextLinesNumber());
contextSpinBox->setFrame(false);
contextSpinBox->setSizePolicy(QSizePolicy::Minimum,
QSizePolicy::Expanding); // Mac Qt5
@@ -349,7 +348,7 @@ QWidget *DiffEditor::toolBar()
reloadButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_RELOAD_GRAY)));
reloadButton->setToolTip(tr("Reload Editor"));
m_reloadAction = m_toolBar->addWidget(reloadButton);
- slotReloaderChanged(m_controller->reloader());
+ slotReloaderChanged();
QToolButton *toggleSync = new QToolButton(m_toolBar);
toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
@@ -362,31 +361,33 @@ QWidget *DiffEditor::toolBar()
m_toolBar->addWidget(m_diffEditorSwitcher);
updateDiffEditorSwitcher();
- connect(whitespaceButton, SIGNAL(clicked(bool)),
- m_controller, SLOT(setIgnoreWhitespace(bool)));
- connect(m_controller, SIGNAL(ignoreWhitespaceChanged(bool)),
- whitespaceButton, SLOT(setChecked(bool)));
- connect(contextSpinBox, SIGNAL(valueChanged(int)),
- m_controller, SLOT(setContextLinesNumber(int)));
- connect(m_controller, SIGNAL(contextLinesNumberChanged(int)),
- contextSpinBox, SLOT(setValue(int)));
- connect(toggleSync, SIGNAL(clicked(bool)),
- m_guiController, SLOT(setHorizontalScrollBarSynchronization(bool)));
- connect(toggleDescription, SIGNAL(clicked(bool)),
- m_guiController, SLOT(setDescriptionVisible(bool)));
- connect(m_diffEditorSwitcher, SIGNAL(clicked()),
- this, SLOT(slotDiffEditorSwitched()));
- connect(reloadButton, SIGNAL(clicked()),
- m_controller, SLOT(requestReload()));
- connect(m_controller, SIGNAL(reloaderChanged(DiffEditorReloader*)),
- this, SLOT(slotReloaderChanged(DiffEditorReloader*)));
+ connect(whitespaceButton, &QToolButton::clicked,
+ control, &DiffEditorController::setIgnoreWhitespace);
+ connect(control, &DiffEditorController::ignoreWhitespaceChanged,
+ whitespaceButton, &QToolButton::setChecked);
+ connect(contextSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
+ control, &DiffEditorController::setContextLinesNumber);
+ connect(control, &DiffEditorController::contextLinesNumberChanged,
+ contextSpinBox, &QSpinBox::setValue);
+ connect(toggleSync, &QAbstractButton::clicked,
+ m_guiController, &DiffEditorGuiController::setHorizontalScrollBarSynchronization);
+ connect(toggleDescription, &QAbstractButton::clicked,
+ m_guiController, &DiffEditorGuiController::setDescriptionVisible);
+ connect(m_diffEditorSwitcher, &QAbstractButton::clicked,
+ this, &DiffEditor::slotDiffEditorSwitched);
+ connect(reloadButton, &QAbstractButton::clicked,
+ control, &DiffEditorController::requestReload);
+ connect(control, &DiffEditorController::reloaderChanged,
+ this, &DiffEditor::slotReloaderChanged);
+ connect(control, &DiffEditorController::contextLinesNumberEnablementChanged,
+ this, &DiffEditor::slotReloaderChanged);
return m_toolBar;
}
DiffEditorController *DiffEditor::controller() const
{
- return m_controller;
+ return m_document->controller();
}
void DiffEditor::updateEntryToolTip()
@@ -420,8 +421,8 @@ void DiffEditor::slotDiffFilesChanged(const QList<FileData> &diffFileList,
for (int i = 0; i < count; i++) {
const DiffFileInfo leftEntry = diffFileList.at(i).leftFileInfo;
const DiffFileInfo rightEntry = diffFileList.at(i).rightFileInfo;
- const QString leftShortFileName = QFileInfo(leftEntry.fileName).fileName();
- const QString rightShortFileName = QFileInfo(rightEntry.fileName).fileName();
+ const QString leftShortFileName = Utils::FileName::fromString(leftEntry.fileName).fileName();
+ const QString rightShortFileName = Utils::FileName::fromString(rightEntry.fileName).fileName();
QString itemText;
QString itemToolTip;
if (leftEntry.fileName == rightEntry.fileName) {
@@ -478,7 +479,7 @@ void DiffEditor::slotDescriptionChanged(const QString &description)
void DiffEditor::slotDescriptionVisibilityChanged()
{
- const bool enabled = m_controller->isDescriptionEnabled();
+ const bool enabled = controller()->isDescriptionEnabled();
const bool visible = m_guiController->isDescriptionVisible();
m_descriptionWidget->setVisible(visible && enabled);
@@ -495,11 +496,15 @@ void DiffEditor::slotDescriptionVisibilityChanged()
m_toggleDescriptionAction->setVisible(enabled);
}
-void DiffEditor::slotReloaderChanged(DiffEditorReloader *reloader)
+void DiffEditor::slotReloaderChanged()
{
+ DiffEditorController *control = controller();
+ const DiffEditorReloader *reloader = control->reloader();
+ const bool contextVisible = control->isContextLinesNumberEnabled();
+
m_whitespaceButtonAction->setVisible(reloader);
- m_contextLabelAction->setVisible(reloader);
- m_contextSpinBoxAction->setVisible(reloader);
+ m_contextLabelAction->setVisible(reloader && contextVisible);
+ m_contextSpinBoxAction->setVisible(reloader && contextVisible);
m_reloadAction->setVisible(reloader);
}
diff --git a/src/plugins/diffeditor/diffeditor.h b/src/plugins/diffeditor/diffeditor.h
index 8825f225ba2..417fb121787 100644
--- a/src/plugins/diffeditor/diffeditor.h
+++ b/src/plugins/diffeditor/diffeditor.h
@@ -48,6 +48,8 @@ namespace TextEditor { class TextEditorWidget; }
namespace DiffEditor {
+namespace Internal { class DescriptionEditorWidget; }
+
class DiffEditorDocument;
class DiffEditorGuiController;
class SideBySideDiffEditorWidget;
@@ -83,7 +85,7 @@ private slots:
void entryActivated(int index);
void slotDescriptionChanged(const QString &description);
void slotDescriptionVisibilityChanged();
- void slotReloaderChanged(DiffEditorReloader *reloader);
+ void slotReloaderChanged();
void slotDiffEditorSwitched();
private:
@@ -95,12 +97,11 @@ private:
void writeCurrentDiffEditorSetting(QWidget *currentEditor);
QSharedPointer<DiffEditorDocument> m_document;
- TextEditor::TextEditorWidget *m_descriptionWidget;
+ Internal::DescriptionEditorWidget *m_descriptionWidget;
QStackedWidget *m_stackedWidget;
SideBySideDiffEditorWidget *m_sideBySideEditor;
UnifiedDiffEditorWidget *m_unifiedEditor;
QWidget *m_currentEditor;
- DiffEditorController *m_controller;
DiffEditorGuiController *m_guiController;
QToolBar *m_toolBar;
QComboBox *m_entriesComboBox;
diff --git a/src/plugins/diffeditor/diffeditorcontroller.cpp b/src/plugins/diffeditor/diffeditorcontroller.cpp
index 3b972e2abbd..e4bab7fc74a 100644
--- a/src/plugins/diffeditor/diffeditorcontroller.cpp
+++ b/src/plugins/diffeditor/diffeditorcontroller.cpp
@@ -44,12 +44,13 @@ namespace DiffEditor {
DiffEditorController::DiffEditorController(QObject *parent)
: QObject(parent),
+ m_reloader(0),
+ m_contextLinesNumber(3),
m_diffFileIndex(-1),
m_chunkIndex(-1),
m_descriptionEnabled(false),
- m_contextLinesNumber(3),
- m_ignoreWhitespace(true),
- m_reloader(0)
+ m_contextLinesNumberEnabled(true),
+ m_ignoreWhitespace(true)
{
QSettings *s = Core::ICore::settings();
s->beginGroup(QLatin1String(settingsGroupC));
@@ -97,6 +98,11 @@ int DiffEditorController::contextLinesNumber() const
return m_contextLinesNumber;
}
+bool DiffEditorController::isContextLinesNumberEnabled() const
+{
+ return m_contextLinesNumberEnabled;
+}
+
bool DiffEditorController::isIgnoreWhitespace() const
{
return m_ignoreWhitespace;
@@ -188,7 +194,7 @@ void DiffEditorController::setReloader(DiffEditorReloader *reloader)
if (m_reloader)
m_reloader->setController(this);
- emit reloaderChanged(m_reloader);
+ emit reloaderChanged();
}
void DiffEditorController::clear()
@@ -218,10 +224,6 @@ void DiffEditorController::setDescription(const QString &description)
return;
m_description = description;
- // Empty line before headers and commit message
- const int emptyLine = m_description.indexOf(QLatin1String("\n\n"));
- if (emptyLine != -1)
- m_description.insert(emptyLine, QLatin1Char('\n') + QLatin1String(Constants::EXPAND_BRANCHES));
emit descriptionChanged(m_description);
}
@@ -244,7 +246,7 @@ void DiffEditorController::branchesForCommitReceived(const QString &output)
void DiffEditorController::expandBranchesRequested()
{
- emit expandBranchesRequested(m_description.mid(7, 8));
+ emit requestBranchList(m_description.mid(7, 8));
}
QString DiffEditorController::prepareBranchesForCommit(const QString &output)
@@ -288,6 +290,15 @@ void DiffEditorController::setContextLinesNumber(int lines)
emit contextLinesNumberChanged(l);
}
+void DiffEditorController::setContextLinesNumberEnabled(bool on)
+{
+ if (m_contextLinesNumberEnabled == on)
+ return;
+
+ m_contextLinesNumberEnabled = on;
+ emit contextLinesNumberEnablementChanged(on);
+}
+
void DiffEditorController::setIgnoreWhitespace(bool ignore)
{
if (m_ignoreWhitespace == ignore)
diff --git a/src/plugins/diffeditor/diffeditorcontroller.h b/src/plugins/diffeditor/diffeditorcontroller.h
index 3bc154f5314..08d4036ab4e 100644
--- a/src/plugins/diffeditor/diffeditorcontroller.h
+++ b/src/plugins/diffeditor/diffeditorcontroller.h
@@ -54,6 +54,7 @@ public:
QString description() const;
bool isDescriptionEnabled() const;
int contextLinesNumber() const;
+ bool isContextLinesNumberEnabled() const;
bool isIgnoreWhitespace() const;
QString makePatch(bool revert, bool addPrefix = false) const;
@@ -70,6 +71,7 @@ public slots:
void setDescription(const QString &description);
void setDescriptionEnabled(bool on);
void setContextLinesNumber(int lines);
+ void setContextLinesNumberEnabled(bool on);
void setIgnoreWhitespace(bool ignore);
void requestReload();
void requestChunkActions(QMenu *menu,
@@ -87,26 +89,28 @@ signals:
void descriptionChanged(const QString &description);
void descriptionEnablementChanged(bool on);
void contextLinesNumberChanged(int lines);
+ void contextLinesNumberEnablementChanged(bool on);
void ignoreWhitespaceChanged(bool ignore);
void chunkActionsRequested(QMenu *menu, bool isValid);
void saveStateRequested();
void restoreStateRequested();
- void expandBranchesRequested(const QString &revision);
- void reloaderChanged(DiffEditorReloader *reloader);
+ void requestBranchList(const QString &revision);
+ void reloaderChanged();
private:
QString prepareBranchesForCommit(const QString &output);
QString m_clearMessage;
QList<FileData> m_diffFiles;
- int m_diffFileIndex;
- int m_chunkIndex;
QString m_workingDirectory;
QString m_description;
- bool m_descriptionEnabled;
+ DiffEditorReloader *m_reloader;
int m_contextLinesNumber;
+ int m_diffFileIndex;
+ int m_chunkIndex;
+ bool m_descriptionEnabled;
+ bool m_contextLinesNumberEnabled;
bool m_ignoreWhitespace;
- DiffEditorReloader *m_reloader;
};
} // namespace DiffEditor
diff --git a/src/plugins/diffeditor/diffeditordocument.cpp b/src/plugins/diffeditor/diffeditordocument.cpp
index 5eda014c7f0..3119925cc19 100644
--- a/src/plugins/diffeditor/diffeditordocument.cpp
+++ b/src/plugins/diffeditor/diffeditordocument.cpp
@@ -53,10 +53,6 @@ DiffEditorDocument::DiffEditorDocument() :
setTemporary(true);
}
-DiffEditorDocument::~DiffEditorDocument()
-{
-}
-
DiffEditorController *DiffEditorDocument::controller() const
{
return m_controller;
@@ -90,7 +86,7 @@ bool DiffEditorDocument::save(QString *errorString, const QString &fileName, boo
DiffEditorManager::removeDocument(this);
const QFileInfo fi(fileName);
setTemporary(false);
- setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
+ setFilePath(Utils::FileName::fromString(fi.absoluteFilePath()));
setDisplayName(QString());
return true;
}
@@ -100,7 +96,7 @@ bool DiffEditorDocument::reload(QString *errorString, ReloadFlag flag, ChangeTyp
Q_UNUSED(type)
if (flag == FlagIgnore)
return true;
- return open(errorString, filePath());
+ return open(errorString, filePath().toString());
}
bool DiffEditorDocument::open(QString *errorString, const QString &fileName)
@@ -120,7 +116,7 @@ bool DiffEditorDocument::open(QString *errorString, const QString &fileName)
const QFileInfo fi(fileName);
setTemporary(false);
- setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
+ setFilePath(Utils::FileName::fromString(fi.absoluteFilePath()));
m_controller->setDiffFiles(fileDataList, fi.absolutePath());
return true;
}
diff --git a/src/plugins/diffeditor/diffeditordocument.h b/src/plugins/diffeditor/diffeditordocument.h
index 23b7f93c2d6..e5f4ccd7576 100644
--- a/src/plugins/diffeditor/diffeditordocument.h
+++ b/src/plugins/diffeditor/diffeditordocument.h
@@ -44,8 +44,7 @@ class DIFFEDITOR_EXPORT DiffEditorDocument : public Core::BaseTextDocument
Q_OBJECT
Q_PROPERTY(QString plainText READ plainText STORED false) // For access by code pasters
public:
- explicit DiffEditorDocument();
- virtual ~DiffEditorDocument();
+ DiffEditorDocument();
DiffEditorController *controller() const;
@@ -62,7 +61,7 @@ public:
QString plainText() const;
private:
- DiffEditorController *m_controller;
+ DiffEditorController *const m_controller;
};
} // namespace DiffEditor
diff --git a/src/plugins/diffeditor/diffeditorguicontroller.cpp b/src/plugins/diffeditor/diffeditorguicontroller.cpp
index f955806b4ad..c32ded2eb57 100644
--- a/src/plugins/diffeditor/diffeditorguicontroller.cpp
+++ b/src/plugins/diffeditor/diffeditorguicontroller.cpp
@@ -33,6 +33,8 @@
#include <coreplugin/icore.h>
+#include <utils/qtcassert.h>
+
static const char settingsGroupC[] = "DiffEditor";
static const char descriptionVisibleKeyC[] = "DescriptionVisible";
static const char horizontalScrollBarSynchronizationKeyC[] =
@@ -49,6 +51,7 @@ DiffEditorGuiController::DiffEditorGuiController(
m_syncScrollBars(true),
m_currentDiffFileIndex(-1)
{
+ QTC_ASSERT(m_controller, return);
QSettings *s = Core::ICore::settings();
s->beginGroup(QLatin1String(settingsGroupC));
m_descriptionVisible = s->value(QLatin1String(descriptionVisibleKeyC),
@@ -57,18 +60,13 @@ DiffEditorGuiController::DiffEditorGuiController(
m_syncScrollBars).toBool();
s->endGroup();
- connect(m_controller, SIGNAL(cleared(QString)),
- this, SLOT(slotUpdateDiffFileIndex()));
- connect(m_controller, SIGNAL(diffFilesChanged(QList<FileData>,QString)),
- this, SLOT(slotUpdateDiffFileIndex()));
+ connect(m_controller, &DiffEditorController::cleared, this,
+ &DiffEditorGuiController::slotUpdateDiffFileIndex);
+ connect(m_controller, &DiffEditorController::diffFilesChanged, this,
+ &DiffEditorGuiController::slotUpdateDiffFileIndex);
slotUpdateDiffFileIndex();
}
-DiffEditorGuiController::~DiffEditorGuiController()
-{
-
-}
-
DiffEditorController *DiffEditorGuiController::controller() const
{
return m_controller;
diff --git a/src/plugins/diffeditor/diffeditorguicontroller.h b/src/plugins/diffeditor/diffeditorguicontroller.h
index ae563d9b488..e5d155059bd 100644
--- a/src/plugins/diffeditor/diffeditorguicontroller.h
+++ b/src/plugins/diffeditor/diffeditorguicontroller.h
@@ -45,7 +45,6 @@ class DIFFEDITOR_EXPORT DiffEditorGuiController : public QObject
public:
DiffEditorGuiController(DiffEditorController *controller,
QObject *parent = 0);
- ~DiffEditorGuiController();
DiffEditorController *controller() const;
@@ -67,7 +66,7 @@ private slots:
void slotUpdateDiffFileIndex();
private:
- DiffEditorController *m_controller;
+ DiffEditorController *const m_controller;
bool m_descriptionVisible;
bool m_syncScrollBars;
int m_currentDiffFileIndex;
diff --git a/src/plugins/diffeditor/diffeditormanager.cpp b/src/plugins/diffeditor/diffeditormanager.cpp
index df37b12cdfb..ce8b5c38346 100644
--- a/src/plugins/diffeditor/diffeditormanager.cpp
+++ b/src/plugins/diffeditor/diffeditormanager.cpp
@@ -48,8 +48,8 @@ DiffEditorManager::DiffEditorManager(QObject *parent)
m_instance = this;
Core::EditorManager *editorManager = Core::EditorManager::instance();
- connect(editorManager, SIGNAL(editorsClosed(QList<Core::IEditor*>)),
- this, SLOT(slotEditorsClosed(QList<Core::IEditor*>)));
+ connect(editorManager, &Core::EditorManager::editorsClosed,
+ this, &DiffEditorManager::slotEditorsClosed);
}
DiffEditorManager::~DiffEditorManager()
@@ -57,11 +57,6 @@ DiffEditorManager::~DiffEditorManager()
m_instance = 0;
}
-DiffEditorManager *DiffEditorManager::instance()
-{
- return m_instance;
-}
-
void DiffEditorManager::slotEditorsClosed(const QList<Core::IEditor *> &editors)
{
QMap<Core::IDocument *, int> editorsForDocument;
@@ -89,7 +84,7 @@ void DiffEditorManager::slotEditorsClosed(const QList<Core::IEditor *> &editors)
DiffEditorDocument *DiffEditorManager::find(const QString &documentId)
{
- return instance()->idToDocument.value(documentId);
+ return m_instance->idToDocument.value(documentId);
}
DiffEditorDocument *DiffEditorManager::findOrCreate(const QString &documentId, const QString &displayName)
@@ -109,19 +104,19 @@ DiffEditorDocument *DiffEditorManager::findOrCreate(const QString &documentId, c
document->setDisplayName(displayName);
- instance()->idToDocument.insert(documentId, document);
- instance()->documentToId.insert(document, documentId);
+ m_instance->idToDocument.insert(documentId, document);
+ m_instance->documentToId.insert(document, documentId);
return document;
}
void DiffEditorManager::removeDocument(DiffEditorDocument *document)
{
- if (!instance()->documentToId.contains(document))
+ if (!m_instance->documentToId.contains(document))
return;
- const QString documentId = instance()->documentToId.value(document);
- instance()->documentToId.remove(document);
- instance()->idToDocument.remove(documentId);
+ const QString documentId = m_instance->documentToId.value(document);
+ m_instance->documentToId.remove(document);
+ m_instance->idToDocument.remove(documentId);
}
diff --git a/src/plugins/diffeditor/diffeditormanager.h b/src/plugins/diffeditor/diffeditormanager.h
index 35f49fc5ade..3fc7f34c34f 100644
--- a/src/plugins/diffeditor/diffeditormanager.h
+++ b/src/plugins/diffeditor/diffeditormanager.h
@@ -49,8 +49,6 @@ public:
explicit DiffEditorManager(QObject *parent);
virtual ~DiffEditorManager();
- static DiffEditorManager *instance();
-
static DiffEditorDocument *find(const QString &documentId);
static DiffEditorDocument *findOrCreate(const QString &documentId, const QString &displayName);
static void removeDocument(DiffEditorDocument *document);
diff --git a/src/plugins/diffeditor/diffeditorplugin.cpp b/src/plugins/diffeditor/diffeditorplugin.cpp
index 36ad3cd15ee..c53e1729d1e 100644
--- a/src/plugins/diffeditor/diffeditorplugin.cpp
+++ b/src/plugins/diffeditor/diffeditorplugin.cpp
@@ -163,7 +163,7 @@ bool DiffEditorPlugin::initialize(const QStringList &arguments, QString *errorMe
QAction *diffAction = new QAction(tr("Diff..."), this);
Core::Command *diffCommand = Core::ActionManager::registerAction(diffAction,
"DiffEditor.Diff", globalcontext);
- connect(diffAction, SIGNAL(triggered()), this, SLOT(diff()));
+ connect(diffAction, &QAction::triggered, this, &DiffEditorPlugin::diff);
toolsContainer->addAction(diffCommand, Constants::G_TOOLS_DIFF);
addAutoReleasedObject(new DiffEditorFactory(this));
@@ -893,6 +893,66 @@ void DiffEditor::Internal::DiffEditorPlugin::testReadPatch_data()
fileDataList7 << fileData1;
QTest::newRow("Dirty submodule") << patch
<< fileDataList7;
+
+ //////////////
+
+ // Subversion New
+ patch = _("Index: src/plugins/subversion/subversioneditor.cpp\n"
+ "===================================================================\n"
+ "--- src/plugins/subversion/subversioneditor.cpp\t(revision 0)\n"
+ "+++ src/plugins/subversion/subversioneditor.cpp\t(revision 0)\n"
+ "@@ -0,0 +125 @@\n\n");
+ fileData1 = FileData();
+ fileData1.leftFileInfo = DiffFileInfo(_("src/plugins/subversion/subversioneditor.cpp"));
+ fileData1.rightFileInfo = DiffFileInfo(_("src/plugins/subversion/subversioneditor.cpp"));
+ chunkData1 = ChunkData();
+ chunkData1.leftStartingLineNumber = -1;
+ chunkData1.rightStartingLineNumber = 124;
+ fileData1.chunks << chunkData1;
+ QList<FileData> fileDataList8;
+ fileDataList8 << fileData1;
+ QTest::newRow("Subversion New") << patch
+ << fileDataList8;
+
+ //////////////
+
+ // Subversion Deleted
+ patch = _("Index: src/plugins/subversion/subversioneditor.cpp\n"
+ "===================================================================\n"
+ "--- src/plugins/subversion/subversioneditor.cpp\t(revision 42)\n"
+ "+++ src/plugins/subversion/subversioneditor.cpp\t(working copy)\n"
+ "@@ -1,125 +0,0 @@\n\n");
+ fileData1 = FileData();
+ fileData1.leftFileInfo = DiffFileInfo(_("src/plugins/subversion/subversioneditor.cpp"));
+ fileData1.rightFileInfo = DiffFileInfo(_("src/plugins/subversion/subversioneditor.cpp"));
+ chunkData1 = ChunkData();
+ chunkData1.leftStartingLineNumber = 0;
+ chunkData1.rightStartingLineNumber = -1;
+ fileData1.chunks << chunkData1;
+ QList<FileData> fileDataList9;
+ fileDataList9 << fileData1;
+ QTest::newRow("Subversion Deleted") << patch
+ << fileDataList9;
+
+ //////////////
+
+ // Subversion Normal
+ patch = _("Index: src/plugins/subversion/subversioneditor.cpp\n"
+ "===================================================================\n"
+ "--- src/plugins/subversion/subversioneditor.cpp\t(revision 42)\n"
+ "+++ src/plugins/subversion/subversioneditor.cpp\t(working copy)\n"
+ "@@ -120,7 +120,7 @@\n\n");
+ fileData1 = FileData();
+ fileData1.leftFileInfo = DiffFileInfo(_("src/plugins/subversion/subversioneditor.cpp"));
+ fileData1.rightFileInfo = DiffFileInfo(_("src/plugins/subversion/subversioneditor.cpp"));
+ chunkData1 = ChunkData();
+ chunkData1.leftStartingLineNumber = 119;
+ chunkData1.rightStartingLineNumber = 119;
+ fileData1.chunks << chunkData1;
+ QList<FileData> fileDataList10;
+ fileDataList10 << fileData1;
+ QTest::newRow("Subversion Normal") << patch
+ << fileDataList10;
}
void DiffEditor::Internal::DiffEditorPlugin::testReadPatch()
diff --git a/src/plugins/diffeditor/diffeditorreloader.cpp b/src/plugins/diffeditor/diffeditorreloader.cpp
index 4d812547c1f..9ae58051dda 100644
--- a/src/plugins/diffeditor/diffeditorreloader.cpp
+++ b/src/plugins/diffeditor/diffeditorreloader.cpp
@@ -64,10 +64,10 @@ void DiffEditorReloader::setController(DiffEditorController *controller)
m_controller = controller;
if (m_controller) {
- connect(m_controller, SIGNAL(ignoreWhitespaceChanged(bool)),
- this, SLOT(requestReload()));
- connect(m_controller, SIGNAL(contextLinesNumberChanged(int)),
- this, SLOT(requestReload()));
+ connect(m_controller, &DiffEditorController::ignoreWhitespaceChanged,
+ this, &DiffEditorReloader::requestReload);
+ connect(m_controller, &DiffEditorController::contextLinesNumberChanged,
+ this, &DiffEditorReloader::requestReload);
}
}
diff --git a/src/plugins/diffeditor/diffutils.cpp b/src/plugins/diffeditor/diffutils.cpp
index 1d326040efa..d464e230b09 100644
--- a/src/plugins/diffeditor/diffutils.cpp
+++ b/src/plugins/diffeditor/diffutils.cpp
@@ -545,8 +545,11 @@ static QList<RowData> readLines(const QString &patch,
int i;
for (i = 0; i < lines.count(); i++) {
const QString line = lines.at(i);
- if (line.isEmpty())
- break; // need to have at least one character (1 column)
+ if (line.isEmpty()) { // need to have at least one character (1 column)
+ if (lastChunk)
+ i = lines.count(); // pretend as we've read all the lines (we just ignore the rest)
+ break;
+ }
QChar firstCharacter = line.at(0);
if (firstCharacter == QLatin1Char('\\')) { // no new line marker
if (!lastChunk) // can only appear in last chunk of the file
@@ -572,14 +575,17 @@ static QList<RowData> readLines(const QString &patch,
}
} else {
Diff::Command command = Diff::Equal;
- if (firstCharacter == QLatin1Char(' ')) // common line
+ if (firstCharacter == QLatin1Char(' ')) { // common line
command = Diff::Equal;
- else if (firstCharacter == QLatin1Char('-')) // deleted line
+ } else if (firstCharacter == QLatin1Char('-')) { // deleted line
command = Diff::Delete;
- else if (firstCharacter == QLatin1Char('+')) // inserted line
+ } else if (firstCharacter == QLatin1Char('+')) { // inserted line
command = Diff::Insert;
- else
- break; // no other character may exist as the first character
+ } else { // no other character may exist as the first character
+ if (lastChunk)
+ i = lines.count(); // pretend as we've read all the lines (we just ignore the rest)
+ break;
+ }
Diff diffToBeAdded(command, line.mid(1) + newLine);
diff --git a/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp b/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp
index 241ed5b086f..108cc0080cd 100644
--- a/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp
+++ b/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp
@@ -61,7 +61,6 @@
#include <extensionsystem/pluginmanager.h>
-#include <utils/tooltip/tipcontents.h>
#include <utils/tooltip/tooltip.h>
//static const int FILE_LEVEL = 1;
@@ -82,7 +81,7 @@ public:
MultiHighlighter(SideDiffEditorWidget *editor, QTextDocument *document = 0);
~MultiHighlighter();
- virtual void setFontSettings(const TextEditor::FontSettings &fontSettings);
+ virtual void setFontSettings(const FontSettings &fontSettings);
void setDocuments(const QList<QPair<DiffFileInfo, QString> > &documents);
protected:
@@ -198,7 +197,7 @@ MultiHighlighter::MultiHighlighter(SideDiffEditorWidget *editor, QTextDocument *
m_editor(editor)
{
const QList<HighlighterFactory *> &factories =
- ExtensionSystem::PluginManager::getObjects<TextEditor::HighlighterFactory>();
+ ExtensionSystem::PluginManager::getObjects<HighlighterFactory>();
foreach (HighlighterFactory *factory, factories) {
QStringList mimeTypes = factory->mimeTypes();
foreach (const QString &mimeType, mimeTypes)
@@ -211,7 +210,7 @@ MultiHighlighter::~MultiHighlighter()
setDocuments(QList<QPair<DiffFileInfo, QString> >());
}
-void MultiHighlighter::setFontSettings(const TextEditor::FontSettings &fontSettings)
+void MultiHighlighter::setFontSettings(const FontSettings &fontSettings)
{
foreach (SyntaxHighlighter *highlighter, m_highlighters) {
if (highlighter) {
@@ -298,7 +297,7 @@ SideDiffEditorWidget::SideDiffEditorWidget(QWidget *parent)
int block = document()->findBlock(position).blockNumber();
auto it = m_fileInfo.constFind(block);
if (it != m_fileInfo.constEnd())
- ToolTip::show(point, TextContent(it.value().fileName), this);
+ ToolTip::show(point, it.value().fileName, this);
else
ToolTip::hide();
});
@@ -336,7 +335,7 @@ void SideDiffEditorWidget::setDisplaySettings(const DisplaySettings &ds)
void SideDiffEditorWidget::applyFontSettings()
{
SelectableTextEditorWidget::applyFontSettings();
- const TextEditor::FontSettings &fs = textDocument()->fontSettings();
+ const FontSettings &fs = textDocument()->fontSettings();
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();
@@ -363,7 +362,7 @@ bool SideDiffEditorWidget::selectionVisible(int blockNumber) const
bool SideDiffEditorWidget::replacementVisible(int blockNumber) const
{
return isChunkLine(blockNumber) || (isFileLine(blockNumber)
- && TextEditor::TextDocumentLayout::isFolded(
+ && TextDocumentLayout::isFolded(
document()->findBlockByNumber(blockNumber)));
}
@@ -531,7 +530,7 @@ void SideDiffEditorWidget::paintSeparator(QPainter &painter,
const int replacementTextWidth = fontMetrics().width(replacementText) + 24;
int x = replacementTextWidth + offset.x();
if (x < document()->documentMargin()
- || !TextEditor::TextDocumentLayout::isFolded(block)) {
+ || !TextDocumentLayout::isFolded(block)) {
x = document()->documentMargin();
}
const QString elidedText = fontMetrics().elidedText(text,
@@ -569,7 +568,7 @@ void SideDiffEditorWidget::contextMenuEvent(QContextMenuEvent *e)
emit contextMenuRequested(menu, fileIndexForBlockNumber(blockNumber),
chunkIndexForBlockNumber(blockNumber));
- connect(this, SIGNAL(destroyed()), menu, SLOT(deleteLater()));
+ connect(this, &SideDiffEditorWidget::destroyed, menu.data(), &QMenu::deleteLater);
menu->exec(e->globalPos());
delete menu;
}
@@ -763,10 +762,10 @@ SideBySideDiffEditorWidget::SideBySideDiffEditorWidget(QWidget *parent)
m_leftEditor, &SideDiffEditorWidget::setDisplaySettings);
m_leftEditor->setDisplaySettings(TextEditorSettings::displaySettings());
m_leftEditor->setCodeStyle(TextEditorSettings::codeStyle());
- connect(m_leftEditor, SIGNAL(jumpToOriginalFileRequested(int,int,int)),
- this, SLOT(slotLeftJumpToOriginalFileRequested(int,int,int)));
- connect(m_leftEditor, SIGNAL(contextMenuRequested(QMenu*,int,int)),
- this, SLOT(slotLeftContextMenuRequested(QMenu*,int,int)),
+ connect(m_leftEditor, &SideDiffEditorWidget::jumpToOriginalFileRequested,
+ this, &SideBySideDiffEditorWidget::slotLeftJumpToOriginalFileRequested);
+ connect(m_leftEditor, &SideDiffEditorWidget::contextMenuRequested,
+ this, &SideBySideDiffEditorWidget::slotLeftContextMenuRequested,
Qt::DirectConnection);
m_rightEditor = new SideDiffEditorWidget(this);
@@ -775,48 +774,48 @@ SideBySideDiffEditorWidget::SideBySideDiffEditorWidget(QWidget *parent)
m_rightEditor, &SideDiffEditorWidget::setDisplaySettings);
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(m_rightEditor, SIGNAL(contextMenuRequested(QMenu*,int,int)),
- this, SLOT(slotRightContextMenuRequested(QMenu*,int,int)),
+ connect(m_rightEditor, &SideDiffEditorWidget::jumpToOriginalFileRequested,
+ this, &SideBySideDiffEditorWidget::slotRightJumpToOriginalFileRequested);
+ connect(m_rightEditor, &SideDiffEditorWidget::contextMenuRequested,
+ this, &SideBySideDiffEditorWidget::slotRightContextMenuRequested,
Qt::DirectConnection);
connect(TextEditorSettings::instance(),
- SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
- this, SLOT(setFontSettings(TextEditor::FontSettings)));
+ &TextEditorSettings::fontSettingsChanged,
+ this, &SideBySideDiffEditorWidget::setFontSettings);
setFontSettings(TextEditorSettings::fontSettings());
- connect(m_leftEditor->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(leftVSliderChanged()));
- connect(m_leftEditor->verticalScrollBar(), SIGNAL(actionTriggered(int)),
- this, SLOT(leftVSliderChanged()));
+ connect(m_leftEditor->verticalScrollBar(), &QAbstractSlider::valueChanged,
+ this, &SideBySideDiffEditorWidget::leftVSliderChanged);
+ connect(m_leftEditor->verticalScrollBar(), &QAbstractSlider::actionTriggered,
+ this, &SideBySideDiffEditorWidget::leftVSliderChanged);
- connect(m_leftEditor->horizontalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(leftHSliderChanged()));
- connect(m_leftEditor->horizontalScrollBar(), SIGNAL(actionTriggered(int)),
- this, SLOT(leftHSliderChanged()));
+ connect(m_leftEditor->horizontalScrollBar(), &QAbstractSlider::valueChanged,
+ this, &SideBySideDiffEditorWidget::leftHSliderChanged);
+ connect(m_leftEditor->horizontalScrollBar(), &QAbstractSlider::actionTriggered,
+ this, &SideBySideDiffEditorWidget::leftHSliderChanged);
- connect(m_leftEditor, SIGNAL(cursorPositionChanged()),
- this, SLOT(leftCursorPositionChanged()));
+ connect(m_leftEditor, &QPlainTextEdit::cursorPositionChanged,
+ this, &SideBySideDiffEditorWidget::leftCursorPositionChanged);
// connect(m_leftEditor->document()->documentLayout(), SIGNAL(documentSizeChanged(QSizeF)),
// this, SLOT(leftDocumentSizeChanged()));
- connect(m_rightEditor->verticalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(rightVSliderChanged()));
- connect(m_rightEditor->verticalScrollBar(), SIGNAL(actionTriggered(int)),
- this, SLOT(rightVSliderChanged()));
+ connect(m_rightEditor->verticalScrollBar(), &QAbstractSlider::valueChanged,
+ this, &SideBySideDiffEditorWidget::rightVSliderChanged);
+ connect(m_rightEditor->verticalScrollBar(), &QAbstractSlider::actionTriggered,
+ this, &SideBySideDiffEditorWidget::rightVSliderChanged);
- connect(m_rightEditor->horizontalScrollBar(), SIGNAL(valueChanged(int)),
- this, SLOT(rightHSliderChanged()));
- connect(m_rightEditor->horizontalScrollBar(), SIGNAL(actionTriggered(int)),
- this, SLOT(rightHSliderChanged()));
+ connect(m_rightEditor->horizontalScrollBar(), &QAbstractSlider::valueChanged,
+ this, &SideBySideDiffEditorWidget::rightHSliderChanged);
+ connect(m_rightEditor->horizontalScrollBar(), &QAbstractSlider::actionTriggered,
+ this, &SideBySideDiffEditorWidget::rightHSliderChanged);
- connect(m_rightEditor, SIGNAL(cursorPositionChanged()),
- this, SLOT(rightCursorPositionChanged()));
+ connect(m_rightEditor, &QPlainTextEdit::cursorPositionChanged,
+ this, &SideBySideDiffEditorWidget::rightCursorPositionChanged);
// connect(m_rightEditor->document()->documentLayout(), SIGNAL(documentSizeChanged(QSizeF)),
// this, SLOT(rightDocumentSizeChanged()));
- m_splitter = new Core::MiniSplitter(this);
+ m_splitter = new MiniSplitter(this);
m_splitter->addWidget(m_leftEditor);
m_splitter->addWidget(m_rightEditor);
QVBoxLayout *l = new QVBoxLayout(this);
@@ -827,11 +826,6 @@ SideBySideDiffEditorWidget::SideBySideDiffEditorWidget(QWidget *parent)
clear(tr("No controller"));
}
-SideBySideDiffEditorWidget::~SideBySideDiffEditorWidget()
-{
-
-}
-
void SideBySideDiffEditorWidget::setDiffEditorGuiController(
DiffEditorGuiController *controller)
{
@@ -839,21 +833,21 @@ void SideBySideDiffEditorWidget::setDiffEditorGuiController(
return;
if (m_guiController) {
- disconnect(m_controller, SIGNAL(cleared(QString)),
- this, SLOT(clearAll(QString)));
- disconnect(m_controller, SIGNAL(diffFilesChanged(QList<FileData>,QString)),
- this, SLOT(setDiff(QList<FileData>,QString)));
- disconnect(m_controller, SIGNAL(saveStateRequested()),
- m_leftEditor, SLOT(saveStateRequested()));
- disconnect(m_controller, SIGNAL(saveStateRequested()),
- m_rightEditor, SLOT(saveStateRequested()));
- disconnect(m_controller, SIGNAL(restoreStateRequested()),
- m_leftEditor, SLOT(restoreStateRequested()));
- disconnect(m_controller, SIGNAL(restoreStateRequested()),
- m_rightEditor, SLOT(restoreStateRequested()));
-
- disconnect(m_guiController, SIGNAL(currentDiffFileIndexChanged(int)),
- this, SLOT(setCurrentDiffFileIndex(int)));
+ disconnect(m_controller, &DiffEditorController::cleared,
+ this, &SideBySideDiffEditorWidget::clearAll);
+ disconnect(m_controller, &DiffEditorController::diffFilesChanged,
+ this, &SideBySideDiffEditorWidget::setDiff);
+ disconnect(m_controller, &DiffEditorController::saveStateRequested,
+ m_leftEditor, &SideDiffEditorWidget::saveStateRequested);
+ disconnect(m_controller, &DiffEditorController::saveStateRequested,
+ m_rightEditor, &SideDiffEditorWidget::saveStateRequested);
+ disconnect(m_controller, &DiffEditorController::restoreStateRequested,
+ m_leftEditor, &SideDiffEditorWidget::restoreStateRequested);
+ disconnect(m_controller, &DiffEditorController::restoreStateRequested,
+ m_rightEditor, &SideDiffEditorWidget::restoreStateRequested);
+
+ disconnect(m_guiController, &DiffEditorGuiController::currentDiffFileIndexChanged,
+ this, &SideBySideDiffEditorWidget::setCurrentDiffFileIndex);
clearAll(tr("No controller"));
}
@@ -862,33 +856,27 @@ void SideBySideDiffEditorWidget::setDiffEditorGuiController(
if (m_guiController) {
m_controller = m_guiController->controller();
- connect(m_controller, SIGNAL(cleared(QString)),
- this, SLOT(clearAll(QString)));
- connect(m_controller, SIGNAL(diffFilesChanged(QList<FileData>,QString)),
- this, SLOT(setDiff(QList<FileData>,QString)));
- connect(m_controller, SIGNAL(saveStateRequested()),
- m_leftEditor, SLOT(saveStateRequested()));
- connect(m_controller, SIGNAL(saveStateRequested()),
- m_rightEditor, SLOT(saveStateRequested()));
- connect(m_controller, SIGNAL(restoreStateRequested()),
- m_leftEditor, SLOT(restoreStateRequested()));
- connect(m_controller, SIGNAL(restoreStateRequested()),
- m_rightEditor, SLOT(restoreStateRequested()));
-
- connect(m_guiController, SIGNAL(currentDiffFileIndexChanged(int)),
- this, SLOT(setCurrentDiffFileIndex(int)));
+ connect(m_controller, &DiffEditorController::cleared,
+ this, &SideBySideDiffEditorWidget::clearAll);
+ connect(m_controller, &DiffEditorController::diffFilesChanged,
+ this, &SideBySideDiffEditorWidget::setDiff);
+ connect(m_controller, &DiffEditorController::saveStateRequested,
+ m_leftEditor, &SideDiffEditorWidget::saveStateRequested);
+ connect(m_controller, &DiffEditorController::saveStateRequested,
+ m_rightEditor, &SideDiffEditorWidget::saveStateRequested);
+ connect(m_controller, &DiffEditorController::restoreStateRequested,
+ m_leftEditor, &SideDiffEditorWidget::restoreStateRequested);
+ connect(m_controller, &DiffEditorController::restoreStateRequested,
+ m_rightEditor, &SideDiffEditorWidget::restoreStateRequested);
+
+ connect(m_guiController, &DiffEditorGuiController::currentDiffFileIndexChanged,
+ this, &SideBySideDiffEditorWidget::setCurrentDiffFileIndex);
setDiff(m_controller->diffFiles(), m_controller->workingDirectory());
setCurrentDiffFileIndex(m_guiController->currentDiffFileIndex());
}
}
-
-DiffEditorGuiController *SideBySideDiffEditorWidget::diffEditorGuiController() const
-{
- return m_guiController;
-}
-
void SideBySideDiffEditorWidget::clear(const QString &message)
{
const bool oldIgnore = m_ignoreCurrentIndexChange;
@@ -1106,15 +1094,15 @@ void SideBySideDiffEditorWidget::showDiff()
for (int j = 0; j < contextFileData.chunks.count(); j++) {
ChunkData chunkData = contextFileData.chunks.at(j);
if (chunkData.contextChunk) {
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(leftBlock, FILE_LEVEL);
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(rightBlock, FILE_LEVEL);
+ BaseTextDocumentLayout::setFoldingIndent(leftBlock, FILE_LEVEL);
+ BaseTextDocumentLayout::setFoldingIndent(rightBlock, FILE_LEVEL);
leftBlock = leftBlock.next();
rightBlock = rightBlock.next();
}
const int indent = chunkData.contextChunk ? CHUNK_LEVEL : FILE_LEVEL;
for (int k = 0; k < chunkData.rows.count(); k++) {
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(leftBlock, indent);
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(rightBlock, indent);
+ BaseTextDocumentLayout::setFoldingIndent(leftBlock, indent);
+ BaseTextDocumentLayout::setFoldingIndent(rightBlock, indent);
leftBlock = leftBlock.next();
rightBlock = rightBlock.next();
}
@@ -1128,9 +1116,9 @@ void SideBySideDiffEditorWidget::showDiff()
ChunkData chunkData = contextFileData.chunks.at(j);
if (chunkData.contextChunk) {
QTextBlock leftBlock = m_leftEditor->document()->findBlockByNumber(blockNumber);
- TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(leftBlock, false);
+ BaseTextDocumentLayout::doFoldOrUnfold(leftBlock, false);
QTextBlock rightBlock = m_rightEditor->document()->findBlockByNumber(blockNumber);
- TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(rightBlock, false);
+ BaseTextDocumentLayout::doFoldOrUnfold(rightBlock, false);
blockNumber++;
}
blockNumber += chunkData.rows.count();
@@ -1154,7 +1142,7 @@ void SideBySideDiffEditorWidget::showDiff()
}
void SideBySideDiffEditorWidget::setFontSettings(
- const TextEditor::FontSettings &fontSettings)
+ const FontSettings &fontSettings)
{
m_spanLineFormat = fontSettings.toTextCharFormat(C_LINE_NUMBER);
m_fileLineFormat = fontSettings.toTextCharFormat(C_DIFF_FILE_LINE);
@@ -1228,7 +1216,7 @@ void SideBySideDiffEditorWidget::jumpToOriginalFile(const QString &fileName,
const QString absoluteFileName = dir.absoluteFilePath(fileName);
QFileInfo fi(absoluteFileName);
if (fi.exists() && !fi.isDir())
- Core::EditorManager::openEditorAt(absoluteFileName, lineNumber, columnNumber);
+ EditorManager::openEditorAt(absoluteFileName, lineNumber, columnNumber);
}
void SideBySideDiffEditorWidget::slotLeftContextMenuRequested(QMenu *menu,
@@ -1238,11 +1226,11 @@ void SideBySideDiffEditorWidget::slotLeftContextMenuRequested(QMenu *menu,
menu->addSeparator();
QAction *sendChunkToCodePasterAction =
menu->addAction(tr("Send Chunk to CodePaster..."));
- connect(sendChunkToCodePasterAction, SIGNAL(triggered()),
- this, SLOT(slotSendChunkToCodePaster()));
+ connect(sendChunkToCodePasterAction, &QAction::triggered,
+ this, &SideBySideDiffEditorWidget::slotSendChunkToCodePaster);
menu->addSeparator();
QAction *applyAction = menu->addAction(tr("Apply Chunk..."));
- connect(applyAction, SIGNAL(triggered()), this, SLOT(slotApplyChunk()));
+ connect(applyAction, &QAction::triggered, this, &SideBySideDiffEditorWidget::slotApplyChunk);
applyAction->setEnabled(false);
m_contextMenuFileIndex = diffFileIndex;
@@ -1273,11 +1261,11 @@ void SideBySideDiffEditorWidget::slotRightContextMenuRequested(QMenu *menu,
menu->addSeparator();
QAction *sendChunkToCodePasterAction =
menu->addAction(tr("Send Chunk to CodePaster..."));
- connect(sendChunkToCodePasterAction, SIGNAL(triggered()),
- this, SLOT(slotSendChunkToCodePaster()));
+ connect(sendChunkToCodePasterAction, &QAction::triggered,
+ this, &SideBySideDiffEditorWidget::slotSendChunkToCodePaster);
menu->addSeparator();
QAction *revertAction = menu->addAction(tr("Revert Chunk..."));
- connect(revertAction, SIGNAL(triggered()), this, SLOT(slotRevertChunk()));
+ connect(revertAction, &QAction::triggered, this, &SideBySideDiffEditorWidget::slotRevertChunk);
revertAction->setEnabled(false);
m_contextMenuFileIndex = diffFileIndex;
@@ -1382,7 +1370,7 @@ void SideBySideDiffEditorWidget::patch(bool revert)
if (patch.isEmpty())
return;
- if (PatchTool::runPatch(Core::EditorManager::defaultTextCodec()->fromUnicode(patch),
+ if (PatchTool::runPatch(EditorManager::defaultTextCodec()->fromUnicode(patch),
workingDirectory, strip, revert))
m_controller->requestReload();
}
@@ -1462,19 +1450,19 @@ void SideBySideDiffEditorWidget::rightDocumentSizeChanged()
synchronizeFoldings(m_rightEditor, m_leftEditor);
}
-/* Special version of that method (original: TextEditor::BaseTextDocumentLayout::doFoldOrUnfold())
+/* Special version of that method (original: BaseTextDocumentLayout::doFoldOrUnfold())
The hack lies in fact, that when unfolding all direct sub-blocks are made visible,
while some of them need to stay invisible (i.e. unfolded chunk lines)
*/
static void doFoldOrUnfold(SideDiffEditorWidget *editor, const QTextBlock &block, bool unfold)
{
- if (!TextEditor::BaseTextDocumentLayout::canFold(block))
+ if (!BaseTextDocumentLayout::canFold(block))
return;
QTextBlock b = block.next();
- int indent = TextEditor::BaseTextDocumentLayout::foldingIndent(block);
- while (b.isValid() && TextEditor::BaseTextDocumentLayout::foldingIndent(b) > indent && (unfold || b.next().isValid())) {
- if (unfold && editor->isChunkLine(b.blockNumber()) && !TextEditor::BaseTextDocumentLayout::isFolded(b)) {
+ int indent = BaseTextDocumentLayout::foldingIndent(block);
+ while (b.isValid() && BaseTextDocumentLayout::foldingIndent(b) > indent && (unfold || b.next().isValid())) {
+ if (unfold && editor->isChunkLine(b.blockNumber()) && !BaseTextDocumentLayout::isFolded(b)) {
b.setVisible(false);
b.setLineCount(0);
} else {
@@ -1482,17 +1470,17 @@ static void doFoldOrUnfold(SideDiffEditorWidget *editor, const QTextBlock &block
b.setLineCount(unfold ? qMax(1, b.layout()->lineCount()) : 0);
}
if (unfold) { // do not unfold folded sub-blocks
- if (TextEditor::BaseTextDocumentLayout::isFolded(b) && b.next().isValid()) {
- int jndent = TextEditor::BaseTextDocumentLayout::foldingIndent(b);
+ if (BaseTextDocumentLayout::isFolded(b) && b.next().isValid()) {
+ int jndent = BaseTextDocumentLayout::foldingIndent(b);
b = b.next();
- while (b.isValid() && TextEditor::BaseTextDocumentLayout::foldingIndent(b) > jndent)
+ while (b.isValid() && BaseTextDocumentLayout::foldingIndent(b) > jndent)
b = b.next();
continue;
}
}
b = b.next();
}
- TextEditor::BaseTextDocumentLayout::setFolded(block, !unfold);
+ BaseTextDocumentLayout::setFolded(block, !unfold);
}
void SideBySideDiffEditorWidget::synchronizeFoldings(SideDiffEditorWidget *source, SideDiffEditorWidget *destination)
@@ -1504,9 +1492,9 @@ void SideBySideDiffEditorWidget::synchronizeFoldings(SideDiffEditorWidget *sourc
QTextBlock sourceBlock = source->document()->firstBlock();
QTextBlock destinationBlock = destination->document()->firstBlock();
while (sourceBlock.isValid() && destinationBlock.isValid()) {
- if (TextEditor::BaseTextDocumentLayout::canFold(sourceBlock)) {
- const bool isSourceFolded = TextEditor::BaseTextDocumentLayout::isFolded(sourceBlock);
- const bool isDestinationFolded = TextEditor::BaseTextDocumentLayout::isFolded(destinationBlock);
+ if (BaseTextDocumentLayout::canFold(sourceBlock)) {
+ const bool isSourceFolded = BaseTextDocumentLayout::isFolded(sourceBlock);
+ const bool isDestinationFolded = BaseTextDocumentLayout::isFolded(destinationBlock);
if (isSourceFolded != isDestinationFolded) {
if (source->isFileLine(sourceBlock.blockNumber())) {
doFoldOrUnfold(source, sourceBlock, !isSourceFolded);
@@ -1518,9 +1506,9 @@ void SideBySideDiffEditorWidget::synchronizeFoldings(SideDiffEditorWidget *sourc
if (source->isChunkLine(previousSource.blockNumber())) {
QTextBlock firstVisibleDestinationBlock = destination->firstVisibleBlock();
QTextBlock firstDestinationBlock = destination->document()->firstBlock();
- TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(destinationBlock, !isSourceFolded);
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(sourceBlock, CHUNK_LEVEL);
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(destinationBlock, CHUNK_LEVEL);
+ BaseTextDocumentLayout::doFoldOrUnfold(destinationBlock, !isSourceFolded);
+ BaseTextDocumentLayout::setFoldingIndent(sourceBlock, CHUNK_LEVEL);
+ BaseTextDocumentLayout::setFoldingIndent(destinationBlock, CHUNK_LEVEL);
previousSource.setVisible(true);
previousSource.setLineCount(1);
previousDestination.setVisible(true);
@@ -1529,8 +1517,8 @@ void SideBySideDiffEditorWidget::synchronizeFoldings(SideDiffEditorWidget *sourc
sourceBlock.setLineCount(0);
destinationBlock.setVisible(false);
destinationBlock.setLineCount(0);
- TextEditor::BaseTextDocumentLayout::setFolded(previousSource, true);
- TextEditor::BaseTextDocumentLayout::setFolded(previousDestination, true);
+ BaseTextDocumentLayout::setFolded(previousSource, true);
+ BaseTextDocumentLayout::setFolded(previousDestination, true);
if (firstVisibleDestinationBlock == destinationBlock) {
/*
@@ -1553,15 +1541,15 @@ void SideBySideDiffEditorWidget::synchronizeFoldings(SideDiffEditorWidget *sourc
if (source->isChunkLine(sourceBlock.blockNumber())) {
QTextBlock nextSource = sourceBlock.next();
QTextBlock nextDestination = destinationBlock.next();
- TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(destinationBlock, !isSourceFolded);
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(nextSource, FILE_LEVEL);
- TextEditor::BaseTextDocumentLayout::setFoldingIndent(nextDestination, FILE_LEVEL);
+ BaseTextDocumentLayout::doFoldOrUnfold(destinationBlock, !isSourceFolded);
+ BaseTextDocumentLayout::setFoldingIndent(nextSource, FILE_LEVEL);
+ BaseTextDocumentLayout::setFoldingIndent(nextDestination, FILE_LEVEL);
sourceBlock.setVisible(false);
sourceBlock.setLineCount(0);
destinationBlock.setVisible(false);
destinationBlock.setLineCount(0);
- TextEditor::BaseTextDocumentLayout::setFolded(nextSource, false);
- TextEditor::BaseTextDocumentLayout::setFolded(nextDestination, false);
+ BaseTextDocumentLayout::setFolded(nextSource, false);
+ BaseTextDocumentLayout::setFolded(nextDestination, false);
}
}
}
diff --git a/src/plugins/diffeditor/sidebysidediffeditorwidget.h b/src/plugins/diffeditor/sidebysidediffeditorwidget.h
index e3b836ec317..4ba741df1db 100644
--- a/src/plugins/diffeditor/sidebysidediffeditorwidget.h
+++ b/src/plugins/diffeditor/sidebysidediffeditorwidget.h
@@ -55,11 +55,9 @@ class DIFFEDITOR_EXPORT SideBySideDiffEditorWidget : public QWidget
{
Q_OBJECT
public:
- SideBySideDiffEditorWidget(QWidget *parent = 0);
- ~SideBySideDiffEditorWidget();
+ explicit SideBySideDiffEditorWidget(QWidget *parent = 0);
void setDiffEditorGuiController(DiffEditorGuiController *controller);
- DiffEditorGuiController *diffEditorGuiController() const;
private slots:
void clear(const QString &message = QString());
diff --git a/src/plugins/diffeditor/unifieddiffeditorwidget.cpp b/src/plugins/diffeditor/unifieddiffeditorwidget.cpp
index 3bd36d057c3..332667addf7 100644
--- a/src/plugins/diffeditor/unifieddiffeditorwidget.cpp
+++ b/src/plugins/diffeditor/unifieddiffeditorwidget.cpp
@@ -60,7 +60,6 @@
#include <extensionsystem/pluginmanager.h>
-#include <utils/tooltip/tipcontents.h>
#include <utils/tooltip/tooltip.h>
//static const int FILE_LEVEL = 1;
@@ -96,20 +95,14 @@ UnifiedDiffEditorWidget::UnifiedDiffEditorWidget(QWidget *parent)
setDisplaySettings(TextEditorSettings::displaySettings());
setCodeStyle(TextEditorSettings::codeStyle());
- connect(TextEditorSettings::instance(),
- SIGNAL(fontSettingsChanged(TextEditor::FontSettings)),
- this, SLOT(setFontSettings(TextEditor::FontSettings)));
+ connect(TextEditorSettings::instance(), &TextEditorSettings::fontSettingsChanged,
+ this, &UnifiedDiffEditorWidget::setFontSettings);
setFontSettings(TextEditorSettings::fontSettings());
clear(tr("No controller"));
- connect(this, SIGNAL(cursorPositionChanged()),
- this, SLOT(slotCursorPositionChangedInEditor()));
-}
-
-UnifiedDiffEditorWidget::~UnifiedDiffEditorWidget()
-{
-
+ connect(this, &QPlainTextEdit::cursorPositionChanged,
+ this, &UnifiedDiffEditorWidget::slotCursorPositionChangedInEditor);
}
void UnifiedDiffEditorWidget::setDiffEditorGuiController(
@@ -119,17 +112,17 @@ void UnifiedDiffEditorWidget::setDiffEditorGuiController(
return;
if (m_guiController) {
- disconnect(m_controller, SIGNAL(cleared(QString)),
- this, SLOT(clearAll(QString)));
- disconnect(m_controller, SIGNAL(diffFilesChanged(QList<FileData>,QString)),
- this, SLOT(setDiff(QList<FileData>,QString)));
- disconnect(m_controller, SIGNAL(saveStateRequested()),
- this, SLOT(saveStateRequested()));
- disconnect(m_controller, SIGNAL(restoreStateRequested()),
- this, SLOT(restoreStateRequested()));
-
- disconnect(m_guiController, SIGNAL(currentDiffFileIndexChanged(int)),
- this, SLOT(setCurrentDiffFileIndex(int)));
+ disconnect(m_controller, &DiffEditorController::cleared,
+ this, &UnifiedDiffEditorWidget::clearAll);
+ disconnect(m_controller, &DiffEditorController::diffFilesChanged,
+ this, &UnifiedDiffEditorWidget::setDiff);
+ disconnect(m_controller, &DiffEditorController::saveStateRequested,
+ this, &UnifiedDiffEditorWidget::saveStateRequested);
+ disconnect(m_controller, &DiffEditorController::restoreStateRequested,
+ this, &UnifiedDiffEditorWidget::restoreStateRequested);
+
+ disconnect(m_guiController, &DiffEditorGuiController::currentDiffFileIndexChanged,
+ this, &UnifiedDiffEditorWidget::setCurrentDiffFileIndex);
clear(tr("No controller"));
}
@@ -138,17 +131,17 @@ void UnifiedDiffEditorWidget::setDiffEditorGuiController(
if (m_guiController) {
m_controller = m_guiController->controller();
- connect(m_controller, SIGNAL(cleared(QString)),
- this, SLOT(clearAll(QString)));
- connect(m_controller, SIGNAL(diffFilesChanged(QList<FileData>,QString)),
- this, SLOT(setDiff(QList<FileData>,QString)));
- connect(m_controller, SIGNAL(saveStateRequested()),
- this, SLOT(saveStateRequested()));
- connect(m_controller, SIGNAL(restoreStateRequested()),
- this, SLOT(restoreStateRequested()));
+ connect(m_controller, &DiffEditorController::cleared,
+ this, &UnifiedDiffEditorWidget::clearAll);
+ connect(m_controller, &DiffEditorController::diffFilesChanged,
+ this, &UnifiedDiffEditorWidget::setDiff);
+ connect(m_controller, &DiffEditorController::saveStateRequested,
+ this, &UnifiedDiffEditorWidget::saveStateRequested);
+ connect(m_controller, &DiffEditorController::restoreStateRequested,
+ this, &UnifiedDiffEditorWidget::restoreStateRequested);
- connect(m_guiController, SIGNAL(currentDiffFileIndexChanged(int)),
- this, SLOT(setCurrentDiffFileIndex(int)));
+ connect(m_guiController, &DiffEditorGuiController::currentDiffFileIndexChanged,
+ this, &UnifiedDiffEditorWidget::setCurrentDiffFileIndex);
setDiff(m_controller->diffFiles(), m_controller->workingDirectory());
setCurrentDiffFileIndex(m_guiController->currentDiffFileIndex());
@@ -172,11 +165,6 @@ void UnifiedDiffEditorWidget::restoreStateRequested()
m_state.clear();
}
-DiffEditorGuiController *UnifiedDiffEditorWidget::diffEditorGuiController() const
-{
- return m_guiController;
-}
-
void UnifiedDiffEditorWidget::setDisplaySettings(const DisplaySettings &ds)
{
DisplaySettings settings = displaySettings();
@@ -230,7 +218,7 @@ void UnifiedDiffEditorWidget::contextMenuEvent(QContextMenuEvent *e)
addContextMenuActions(menu, fileIndexForBlockNumber(blockNumber),
chunkIndexForBlockNumber(blockNumber));
- connect(this, SIGNAL(destroyed()), menu, SLOT(deleteLater()));
+ connect(this, &UnifiedDiffEditorWidget::destroyed, menu.data(), &QMenu::deleteLater);
menu->exec(e->globalPos());
delete menu;
}
@@ -246,12 +234,12 @@ void UnifiedDiffEditorWidget::addContextMenuActions(QMenu *menu,
menu->addSeparator();
QAction *sendChunkToCodePasterAction =
menu->addAction(tr("Send Chunk to CodePaster..."));
- connect(sendChunkToCodePasterAction, SIGNAL(triggered()),
- this, SLOT(slotSendChunkToCodePaster()));
+ connect(sendChunkToCodePasterAction, &QAction::triggered,
+ this, &UnifiedDiffEditorWidget::slotSendChunkToCodePaster);
QAction *applyAction = menu->addAction(tr("Apply Chunk..."));
- connect(applyAction, SIGNAL(triggered()), this, SLOT(slotApplyChunk()));
+ connect(applyAction, &QAction::triggered, this, &UnifiedDiffEditorWidget::slotApplyChunk);
QAction *revertAction = menu->addAction(tr("Revert Chunk..."));
- connect(revertAction, SIGNAL(triggered()), this, SLOT(slotRevertChunk()));
+ connect(revertAction, &QAction::triggered, this, &UnifiedDiffEditorWidget::slotRevertChunk);
m_contextMenuFileIndex = diffFileIndex;
m_contextMenuChunkIndex = chunkIndex;
@@ -363,7 +351,7 @@ void UnifiedDiffEditorWidget::patch(bool revert)
return;
if (PatchTool::runPatch(
- Core::EditorManager::defaultTextCodec()->fromUnicode(patch),
+ EditorManager::defaultTextCodec()->fromUnicode(patch),
workingDirectory, strip, revert))
m_controller->requestReload();
}
@@ -799,7 +787,7 @@ void UnifiedDiffEditorWidget::jumpToOriginalFile(const QString &fileName,
const QString absoluteFileName = dir.absoluteFilePath(fileName);
QFileInfo fi(absoluteFileName);
if (fi.exists() && !fi.isDir())
- Core::EditorManager::openEditorAt(absoluteFileName, lineNumber, columnNumber);
+ EditorManager::openEditorAt(absoluteFileName, lineNumber, columnNumber);
}
void UnifiedDiffEditorWidget::setCurrentDiffFileIndex(int diffFileIndex)
diff --git a/src/plugins/diffeditor/unifieddiffeditorwidget.h b/src/plugins/diffeditor/unifieddiffeditorwidget.h
index 70258185cc4..df780417029 100644
--- a/src/plugins/diffeditor/unifieddiffeditorwidget.h
+++ b/src/plugins/diffeditor/unifieddiffeditorwidget.h
@@ -58,10 +58,8 @@ class DIFFEDITOR_EXPORT UnifiedDiffEditorWidget
Q_OBJECT
public:
UnifiedDiffEditorWidget(QWidget *parent = 0);
- ~UnifiedDiffEditorWidget();
void setDiffEditorGuiController(DiffEditorGuiController *controller);
- DiffEditorGuiController *diffEditorGuiController() const;
public slots:
void setDisplaySettings(const TextEditor::DisplaySettings &ds);
diff --git a/src/plugins/fakevim/fakevim_test.cpp b/src/plugins/fakevim/fakevim_test.cpp
index 936aa9bebf8..88350eca577 100644
--- a/src/plugins/fakevim/fakevim_test.cpp
+++ b/src/plugins/fakevim/fakevim_test.cpp
@@ -95,7 +95,6 @@ static QByteArray textWithCursor(const QByteArray &text, const QTextBlock &block
do { \
QByteArray beforeText(data.text()); \
int beforePosition = data.position(); \
- data.doKeys("<ESC>"); \
data.doKeys(keys); \
QByteArray actual(data.text()); \
QByteArray expected = expectedText; \
@@ -540,6 +539,147 @@ void FakeVimPlugin::test_vim_movement()
X "");
}
+void FakeVimPlugin::test_vim_target_column_normal()
+{
+ TestData data;
+ setup(&data);
+ data.setText("a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+
+ // normal mode movement
+ KEYS("", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("$", "a" "b" "c" N "d" X "e" N "" N "k" "l" "m" "n");
+ KEYS("k", "a" "b" X "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("3j", "a" "b" "c" N "d" "e" N "" N "k" "l" "m" X "n");
+ KEYS("02k", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" "e" N X "" N "k" "l" "m" "n");
+ KEYS("$", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("2k", "a" "b" X "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("jj2|", "a" "b" "c" N "d" "e" N X "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" "e" N "" N "k" X "l" "m" "n");
+ KEYS("gg", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("^k", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+}
+
+void FakeVimPlugin::test_vim_target_column_visual_char()
+{
+ TestData data;
+ setup(&data);
+ data.setText("a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+
+ KEYS("v", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("$", "a" "b" "c" N "d" "e" X N "" N "k" "l" "m" "n");
+ KEYS("k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("3j", "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n" X);
+ KEYS("02k", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" "e" N X "" N "k" "l" "m" "n");
+ KEYS("$", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("2k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("jj2|", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" "e" N "" N "k" X "l" "m" "n");
+ KEYS("gg", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("^k", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("lO", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<ESC>j",
+ "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+}
+
+void FakeVimPlugin::test_vim_target_column_visual_block()
+{
+ TestData data;
+ setup(&data);
+ data.setText("a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+
+ KEYS("<C-V>",
+ "a" X "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" X "e" N "" N "k" "l" "m" "n");
+ KEYS("$", "a" "b" "c" N "d" "e" X N "" N "k" "l" "m" "n");
+ KEYS("k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("3j", "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n" X);
+ KEYS("02k", "a" "b" "c" N "d" X "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("$", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("2k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("jj2|", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" "e" N "" N "k" "l" X "m" "n");
+ KEYS("gg", "a" X "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("j", "a" "b" "c" N "d" X "e" N "" N "k" "l" "m" "n");
+ KEYS("^k", "a" X "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("lO", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<ESC>j",
+ "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+}
+
+void FakeVimPlugin::test_vim_target_column_visual_line()
+{
+ TestData data;
+ setup(&data);
+ data.setText("a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+
+ KEYS("lV<ESC>", "a" X "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("Vj<ESC>", "a" "b" "c" N "d" X "e" N "" N "k" "l" "m" "n");
+ KEYS("Vj<ESC>", "a" "b" "c" N "d" "e" N X "" N "k" "l" "m" "n");
+ KEYS("Vj<ESC>", "a" "b" "c" N "d" "e" N "" N "k" X "l" "m" "n");
+ KEYS("Vgg<ESC>", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+
+ NOT_IMPLEMENTED
+ // Movement inside selection is not supported.
+}
+
+void FakeVimPlugin::test_vim_target_column_insert()
+{
+ TestData data;
+ setup(&data);
+ data.setText("a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+
+ KEYS("i", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>$", "a" "b" "c" N "d" "e" X N "" N "k" "l" "m" "n");
+ KEYS("<C-O>k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>3j", "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n" X);
+ KEYS("<C-O>0<C-O>2k",
+ "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N "d" "e" N X "" N "k" "l" "m" "n");
+ KEYS("<C-O>$", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("<C-O>2k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<down><down><c-o>2|",
+ "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N "d" "e" N "" N "k" X "l" "m" "n");
+ KEYS("<C-O>gg", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>^<up>",
+ X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+}
+
+void FakeVimPlugin::test_vim_target_column_replace()
+{
+ TestData data;
+ setup(&data);
+ data.setText("a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+
+ KEYS("i<insert>",
+ X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>$", "a" "b" "c" N "d" "e" X N "" N "k" "l" "m" "n");
+ KEYS("<C-O>k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>3j", "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n" X);
+ KEYS("<C-O>0<C-O>2k",
+ "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N "d" "e" N X "" N "k" "l" "m" "n");
+ KEYS("<C-O>$", "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("<C-O>2k", "a" "b" "c" X N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<down><down><c-o>2|",
+ "a" "b" "c" N "d" "e" N "" X N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N "d" "e" N "" N "k" X "l" "m" "n");
+ KEYS("<C-O>gg", X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>j", "a" "b" "c" N X "d" "e" N "" N "k" "l" "m" "n");
+ KEYS("<C-O>^<up>",
+ X "a" "b" "c" N "d" "e" N "" N "k" "l" "m" "n");
+}
+
void FakeVimPlugin::test_vim_insert()
{
TestData data;
@@ -598,6 +738,7 @@ void FakeVimPlugin::test_vim_insert()
// <C-O>
data.setText("abc" N "d" X "ef");
KEYS("i<c-o>xX", "abc" N "dX" X "f");
+ data.doKeys("<ESC>");
KEYS("i<c-o><end>", "abc" N "dXf" X);
data.setText("ab" X "c" N "def");
KEYS("i<c-o>rX", "ab" X "X" N "def");
@@ -607,6 +748,8 @@ void FakeVimPlugin::test_vim_insert()
KEYS("i<c-o>0x", "abc" N "x" X "def");
data.setText("abc" N "de" X "f");
KEYS("i<c-o>ggx", "x" X "abc" N "def");
+ data.setText("abc" N "def" N "ghi");
+ KEYS("i<c-o>vjlolx", "a" X "f" N "ghi");
// <INSERT> to toggle between insert and replace mode
data.setText("abc" N "def");
@@ -632,6 +775,7 @@ void FakeVimPlugin::test_vim_insert()
// delete in insert mode is part of dot command
data.setText("abc" N "def");
KEYS("iX<delete>Y", "XY" X "bc" N "def");
+ data.doKeys("<ESC>");
KEYS("0j.", "XYbc" N "X" X "Yef");
data.setText("abc" N "def");
@@ -640,10 +784,12 @@ void FakeVimPlugin::test_vim_insert()
data.setText("abc" N "def");
KEYS("i<delete>XY", "XY" X "bc" N "def");
+ data.doKeys("<ESC>");
KEYS("0j.", "XYbc" N "X" X "Yef");
data.setText("ab" X "c" N "def");
KEYS("i<bs>XY", "aXY" X "c" N "def");
+ data.doKeys("<ESC>");
KEYS("j.", "aXYc" N "dX" X "Yf");
// insert in visual mode
@@ -1135,10 +1281,13 @@ void FakeVimPlugin::test_vim_change_replace()
// change in empty document
data.setText("");
KEYS("ccABC", "ABC" X);
+ data.doKeys("<ESC>");
KEYS("u", "");
KEYS("SABC", "ABC" X);
+ data.doKeys("<ESC>");
KEYS("u", "");
KEYS("sABC", "ABC" X);
+ data.doKeys("<ESC>");
KEYS("u", "");
KEYS("rA", "" X);
@@ -1424,6 +1573,432 @@ void FakeVimPlugin::test_vim_block_selection_insert()
"a" X "bXYZc" N
" XYZ" N
"deXYZf" N
+ );
+}
+
+void FakeVimPlugin::test_vim_delete_inner_paragraph()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(
+ "abc" N
+ "def" N
+ "" N
+ "" N
+ "ghi" N
+ "" N
+ "jkl" N
+ );
+
+ KEYS("dip",
+ X "" N
+ "" N
+ "ghi" N
+ "" N
+ "jkl" N
+ );
+ KEYS("dip",
+ X "ghi" N
+ "" N
+ "jkl" N
+ );
+ KEYS("2dip",
+ X "jkl" N
+ );
+}
+
+void FakeVimPlugin::test_vim_delete_a_paragraph()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(
+ "abc" N
+ "def" N
+ "" N
+ "" N
+ "ghi" N
+ "" N
+ "jkl" N
+ );
+
+ KEYS("dap",
+ X "ghi" N
+ "" N
+ "jkl" N
+ );
+ KEYS("dap",
+ X "jkl" N
+ );
+ KEYS("u",
+ X "ghi" N
+ "" N
+ "jkl" N
+ );
+
+ data.setText(
+ "abc" N
+ "" N
+ "" N
+ "def"
+ );
+ KEYS("Gdap",
+ X "abc"
+ );
+}
+
+void FakeVimPlugin::test_vim_change_inner_paragraph()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(
+ "abc" N
+ "def" N
+ "" N
+ "" N
+ "ghi" N
+ "" N
+ "jkl" N
+ );
+
+ KEYS("cipXXX<ESC>",
+ "XX" X "X" N
+ "" N
+ "" N
+ "ghi" N
+ "" N
+ "jkl" N
+ );
+ KEYS("3j" "cipYYY<ESC>",
+ "XXX" N
+ "" N
+ "" N
+ "YY" X "Y" N
+ "" N
+ "jkl" N
+ );
+}
+
+void FakeVimPlugin::test_vim_change_a_paragraph()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(
+ "abc" N
+ "def" N
+ "" N
+ "" N
+ "ghi" N
+ "" N
+ "jkl" N
+ );
+
+ KEYS("4j" "capXXX<ESC>",
+ "abc" N
+ "def" N
+ "" N
+ "" N
+ "XX" X "X" N
+ "jkl" N
+ );
+ KEYS("gg" "capYYY<ESC>",
+ "YY" X "Y" N
+ "XXX" N
+ "jkl" N
+ );
+
+ data.setText(
+ "abc" N
+ "" N
+ "" N
+ "def"
+ );
+ KEYS("GcapXXX<ESC>",
+ "abc" N
+ "XX" X "X"
+ );
+}
+
+void FakeVimPlugin::test_vim_select_inner_paragraph()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(
+ "" N
+ X "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("vip" "r-",
+ "" N
+ X "---" N
+ "---" N
+ "" N
+ "ghi"
+ );
+
+ data.setText(
+ "" N
+ X "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("vip" ":s/^/-<CR>",
+ "" N
+ "-abc" N
+ X "-def" N
+ "" N
+ "ghi"
+ );
+
+ data.setText(
+ "" N
+ X "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("v2ip" ":s/^/-<CR>",
+ "" N
+ "-abc" N
+ "-def" N
+ X "-" N
+ "ghi"
+ );
+
+ data.setText(
+ "" N
+ X "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("Vj" "ip" ":s/^/-<CR>",
+ "" N
+ "-abc" N
+ "-def" N
+ X "-" N
+ "ghi"
+ );
+
+ data.setText(
+ "" N
+ X "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("vj" "ip" ":s/^/-<CR>",
+ "" N
+ "-abc" N
+ "-def" N
+ "-" N
+ "ghi"
+ );
+
+ data.setText(
+ "" N
+ X "abc" N
+ "def" N
+ "ghi" N
+ "" N
+ "jkl"
+ );
+ KEYS("vj" "ip" ":s/^/-<CR>",
+ "" N
+ "-abc" N
+ "-def" N
+ "-ghi" N
+ "" N
+ "jkl"
+ );
+
+ data.setText(
+ "" N
+ X "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("vip" "r-",
+ "" N
+ X "---" N
+ "---" N
+ "" N
+ "ghi"
+ );
+
+ data.setText(
+ "abc" N
+ "" N
+ "def"
+ );
+ KEYS("G" "vip" "r-",
+ "abc" N
+ "" N
+ "---"
+ );
+
+ data.setText(
+ "" N
+ "" N
+ "ghi"
+ );
+ KEYS("vip" ":s/^/-<CR>",
+ "-" N
+ "-" N
+ "ghi"
+ );
+
+ data.setText(
+ "" N
+ "ghi"
+ );
+ KEYS("vip" "ip" ":s/^/-<CR>",
+ "-" N
+ X "-ghi"
+ );
+
+ data.setText(
+ "abc" N
+ "" N
+ ""
+ );
+ KEYS("j" "vip" ":s/^/-<CR>",
+ "abc" N
+ "-" N
+ "-"
+ );
+
+ // Don't move anchor if it's on different line.
+ data.setText(
+ "" N
+ "abc" N
+ X "def" N
+ "ghi" N
+ "" N
+ "jkl"
+ );
+ KEYS("vj" "ip" ":s/^/-<CR>",
+ "" N
+ "abc" N
+ "-def" N
+ "-ghi" N
+ X "-" N
+ "jkl"
+ );
+
+ // Don't change selection mode if anchor is on different line.
+ data.setText(
+ "" N
+ "abc" N
+ X "def" N
+ "ghi" N
+ "" N
+ "jkl"
+ );
+ KEYS("vj" "2ip" "r-",
+ "" N
+ "abc" N
+ X "---" N
+ "---" N
+ "" N
+ "-kl"
+ );
+ KEYS("gv" ":s/^/X<CR>",
+ "" N
+ "abc" N
+ "X---" N
+ "X---" N
+ "X" N
+ X "X-kl"
+ );
+
+ data.setText(
+ "" N
+ "abc" N
+ X "def" N
+ "ghi" N
+ "" N
+ "jkl"
+ );
+ KEYS("<C-V>j" "2ip" "r-",
+ "" N
+ "abc" N
+ X "-ef" N
+ "-hi" N
+ "" N
+ "-kl"
+ );
+ KEYS("gv" "IX<ESC>",
+ "" N
+ "abc" N
+ "X-ef" N
+ "X-hi" N
+ "X" N
+ "X-kl"
+ );
+}
+
+void FakeVimPlugin::test_vim_select_a_paragraph()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(
+ "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("vap" ":s/^/-<CR>",
+ "-abc" N
+ "-def" N
+ "-" N
+ "ghi"
+ );
+
+ data.setText(
+ "" N
+ "abc" N
+ "def" N
+ "" N
+ "ghi"
+ );
+ KEYS("vap" ":s/^/-<CR>",
+ "-" N
+ "-abc" N
+ "-def" N
+ "" N
+ "ghi"
+ );
+
+ data.setText(
+ "abc" N
+ "def" N
+ ""
+ );
+ KEYS("j" "vap" ":s/^/-<CR>",
+ "-abc" N
+ "-def" N
+ "-"
+ );
+
+ data.setText(
+ "" N
+ "abc" N
+ "def"
+ );
+ KEYS("j" "vap" ":s/^/-<CR>",
+ "-" N
+ "-abc" N
+ "-def"
);
}
@@ -1680,6 +2255,59 @@ void FakeVimPlugin::test_vim_indent()
data.setText("abc");
KEYS(">>", "\t\t abc");
INTEGRITY(false);
+
+ // indent inner block
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=2");
+ data.setText("int main()" N
+ "{" N
+ "int i = 0;" N
+ X "return i;" N
+ "}" N
+ "");
+ KEYS(">i{",
+ "int main()" N
+ "{" N
+ " " X "int i = 0;" N
+ " return i;" N
+ "}" N
+ "");
+ KEYS(">i}",
+ "int main()" N
+ "{" N
+ " " X "int i = 0;" N
+ " return i;" N
+ "}" N
+ "");
+ KEYS("<i}",
+ "int main()" N
+ "{" N
+ " " X "int i = 0;" N
+ " return i;" N
+ "}" N
+ "");
+
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=2");
+ data.setText("int main() {" N
+ "return i;" N
+ X "}" N
+ "");
+ KEYS("l>i{",
+ "int main() {" N
+ " " X "return i;" N
+ "}" N
+ "");
+ KEYS("l>i}",
+ "int main() {" N
+ " " X "return i;" N
+ "}" N
+ "");
+ KEYS("l<i}",
+ "int main() {" N
+ " " X "return i;" N
+ "}" N
+ "");
}
void FakeVimPlugin::test_vim_marks()
@@ -1775,6 +2403,7 @@ void FakeVimPlugin::test_vim_current_column()
KEYS("<up>", " abc" N " def 12" X "3" N "" N " ghi");
// ... in insert
KEYS("i<end><up>", " abc" X N " def 123" N "" N " ghi");
+ data.doKeys("<ESC>");
KEYS("<down>i<end><up><down>", " abc" N " def 123" X N "" N " ghi");
// vertical movement doesn't reset column
@@ -1798,11 +2427,14 @@ void FakeVimPlugin::test_vim_current_column()
data.setText(" abc" N " def" N " ghi");
KEYS("lljj", " abc" N " def" N " " X "ghi");
KEYS("i123<up>", " abc" N " def" X N " 123ghi");
+ data.doKeys("<ESC>");
KEYS("a456<up><down>", " abc" N " def456" X N " 123ghi");
data.setText(" abc" N X " def 123" N "" N " ghi");
KEYS("A<down><down>", " abc" N " def 123" N "" N " ghi" X);
+ data.doKeys("<ESC>");
KEYS("A<up><up>", " abc" N " def" X " 123" N "" N " ghi");
+ data.doKeys("<ESC>");
KEYS("A<down><down><up><up>", " abc" N " def 123" X N "" N " ghi");
data.setText(" abc" N X " def 123" N "" N " ghi");
@@ -1862,6 +2494,9 @@ void FakeVimPlugin::test_vim_copy_paste()
KEYS("yj", "ab" X "c" N "def");
data.setText("abc" N "de" X "f");
KEYS("yk", "ab" X "c" N "def");
+ data.setText("ab" X "c" N "def");
+ KEYS("yy", "ab" X "c" N "def");
+ KEYS("2yy", "ab" X "c" N "def");
// copy empty line
data.setText(X "a" N "" N "b");
@@ -2058,6 +2693,7 @@ void FakeVimPlugin::test_vim_code_autoindent()
" return 0;" N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("^i" "int x = 1;" N,
"int main()" N
"{" N
@@ -2067,6 +2703,7 @@ void FakeVimPlugin::test_vim_code_autoindent()
" return 0;" N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("c2k" "if (true) {" N ";" N "}",
"int main()" N
"{" N
@@ -2076,12 +2713,14 @@ void FakeVimPlugin::test_vim_code_autoindent()
" return 0;" N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("jci{" "return 1;",
"int main()" N
"{" N
" return 1;" X N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("di{",
"int main()" N
"{" N
@@ -2212,8 +2851,7 @@ void FakeVimPlugin::test_vim_code_completion()
data.completeText("st");
data.doKeys("1");
data.completeText("Var");
- data.doKeys(" = 0");
- KEYS("",
+ KEYS(" = 0<ESC>",
"int test1Var;" N
"int test2Var;" N
"int main() {" N
@@ -2225,8 +2863,7 @@ void FakeVimPlugin::test_vim_code_completion()
data.completeText("st");
data.doKeys("2");
data.completeText("Var");
- data.doKeys(" = 1;");
- KEYS("",
+ KEYS(" = 1;<ESC>",
"int test1Var;" N
"int test2Var;" N
"int main() {" N
@@ -2234,6 +2871,7 @@ void FakeVimPlugin::test_vim_code_completion()
" test2Var = 1" X ";" N
"}" N
"");
+ data.doKeys("<ESC>");
// repeat text insertion with completion
KEYS(".",
@@ -2403,6 +3041,43 @@ void FakeVimPlugin::test_vim_ex_yank()
"aaabcb" X "cabcbc def" N
"ghi jkl" N
);
+
+ // uppercase register appends to lowercase
+ data.setText(
+ "abc" N
+ "def" N
+ "ghi" N
+ );
+ KEYS("\"zdd" "\"zp",
+ "def" N
+ X "abc" N
+ "ghi" N
+ );
+ KEYS("k\"Zyy" "jj\"zp",
+ "def" N
+ "abc" N
+ "ghi" N
+ X "abc" N
+ "def" N
+ );
+ KEYS("k\"Zdd" "j\"Zp",
+ "def" N
+ "abc" N
+ "abc" N
+ "def" N
+ X "abc" N
+ "def" N
+ "ghi" N
+ );
+ KEYS("\"zdk" "gg\"zp",
+ "def" N
+ X "def" N
+ "abc" N
+ "abc" N
+ "abc" N
+ "def" N
+ "ghi" N
+ );
}
void FakeVimPlugin::test_vim_ex_delete()
@@ -3425,6 +4100,21 @@ void FakeVimPlugin::test_vim_Visual_d()
KEYS("P", '|' + lmid(0,1)+'\n' + lmid(3));
}
+void FakeVimPlugin::test_vim_visual_block_D()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc def" N "ghi" N "" N "jklm");
+ KEYS("l<C-V>3j", "abc def" N "ghi" N "" N "jk" X "lm");
+ KEYS("D", X "a" N "g" N "" N "j");
+
+ KEYS("u", "a" X "bc def" N "ghi" N "" N "jklm");
+ KEYS("<C-R>", X "a" N "g" N "" N "j");
+ KEYS("u", "a" X "bc def" N "ghi" N "" N "jklm");
+ KEYS(".", X "a" N "g" N "" N "j");
+}
+
void FakeVimPlugin::test_macros()
{
TestData data;
@@ -3476,6 +4166,25 @@ void FakeVimPlugin::test_macros()
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>.");
+
+ // record command line
+ data.setText("abc" N "def");
+ KEYS("qq" ":s/./*/g<ESC>" "iX<ESC>" "q", X "Xabc" N "def");
+ KEYS("@q", X "XXabc" N "def");
+
+ KEYS("qq" ":s/./*/g<BS><BS><BS><BS><BS><BS><BS><BS>" "iY<ESC>" "q", X "YXXabc" N "def");
+ KEYS("@q", X "YYXXabc" N "def");
+
+ KEYS("qq" ":s/./*/g<CR>" "q", X "*******" N "def");
+ KEYS("j@q", "*******" N X "***");
+
+ // record repeating last command
+ data.setText("abc" N "def");
+ KEYS(":s/./-/g<CR>", X "---" N "def");
+ KEYS("u", X "abc" N "def");
+ KEYS("qq" ":<UP><CR>" "q", X "---" N "def");
+ KEYS(":s/./!/g<CR>", X "!!!" N "def");
+ KEYS("j@q", "!!!" N X "!!!");
}
void FakeVimPlugin::test_vim_qtcreator()
@@ -3493,18 +4202,21 @@ void FakeVimPlugin::test_vim_qtcreator()
" ;" X N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("cc" "assert(arg1 != 0",
"void f(int arg1) {" N
" // TODO" N
" assert(arg1 != 0" X ")" N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("k" "." "A;",
"void f(int arg1) {" N
" assert(arg1 != 0);" X N
" assert(arg1 != 0)" N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("j.",
"void f(int arg1) {" N
" assert(arg1 != 0);" N
@@ -3688,6 +4400,7 @@ void FakeVimPlugin::test_vim_qtcreator()
" if (arg1 > 0) return true;" N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("`'",
"bool f(int arg1, int arg2 = 0) {" N
" assert(arg1 >= 0);" N
@@ -3702,6 +4415,7 @@ void FakeVimPlugin::test_vim_qtcreator()
" if (arg1 > 0) return false;" X N
"}" N
"");
+ data.doKeys("<ESC>");
KEYS("k.",
"bool f(int arg1, int arg2 = 0) {" N
" assert(arg1 >= 0);" N
diff --git a/src/plugins/fakevim/fakevimhandler.cpp b/src/plugins/fakevim/fakevimhandler.cpp
index fc37c2dc6a6..710270cfe3a 100644
--- a/src/plugins/fakevim/fakevimhandler.cpp
+++ b/src/plugins/fakevim/fakevimhandler.cpp
@@ -93,6 +93,7 @@
#include <algorithm>
#include <climits>
#include <ctype.h>
+#include <functional>
//#define DEBUG_KEY 1
#if DEBUG_KEY
@@ -239,7 +240,7 @@ enum MoveType
\value RangeLineMode Entered by pressing \key V. The range includes
all lines between the line of the cursor and
the line of the anchor.
- \value RangeLineModeExclusice Like \l RangeLineMode, but keeps one
+ \value RangeLineModeExclusive Like \l RangeLineMode, but keeps one
newline when deleting.
\value RangeBlockMode Entered by pressing \key Ctrl-v. The range includes
all characters with line and column coordinates
@@ -953,6 +954,13 @@ inline QString msgMarkNotSet(const QString &text)
return Tr::tr("Mark \"%1\" not set.").arg(text);
}
+static void initSingleShotTimer(QTimer *timer, int interval, QObject *receiver, const char *slot)
+{
+ timer->setSingleShot(true);
+ timer->setInterval(interval);
+ QObject::connect(timer, SIGNAL(timeout()), receiver, slot);
+}
+
class Input
{
public:
@@ -1170,6 +1178,64 @@ private:
// mapping to <Nop> (do nothing)
static const Input Nop(-1, Qt::KeyboardModifiers(-1), QString());
+static SubMode letterCaseModeFromInput(const Input &input)
+{
+ if (input.is('~'))
+ return InvertCaseSubMode;
+ if (input.is('u'))
+ return DownCaseSubMode;
+ if (input.is('U'))
+ return UpCaseSubMode;
+
+ return NoSubMode;
+}
+
+static SubMode indentModeFromInput(const Input &input)
+{
+ if (input.is('<'))
+ return ShiftLeftSubMode;
+ if (input.is('>'))
+ return ShiftRightSubMode;
+ if (input.is('='))
+ return IndentSubMode;
+
+ return NoSubMode;
+}
+
+static SubMode changeDeleteYankModeFromInput(const Input &input)
+{
+ if (input.is('c'))
+ return ChangeSubMode;
+ if (input.is('d'))
+ return DeleteSubMode;
+ if (input.is('y'))
+ return YankSubMode;
+
+ return NoSubMode;
+}
+
+QString dotCommandFromSubMode(SubMode submode)
+{
+ if (submode == ChangeSubMode)
+ return _("c");
+ if (submode == DeleteSubMode)
+ return _("d");
+ if (submode == InvertCaseSubMode)
+ return _("g~");
+ if (submode == DownCaseSubMode)
+ return _("gu");
+ if (submode == UpCaseSubMode)
+ return _("gU");
+ if (submode == IndentSubMode)
+ return _("=");
+ if (submode == ShiftRightSubMode)
+ return _(">");
+ if (submode == ShiftLeftSubMode)
+ return _("<");
+
+ return QString();
+}
+
QDebug operator<<(QDebug ts, const Input &input) { return input.dump(ts); }
class Inputs : public QVector<Input>
@@ -1586,7 +1652,7 @@ public:
EventResult handleEvent(QKeyEvent *ev);
bool wantsOverride(QKeyEvent *ev);
- bool parseExCommmand(QString *line, ExCommand *cmd);
+ bool parseExCommand(QString *line, ExCommand *cmd);
bool parseLineRange(QString *line, ExCommand *cmd);
int parseLineAddress(QString *cmd);
void parseRangeCount(const QString &line, Range *range) const;
@@ -1603,12 +1669,16 @@ public:
void init();
void focus();
+ void unfocus();
+ void fixExternalCursor(bool focus);
+ void fixExternalCursorPosition(bool focus);
// Call before any FakeVim processing (import cursor position from editor)
void enterFakeVim();
// Call after any FakeVim processing
// (if needUpdate is true, export cursor position to editor and scroll)
void leaveFakeVim(bool needUpdate = true);
+ void leaveFakeVim(EventResult eventResult);
EventResult handleKey(const Input &input);
EventResult handleDefaultKey(const Input &input);
@@ -1632,14 +1702,14 @@ public:
// return true only if input in current mode and sub-mode was correctly handled
bool handleEscape();
bool handleNoSubMode(const Input &);
- bool handleChangeDeleteSubModes(const Input &);
+ bool handleChangeDeleteYankSubModes(const Input &);
+ void handleChangeDeleteYankSubModes();
bool handleReplaceSubMode(const Input &);
bool handleFilterSubMode(const Input &);
bool handleRegisterSubMode(const Input &);
bool handleShiftSubMode(const Input &);
bool handleChangeCaseSubMode(const Input &);
bool handleWindowSubMode(const Input &);
- bool handleYankSubMode(const Input &);
bool handleZSubMode(const Input &);
bool handleCapitalZSubMode(const Input &);
bool handleMacroRecordSubMode(const Input &);
@@ -1654,8 +1724,15 @@ public:
void fixSelection(); // Fix selection according to current range, move and command modes.
bool finishSearch();
void finishMovement(const QString &dotCommandMovement = QString());
- void resetCommandMode();
- void clearCommandMode();
+
+ // Returns to insert/replace mode after <C-O> command in insert mode,
+ // otherwise returns to command mode.
+ void leaveCurrentMode();
+
+ // Clear data for current (possibly incomplete) command in current mode.
+ // I.e. clears count, register, g flag, sub-modes etc.
+ void clearCurrentMode();
+
QTextCursor search(const SearchData &sd, int startPos, int count, bool showMessages);
void search(const SearchData &sd, bool showMessages = true);
bool searchNext(bool forward = true);
@@ -1678,7 +1755,9 @@ public:
bool atDocumentEnd() const { return position() >= lastPositionInDocument(true); }
bool atDocumentStart() const { return m_cursor.atStart(); }
- bool atEmptyLine(const QTextCursor &tc = QTextCursor()) const;
+ bool atEmptyLine(int pos) const;
+ bool atEmptyLine(const QTextCursor &tc) const;
+ bool atEmptyLine() const;
bool atBoundary(bool end, bool simple, bool onlyWords = false,
const QTextCursor &tc = QTextCursor()) const;
bool atWordBoundary(bool end, bool simple, const QTextCursor &tc = QTextCursor()) const;
@@ -1697,6 +1776,9 @@ public:
bool end, int count) const; // end or start position of current code block
int lineNumber(const QTextBlock &block) const;
+ int columnAt(int pos) const;
+ int blockNumberAt(int pos) const;
+ QTextBlock blockAt(int pos) const;
QTextBlock nextLine(const QTextBlock &block) const; // following line (respects wrapped parts)
QTextBlock previousLine(const QTextBlock &block) const; // previous line (respects wrapped parts)
@@ -1767,16 +1849,22 @@ public:
void moveDown(int n = 1);
void moveUpVisually(int n = 1) { moveDownVisually(-n); }
void moveDownVisually(int n = 1);
+ void moveVertically(int n = 1) {
+ if (g.gflag) {
+ g.movetype = MoveExclusive;
+ moveDownVisually(n);
+ } else {
+ g.movetype = MoveLineWise;
+ moveDown(n);
+ }
+ }
void movePageDown(int count = 1);
void movePageUp(int count = 1) { movePageDown(-count); }
void dump(const char *msg) const {
qDebug() << msg << "POS: " << anchor() << position()
- << "EXT: " << m_oldExternalAnchor << m_oldExternalPosition
- << "INT: " << m_oldInternalAnchor << m_oldInternalPosition
<< "VISUAL: " << g.visualMode;
}
void moveRight(int n = 1) {
- //dump("RIGHT 1");
if (isVisualCharMode()) {
const QTextBlock currentBlock = block();
const int max = currentBlock.position() + currentBlock.length() - 1;
@@ -1787,10 +1875,21 @@ public:
}
if (atEndOfLine())
emit q->fold(1, false);
- //dump("RIGHT 2");
+ setTargetColumn();
}
void moveLeft(int n = 1) {
m_cursor.movePosition(Left, KeepAnchor, n);
+ setTargetColumn();
+ }
+ void moveToNextCharacter() {
+ moveRight();
+ if (atEndOfLine())
+ moveRight();
+ }
+ void moveToPreviousCharacter() {
+ moveLeft();
+ if (atBlockStart())
+ moveLeft();
}
void setAnchor() {
m_cursor.setPosition(position(), MoveAnchor);
@@ -1805,30 +1904,23 @@ public:
m_cursor.setPosition(anchor, MoveAnchor);
m_cursor.setPosition(position, KeepAnchor);
}
+
// Set cursor in text editor widget.
- void commitCursor() {
- if (isVisualBlockMode()) {
- emit q->requestSetBlockSelection(m_cursor);
- } else {
- emit q->requestDisableBlockSelection();
- if (editor())
- EDITOR(setTextCursor(m_cursor));
- }
- }
+ void commitCursor();
+
// Restore cursor from editor widget.
- void pullCursor() {
- if (isVisualBlockMode())
- q->requestBlockSelection(&m_cursor);
- else if (editor())
- m_cursor = EDITOR(textCursor());
- }
+ // Update selection, record jump and target column if cursor position
+ // changes externally (e.g. by code completion).
+ void pullCursor();
// Values to save when starting FakeVim processing.
int m_firstVisibleLine;
QTextCursor m_cursor;
+ bool m_cursorNeedsUpdate;
- bool moveToPreviousParagraph(int count) { return moveToNextParagraph(-count); }
- bool moveToNextParagraph(int count);
+ bool moveToPreviousParagraph(int count = 1) { return moveToNextParagraph(-count); }
+ bool moveToNextParagraph(int count = 1);
+ void moveToParagraphStartOrEnd(int direction = 1);
bool handleFfTt(const QString &key, bool repeats = false);
@@ -1845,10 +1937,12 @@ public:
void updateSelection();
void updateHighlights();
void updateCursorShape();
+ void setThinCursor(bool enable = true);
+ bool hasThinCursor() const;
QWidget *editor() const;
QTextDocument *document() const { return EDITOR(document()); }
- QChar characterAtCursor() const
- { return document()->characterAt(position()); }
+ QChar characterAt(int pos) const { return document()->characterAt(pos); }
+ QChar characterAtCursor() const { return characterAt(position()); }
void joinPreviousEditBlock();
void beginEditBlock(bool largeEditBlock = false);
@@ -1856,9 +1950,16 @@ public:
void endEditBlock();
void breakEditBlock() { m_buffer->breakEditBlock = true; }
+ bool canModifyBufferData() const { return m_buffer->currentHandler.data() == this; }
+
Q_SLOT void onContentsChanged(int position, int charsRemoved, int charsAdded);
+ Q_SLOT void onCursorPositionChanged();
Q_SLOT void onUndoCommandAdded();
+ Q_SLOT void onInputTimeout();
+ Q_SLOT void onFixCursorTimeout();
+
+ bool isCommandLineMode() const { return g.mode == ExMode || g.subsubmode == SearchSubSubMode; }
bool isInsertMode() const { return g.mode == InsertMode || g.mode == ReplaceMode; }
// Waiting for movement operator.
bool isOperatorPending() const {
@@ -1891,8 +1992,6 @@ public:
bool selectBlockTextObject(bool inner, char left, char right);
bool selectQuotedStringTextObject(bool inner, const QString &quote);
- Q_SLOT void importSelection();
- void exportSelection();
void commitInsertState();
void invalidateInsertState();
bool isInsertStateValid() const;
@@ -1906,6 +2005,9 @@ public:
void stopRecording();
bool executeRegister(int register);
+ // Handle current command as synonym
+ void handleAs(const QString &command);
+
public:
QTextEdit *m_textedit;
QPlainTextEdit *m_plaintextedit;
@@ -1914,14 +2016,9 @@ public:
bool m_inFakeVim; // true if currently processing a key press or a command
FakeVimHandler *q;
- 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_register;
BlockInsertMode m_visualBlockInsert;
- bool m_fakeEnd;
bool m_anchorPastEnd;
bool m_positionPastEnd; // '$' & 'l' in visual mode can move past eol
@@ -1932,35 +2029,22 @@ public:
int anchor() const { return m_cursor.anchor(); }
int position() const { return m_cursor.position(); }
- struct TransformationData
- {
- TransformationData(const QString &s, const QVariant &d)
- : from(s), extraData(d) {}
- QString from;
- QString to;
- QVariant extraData;
- };
- typedef void (Private::*Transformation)(TransformationData *td);
- void transformText(const Range &range, Transformation transformation,
- const QVariant &extraData = QVariant());
+ // Transform text selected by cursor in current visual mode.
+ typedef std::function<QString(const QString &)> Transformation;
+ void transformText(const Range &range, QTextCursor &tc, const std::function<void()> &transform) const;
+ void transformText(const Range &range, const Transformation &transform);
void insertText(QTextCursor &tc, const QString &text);
void insertText(const Register &reg);
void removeText(const Range &range);
- void removeTransform(TransformationData *td);
void invertCase(const Range &range);
- void invertCaseTransform(TransformationData *td);
void upCase(const Range &range);
- void upCaseTransform(TransformationData *td);
void downCase(const Range &range);
- void downCaseTransform(TransformationData *td);
void replaceText(const Range &range, const QString &str);
- void replaceByStringTransform(TransformationData *td);
- void replaceByCharTransform(TransformationData *td);
QString selectText(const Range &range) const;
void setCurrentRange(const Range &range);
@@ -1970,12 +2054,14 @@ public:
void pasteText(bool afterCursor);
+ void cutSelectedText();
+
void joinLines(int count, bool preserveSpace = false);
void insertNewLine();
bool handleInsertInEditor(const Input &input);
- bool passEventToEditor(QEvent &event); // Pass event to editor widget without filtering. Returns true if event was processed.
+ bool passEventToEditor(QEvent &event, QTextCursor &tc); // Pass event to editor widget without filtering. Returns true if event was processed.
// undo handling
int revision() const { return document()->availableUndoSteps(); }
@@ -1993,6 +2079,7 @@ public:
// visual modes
void toggleVisualMode(VisualMode visualMode);
void leaveVisualMode();
+ void saveLastVisualMode();
// marks
Mark mark(QChar code) const;
@@ -2025,7 +2112,7 @@ public:
QString registerContents(int reg) const;
void setRegister(int reg, const QString &contents, RangeMode mode);
RangeMode registerRangeMode(int reg) const;
- void getRegisterType(int reg, bool *isClipboard, bool *isSelection) const;
+ void getRegisterType(int *reg, bool *isClipboard, bool *isSelection, bool *append = 0) const;
void recordJump(int position = -1);
void jump(int distance);
@@ -2058,8 +2145,6 @@ public:
bool handleExWriteCommand(const ExCommand &cmd);
bool handleExEchoCommand(const ExCommand &cmd);
- void timerEvent(QTimerEvent *ev);
-
void setupCharClass();
int charClass(QChar c, bool simple) const;
signed char m_charClass[256];
@@ -2068,6 +2153,9 @@ public:
int m_ctrlVLength;
int m_ctrlVBase;
+ QTimer m_fixCursorTimer;
+ QTimer m_inputTimer;
+
void miniBufferTextEdited(const QString &text, int cursorPos, int anchorPos);
// Data shared among editors with same document.
@@ -2091,7 +2179,6 @@ public:
QStack<CursorPosition> jumpListUndo;
QStack<CursorPosition> jumpListRedo;
- CursorPosition lastChangePosition;
VisualMode lastVisualMode;
bool lastVisualModeInverted;
@@ -2112,6 +2199,10 @@ public:
} insertState;
QString lastInsertion;
+
+ // If there are multiple editors with same document,
+ // only the handler with last focused editor can change buffer data.
+ QPointer<QObject> currentHandler;
};
typedef QSharedPointer<BufferData> BufferDataPtr;
@@ -2134,7 +2225,6 @@ public:
, gflag(false)
, mappings()
, currentMap(&mappings)
- , inputTimer(-1)
, mapDepth(0)
, currentMessageLevel(MessageInfo)
, lastSearchForward(false)
@@ -2179,7 +2269,6 @@ public:
// Input.
QList<Input> pendingInput;
MappingsIterator currentMap;
- int inputTimer;
QStack<MappingState> mapStates;
int mapDepth;
@@ -2238,20 +2327,17 @@ FakeVimHandler::Private::Private(FakeVimHandler *parent, QWidget *widget)
void FakeVimHandler::Private::init()
{
+ m_cursor = QTextCursor(document());
+ m_cursorNeedsUpdate = true;
m_inFakeVim = false;
m_findStartPosition = -1;
m_visualBlockInsert = NoneBlockInsertMode;
- m_fakeEnd = false;
m_positionPastEnd = false;
m_anchorPastEnd = false;
m_register = '"';
m_targetColumn = 0;
m_visualTargetColumn = 0;
m_targetColumnWrapped = 0;
- m_oldInternalAnchor = -1;
- m_oldInternalPosition = -1;
- m_oldExternalAnchor = -1;
- m_oldExternalPosition = -1;
m_searchStartPosition = 0;
m_searchFromScreenLine = 0;
m_firstVisibleLine = 0;
@@ -2259,72 +2345,86 @@ void FakeVimHandler::Private::init()
m_ctrlVLength = 0;
m_ctrlVBase = 0;
+ initSingleShotTimer(&m_fixCursorTimer, 0, this, SLOT(onFixCursorTimeout()));
+ initSingleShotTimer(&m_inputTimer, 1000, this, SLOT(onInputTimeout()));
+
pullOrCreateBufferData();
setupCharClass();
}
void FakeVimHandler::Private::focus()
{
+ m_buffer->currentHandler = this;
+
enterFakeVim();
stopIncrementalFind();
- if (!isInsertMode()) {
+ if (isCommandLineMode()) {
if (g.subsubmode == SearchSubSubMode) {
setPosition(m_searchStartPosition);
scrollToLine(m_searchFromScreenLine);
- setTargetColumn();
- setAnchor();
- commitCursor();
- } else if (g.submode != NoSubMode || g.mode == ExMode) {
+ } else {
leaveVisualMode();
setPosition(qMin(position(), anchor()));
- setTargetColumn();
- setAnchor();
- commitCursor();
}
-
- bool exitCommandLine = (g.subsubmode == SearchSubSubMode || g.mode == ExMode);
- resetCommandMode();
- if (exitCommandLine)
- updateMiniBuffer();
+ leaveCurrentMode();
+ setTargetColumn();
+ setAnchor();
+ commitCursor();
+ } else {
+ clearCurrentMode();
}
- updateCursorShape();
- if (g.mode != CommandMode)
- updateMiniBuffer();
+ fixExternalCursor(true);
updateHighlights();
leaveFakeVim(false);
}
+void FakeVimHandler::Private::unfocus()
+{
+ fixExternalCursor(false);
+}
+
+void FakeVimHandler::Private::fixExternalCursor(bool focus)
+{
+ m_fixCursorTimer.stop();
+
+ if (isVisualCharMode() && !focus && !hasThinCursor()) {
+ // Select the character under thick cursor for external operations with text selection.
+ fixExternalCursorPosition(false);
+ } else if (isVisualCharMode() && focus && hasThinCursor()) {
+ // Fix cursor position if changing its shape.
+ // The fix is postponed so context menu action can be finished.
+ m_fixCursorTimer.start();
+ } else {
+ updateCursorShape();
+ }
+}
+
+void FakeVimHandler::Private::fixExternalCursorPosition(bool focus)
+{
+ QTextCursor tc = EDITOR(textCursor());
+ if (tc.anchor() < tc.position()) {
+ tc.movePosition(focus ? Left : Right, KeepAnchor);
+ EDITOR(setTextCursor(tc));
+ }
+
+ setThinCursor(!focus);
+}
+
void FakeVimHandler::Private::enterFakeVim()
{
QTC_ASSERT(!m_inFakeVim, qDebug() << "enterFakeVim() shouldn't be called recursively!"; return);
pullOrCreateBufferData();
- pullCursor();
- if (m_cursor.isNull())
- m_cursor = QTextCursor(document());
-
m_inFakeVim = true;
removeEventFilter();
- updateFirstVisibleLine();
- importSelection();
-
- // Position changed externally, e.g. by code completion.
- if (position() != m_oldInternalPosition) {
- // record external jump to different line
- if (m_oldInternalPosition != -1 && lineForPosition(m_oldInternalPosition) != lineForPosition(position()))
- recordJump(m_oldInternalPosition);
- setTargetColumn();
- if (atEndOfLine() && !isVisualMode() && !isInsertMode())
- moveLeft();
- }
+ pullCursor();
- if (m_fakeEnd)
- moveRight();
+ updateFirstVisibleLine();
}
void FakeVimHandler::Private::leaveFakeVim(bool needUpdate)
@@ -2333,25 +2433,12 @@ void FakeVimHandler::Private::leaveFakeVim(bool needUpdate)
// The command might have destroyed the editor.
if (m_textedit || m_plaintextedit) {
- // We fake vi-style end-of-line behaviour
- m_fakeEnd = atEndOfLine() && g.mode == CommandMode && !isVisualBlockMode()
- && !isVisualCharMode();
-
- //QTC_ASSERT(g.mode == InsertMode || g.mode == ReplaceMode
- // || !atBlockEnd() || block().length() <= 1,
- // qDebug() << "Cursor at EOL after key handler");
- if (m_fakeEnd)
- moveLeft();
-
if (hasConfig(ConfigShowMarks))
updateSelection();
- exportSelection();
- updateCursorShape();
+ updateMiniBuffer();
if (needUpdate) {
- commitCursor();
-
// Move cursor line to middle of screen if it's not visible.
const int line = cursorLine();
if (line < firstVisibleLine() || line > firstVisibleLine() + linesOnScreen())
@@ -2359,6 +2446,8 @@ void FakeVimHandler::Private::leaveFakeVim(bool needUpdate)
else
scrollToLine(firstVisibleLine());
updateScrollOffset();
+
+ commitCursor();
}
installEventFilter();
@@ -2367,6 +2456,11 @@ void FakeVimHandler::Private::leaveFakeVim(bool needUpdate)
m_inFakeVim = false;
}
+void FakeVimHandler::Private::leaveFakeVim(EventResult eventResult)
+{
+ leaveFakeVim(eventResult == EventHandled || eventResult == EventCancelled);
+}
+
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
{
const int key = ev->key();
@@ -2399,7 +2493,6 @@ bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
return false;
}
KEY_DEBUG(" NOT PASSING CTRL KEY");
- //updateMiniBuffer();
return true;
}
@@ -2426,8 +2519,6 @@ EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
// qDebug() << "FINISHED...";
// return EventHandled;
//}
- g.passing = false;
- updateMiniBuffer();
KEY_DEBUG(" PASS TO CORE");
return EventPassedToCore;
}
@@ -2465,98 +2556,37 @@ EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
enterFakeVim();
EventResult result = handleKey(Input(key, mods, ev->text()));
- leaveFakeVim(result == EventHandled);
+ leaveFakeVim(result);
return result;
}
void FakeVimHandler::Private::installEventFilter()
{
- EDITOR(viewport()->installEventFilter(q));
EDITOR(installEventFilter(q));
}
void FakeVimHandler::Private::removeEventFilter()
{
- EDITOR(viewport()->removeEventFilter(q));
EDITOR(removeEventFilter(q));
}
void FakeVimHandler::Private::setupWidget()
{
+ m_cursorNeedsUpdate = true;
+ connect(editor(), SIGNAL(cursorPositionChanged()),
+ SLOT(onCursorPositionChanged()), Qt::UniqueConnection);
+
enterFakeVim();
- resetCommandMode();
+ leaveCurrentMode();
m_wasReadOnly = EDITOR(isReadOnly());
updateEditor();
- importSelection();
- updateMiniBuffer();
- updateCursorShape();
-
- recordJump();
- setTargetColumn();
- if (atEndOfLine() && !isVisualMode() && !isInsertMode())
- moveLeft();
leaveFakeVim();
}
-void FakeVimHandler::Private::exportSelection()
-{
- int pos = position();
- int anc = isVisualMode() ? anchor() : position();
-
- m_oldInternalPosition = pos;
- m_oldInternalAnchor = anc;
-
- if (isVisualMode()) {
- 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 if (!atBlockEnd())
- ++pos;
- // FIXME: After '$' command (i.e. m_visualTargetColumn == -1), end of selected lines
- // should be selected.
- setAnchorAndPosition(anc, pos);
- commitCursor();
- } else if (g.visualMode == VisualLineMode) {
- const int posLine = lineForPosition(pos);
- const int ancLine = lineForPosition(anc);
- if (anc < pos) {
- pos = lastPositionInLine(posLine);
- anc = firstPositionInLine(ancLine);
- } else {
- pos = firstPositionInLine(posLine);
- 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 (g.visualMode == VisualCharMode) {
- if (anc > pos)
- ++anc;
- } else {
- QTC_CHECK(false);
- }
-
- setAnchorAndPosition(anc, pos);
-
- setMark(QLatin1Char('<'), markLessPosition());
- setMark(QLatin1Char('>'), markGreaterPosition());
- } else {
- if (g.subsubmode == SearchSubSubMode && !m_searchCursor.isNull())
- m_cursor = m_searchCursor;
- else
- setAnchorAndPosition(pos, pos);
- }
- m_oldExternalPosition = position();
- m_oldExternalAnchor = anchor();
-}
-
void FakeVimHandler::Private::commitInsertState()
{
if (!isInsertStateValid())
@@ -2571,7 +2601,7 @@ void FakeVimHandler::Private::commitInsertState()
// Escape special characters and spaces inserted by user (not by auto-indentation).
for (int i = lastInsertion.size() - 1; i >= 0; --i) {
const int pos = insertState.pos1 + i;
- const ushort c = document()->characterAt(pos).unicode();
+ const ushort c = characterAt(pos).unicode();
if (c == '<')
lastInsertion.replace(i, 1, _("<LT>"));
else if ((c == ' ' || c == '\t') && insertState.spaces.contains(pos))
@@ -2593,16 +2623,14 @@ void FakeVimHandler::Private::commitInsertState()
void FakeVimHandler::Private::invalidateInsertState()
{
- m_oldInternalPosition = position();
BufferData::InsertState &insertState = m_buffer->insertState;
insertState.pos1 = -1;
- insertState.pos2 = m_oldInternalPosition;
+ insertState.pos2 = position();
insertState.backspaces = 0;
insertState.deletes = 0;
insertState.spaces.clear();
insertState.insertingSpaces = false;
- insertState.textBeforeCursor = textAt(document()->findBlock(m_oldInternalPosition).position(),
- m_oldInternalPosition);
+ insertState.textBeforeCursor = textAt(block().position(), position());
insertState.newLineBefore = false;
insertState.newLineAfter = false;
}
@@ -2627,8 +2655,8 @@ void FakeVimHandler::Private::ensureCursorVisible()
// fix selection so it is outside folded block
int start = qMin(pos, anc);
int end = qMax(pos, anc) + 1;
- QTextBlock block = document()->findBlock(start);
- QTextBlock block2 = document()->findBlock(end);
+ QTextBlock block = blockAt(start);
+ QTextBlock block2 = blockAt(end);
if (!block.isVisible() || !block2.isVisible()) {
// FIXME: Moving cursor left/right or unfolding block immediately after block is folded
// should restore cursor position inside block.
@@ -2654,31 +2682,6 @@ void FakeVimHandler::Private::ensureCursorVisible()
}
}
-void FakeVimHandler::Private::importSelection()
-{
- if (position() == m_oldExternalPosition
- && anchor() == m_oldExternalAnchor) {
- // Undo drawing correction.
- setAnchorAndPosition(m_oldInternalAnchor, m_oldInternalPosition);
- } else {
- // Import new selection.
- Qt::KeyboardModifiers mods = QApplication::keyboardModifiers();
- if (m_cursor.hasSelection()) {
- if (mods & HostOsInfo::controlModifier())
- g.visualMode = VisualBlockMode;
- else if (mods & Qt::AltModifier)
- g.visualMode = VisualBlockMode;
- else if (mods & Qt::ShiftModifier)
- g.visualMode = VisualLineMode;
- else
- g.visualMode = VisualCharMode;
- m_buffer->lastVisualMode = g.visualMode;
- } else {
- g.visualMode = NoVisualMode;
- }
- }
-}
-
void FakeVimHandler::Private::updateEditor()
{
const int charWidth = QFontMetrics(EDITOR(font())).width(QLatin1Char(' '));
@@ -2688,17 +2691,16 @@ void FakeVimHandler::Private::updateEditor()
void FakeVimHandler::Private::restoreWidget(int tabSize)
{
- //clearMessage();
- //updateMiniBuffer();
//EDITOR(removeEventFilter(q));
//EDITOR(setReadOnly(m_wasReadOnly));
const int charWidth = QFontMetrics(EDITOR(font())).width(QLatin1Char(' '));
EDITOR(setTabStopWidth(charWidth * tabSize));
g.visualMode = NoVisualMode;
// Force "ordinary" cursor.
- EDITOR(setOverwriteMode(false));
+ setThinCursor();
updateSelection();
updateHighlights();
+ disconnect(editor(), SIGNAL(cursorPositionChanged()), this, SLOT(onCursorPositionChanged()));
}
EventResult FakeVimHandler::Private::handleKey(const Input &input)
@@ -2795,7 +2797,6 @@ void FakeVimHandler::Private::prependMapping(const Inputs &inputs)
clearPendingInput();
g.pendingInput.append(inputs);
showMessage(MessageError, Tr::tr("Recursive mapping"));
- updateMiniBuffer();
return;
}
@@ -2843,7 +2844,6 @@ void FakeVimHandler::Private::endMapping()
g.mapStates.pop_back();
if (g.mapStates.isEmpty())
g.commandBuffer.setHistoryAutoSave(true);
- updateMiniBuffer();
}
bool FakeVimHandler::Private::canHandleMapping()
@@ -2877,17 +2877,15 @@ void FakeVimHandler::Private::waitForMapping()
g.currentCommand.clear();
foreach (const Input &input, g.currentMap.currentInputs())
g.currentCommand.append(input.toString());
- updateMiniBuffer();
// wait for user to press any key or trigger complete mapping after interval
- g.inputTimer = startTimer(1000);
+ m_inputTimer.start();
}
EventResult FakeVimHandler::Private::stopWaitForMapping(bool hasInput)
{
- if (g.inputTimer != -1) {
- killTimer(g.inputTimer);
- g.inputTimer = -1;
+ if (!hasInput || m_inputTimer.isActive()) {
+ m_inputTimer.stop();
g.currentCommand.clear();
if (!hasInput && !expandCompleteMapping()) {
// Cannot complete mapping so handle the first input from it as default command.
@@ -2898,15 +2896,6 @@ EventResult FakeVimHandler::Private::stopWaitForMapping(bool hasInput)
return EventHandled;
}
-void FakeVimHandler::Private::timerEvent(QTimerEvent *ev)
-{
- if (ev->timerId() == g.inputTimer) {
- enterFakeVim();
- EventResult result = handleKey(Input());
- leaveFakeVim(result == EventHandled);
- }
-}
-
void FakeVimHandler::Private::stopIncrementalFind()
{
if (g.findPending) {
@@ -2949,11 +2938,19 @@ bool FakeVimHandler::Private::isInputCount(const Input &input) const
return input.isDigit() && (!input.is('0') || g.mvcount > 0);
}
+bool FakeVimHandler::Private::atEmptyLine(int pos) const
+{
+ return blockAt(pos).length() == 1;
+}
+
bool FakeVimHandler::Private::atEmptyLine(const QTextCursor &tc) const
{
- if (tc.isNull())
- return atEmptyLine(m_cursor);
- return tc.block().length() == 1;
+ return atEmptyLine(tc.position());
+}
+
+bool FakeVimHandler::Private::atEmptyLine() const
+{
+ return atEmptyLine(position());
}
bool FakeVimHandler::Private::atBoundary(bool end, bool simple, bool onlyWords,
@@ -2964,8 +2961,8 @@ bool FakeVimHandler::Private::atBoundary(bool end, bool simple, bool onlyWords,
if (atEmptyLine(tc))
return true;
int pos = tc.position();
- QChar c1 = document()->characterAt(pos);
- QChar c2 = document()->characterAt(pos + (end ? 1 : -1));
+ QChar c1 = characterAt(pos);
+ QChar c2 = characterAt(pos + (end ? 1 : -1));
int thisClass = charClass(c1, simple);
return (!onlyWords || thisClass != 0)
&& (c2.isNull() || c2 == ParagraphSeparator || thisClass != charClass(c2, simple));
@@ -2988,7 +2985,7 @@ bool FakeVimHandler::Private::atWordEnd(bool simple, const QTextCursor &tc) cons
bool FakeVimHandler::Private::isFirstNonBlankOnLine(int pos)
{
- for (int i = document()->findBlock(pos).position(); i < pos; ++i) {
+ for (int i = blockAt(pos).position(); i < pos; ++i) {
if (!document()->characterAt(i).isSpace())
return false;
}
@@ -3011,6 +3008,8 @@ void FakeVimHandler::Private::pushUndoState(bool overwrite)
pos = qMin(pos, anchor());
if (isVisualLineMode())
pos = firstPositionInLine(lineForPosition(pos));
+ else if (isVisualBlockMode())
+ pos = blockAt(pos).position() + qMin(columnAt(anchor()), columnAt(position()));
} else if (g.movetype == MoveLineWise && hasConfig(ConfigStartOfLine)) {
QTextCursor tc = m_cursor;
if (g.submode == ShiftLeftSubMode || g.submode == ShiftRightSubMode
@@ -3023,14 +3022,13 @@ void FakeVimHandler::Private::pushUndoState(bool overwrite)
}
}
+ CursorPosition lastChangePosition(document(), pos);
+ setMark(QLatin1Char('.'), lastChangePosition);
+
m_buffer->redo.clear();
- m_buffer->lastChangePosition = CursorPosition(document(), pos);
- if (isVisualMode()) {
- setMark(QLatin1Char('<'), markLessPosition());
- setMark(QLatin1Char('>'), markGreaterPosition());
- }
- m_buffer->undoState = State(revision(), m_buffer->lastChangePosition, m_buffer->marks,
- m_buffer->lastVisualMode, m_buffer->lastVisualModeInverted);
+ m_buffer->undoState = State(
+ revision(), lastChangePosition, m_buffer->marks,
+ m_buffer->lastVisualMode, m_buffer->lastVisualModeInverted);
}
void FakeVimHandler::Private::moveDown(int n)
@@ -3089,6 +3087,9 @@ void FakeVimHandler::Private::moveDownVisually(int n)
m_targetColumnWrapped = targetColumn;
}
+ if (!isInsertMode() && atEndOfLine())
+ m_cursor.movePosition(Left, KeepAnchor);
+
updateScrollOffset();
}
@@ -3106,11 +3107,112 @@ void FakeVimHandler::Private::movePageDown(int count)
scrollToLine(qMax(0, cursorLine() - screenLines + 1));
}
+void FakeVimHandler::Private::commitCursor()
+{
+ QTextCursor tc = m_cursor;
+
+ if (isVisualMode()) {
+ int pos = tc.position();
+ int anc = tc.anchor();
+
+ if (isVisualBlockMode()) {
+ const int col1 = columnAt(anc);
+ const int col2 = columnAt(pos);
+ if (col1 > col2)
+ ++anc;
+ else if (!tc.atBlockEnd())
+ ++pos;
+ // FIXME: After '$' command (i.e. m_visualTargetColumn == -1), end of selected lines
+ // should be selected.
+ } else if (isVisualLineMode()) {
+ const int posLine = lineForPosition(pos);
+ const int ancLine = lineForPosition(anc);
+ if (anc < pos) {
+ pos = lastPositionInLine(posLine);
+ anc = firstPositionInLine(ancLine);
+ } else {
+ pos = firstPositionInLine(posLine);
+ anc = lastPositionInLine(ancLine) + 1;
+ }
+ // putting cursor on folded line will unfold the line, so move the cursor a bit
+ if (!blockAt(pos).isVisible())
+ ++pos;
+ } else if (isVisualCharMode()) {
+ if (anc > pos)
+ ++anc;
+ else if (!editor()->hasFocus() || isCommandLineMode())
+ m_fixCursorTimer.start();
+ } else {
+ QTC_CHECK(false);
+ }
+
+ tc.setPosition(anc);
+ tc.setPosition(pos, KeepAnchor);
+ } else if (g.subsubmode == SearchSubSubMode && !m_searchCursor.isNull()) {
+ tc = m_searchCursor;
+ } else {
+ tc.clearSelection();
+ }
+
+ updateCursorShape();
+
+ if (isVisualBlockMode()) {
+ emit q->requestSetBlockSelection(tc);
+ } else {
+ emit q->requestDisableBlockSelection();
+ if (editor())
+ EDITOR(setTextCursor(tc));
+ }
+}
+
+void FakeVimHandler::Private::pullCursor()
+{
+ if (!m_cursorNeedsUpdate)
+ return;
+
+ m_cursorNeedsUpdate = false;
+
+ QTextCursor oldCursor = m_cursor;
+
+ bool visualBlockMode = false;
+ emit q->requestHasBlockSelection(&visualBlockMode);
+
+ if (visualBlockMode)
+ q->requestBlockSelection(&m_cursor);
+ else if (editor())
+ m_cursor = EDITOR(textCursor());
+
+ // Cursor should be always valid.
+ if (m_cursor.isNull())
+ m_cursor = QTextCursor(document());
+
+ if (visualBlockMode)
+ g.visualMode = VisualBlockMode;
+ else if (m_cursor.hasSelection())
+ g.visualMode = VisualCharMode;
+ else
+ g.visualMode = NoVisualMode;
+
+ // Keep visually the text selection same.
+ // With thick text cursor, the character under cursor is treated as selected.
+ if (isVisualCharMode() && hasThinCursor())
+ moveLeft();
+
+ // Cursor position can be after the end of line only in some modes.
+ if (atEndOfLine() && !isVisualMode() && !isInsertMode())
+ moveLeft();
+
+ // Record external jump to different line.
+ if (lineForPosition(position()) != lineForPosition(oldCursor.position()))
+ recordJump(oldCursor.position());
+
+ setTargetColumn();
+}
+
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)
@@ -3122,23 +3224,39 @@ bool FakeVimHandler::Private::moveToNextParagraph(int count)
break;
while (block.isValid() && block.length() == 1)
block = forward ? block.next() : block.previous();
+ if (!block.isValid())
+ break;
}
}
- if (repeat == 0)
- setPosition(block.position());
- else if (repeat == 1)
- setPosition(forward ? lastPositionInDocument() : 0);
- else
+ if (!block.isValid())
+ --repeat;
+
+ if (repeat > 0)
return false;
- recordJump(pos);
- setTargetColumn();
- g.movetype = MoveExclusive;
+ if (block.isValid())
+ setPosition(block.position());
+ else
+ setPosition(forward ? lastPositionInDocument() : 0);
return true;
}
+void FakeVimHandler::Private::moveToParagraphStartOrEnd(int direction)
+{
+ bool emptyLine = atEmptyLine();
+ int oldPos = -1;
+
+ while (atEmptyLine() == emptyLine && oldPos != position()) {
+ oldPos = position();
+ moveDown(direction);
+ }
+
+ if (oldPos != position())
+ moveUp(direction);
+}
+
void FakeVimHandler::Private::moveToEndOfLine()
{
// Additionally select (in visual mode) or apply current command on hidden lines following
@@ -3174,6 +3292,7 @@ void FakeVimHandler::Private::moveBehindEndOfLine()
int pos = qMin(block().position() + block().length() - 1,
lastPositionInDocument() + 1);
setPosition(pos);
+ setTargetColumn();
}
void FakeVimHandler::Private::moveToStartOfLine()
@@ -3195,12 +3314,12 @@ void FakeVimHandler::Private::fixSelection()
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()) {
+ if (characterAtCursor() == ParagraphSeparator) {
+ if (!atEmptyLine() && !atDocumentEnd()) {
setPosition(position() + 1);
return;
}
- } else if (document()->characterAt(anchor()) == ParagraphSeparator) {
+ } else if (characterAt(anchor()) == ParagraphSeparator) {
QTextCursor tc = m_cursor;
tc.setPosition(anchor());
if (!atEmptyLine(tc)) {
@@ -3303,26 +3422,25 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
|| g.submode == YankSubMode
|| g.submode == InvertCaseSubMode
|| g.submode == DownCaseSubMode
- || g.submode == UpCaseSubMode) {
+ || g.submode == UpCaseSubMode
+ || g.submode == IndentSubMode
+ || g.submode == ShiftLeftSubMode
+ || g.submode == ShiftRightSubMode)
+ {
fixSelection();
- if (g.submode != InvertCaseSubMode
- && g.submode != DownCaseSubMode
- && g.submode != UpCaseSubMode) {
+ if (g.submode == ChangeSubMode
+ || g.submode == DeleteSubMode
+ || g.submode == YankSubMode)
+ {
yankText(currentRange(), m_register);
- if (g.movetype == MoveLineWise)
- setRegister(m_register, registerContents(m_register), RangeLineMode);
}
-
- m_positionPastEnd = m_anchorPastEnd = false;
}
- QString dotCommand;
if (g.submode == ChangeSubMode) {
pushUndoState(false);
beginEditBlock();
removeText(currentRange());
- dotCommand = _("c");
if (g.movetype == MoveLineWise)
insertAutomaticIndentation(true);
endEditBlock();
@@ -3336,13 +3454,8 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
removeText(Range(pos, pos + 1));
else
removeText(currentRange());
- dotCommand = _("d");
if (g.movetype == MoveLineWise)
handleStartOfLine();
- if (atEndOfLine())
- moveLeft();
- else
- setTargetColumn();
endEditBlock();
} else if (g.submode == YankSubMode) {
bool isVisualModeYank = isVisualMode();
@@ -3350,7 +3463,7 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
const QTextCursor tc = m_cursor;
if (g.rangemode == RangeBlockMode) {
const int pos1 = tc.block().position();
- const int pos2 = document()->findBlock(tc.anchor()).position();
+ const int pos2 = blockAt(tc.anchor()).position();
const int col = qMin(tc.position() - pos1, tc.anchor() - pos2);
setPosition(qMin(pos1, pos2) + col);
} else {
@@ -3358,6 +3471,8 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
if (g.rangemode == RangeLineMode) {
if (isVisualModeYank)
moveToStartOfLine();
+ else
+ moveToTargetColumn();
}
}
setTargetColumn();
@@ -3365,16 +3480,12 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
|| g.submode == UpCaseSubMode
|| g.submode == DownCaseSubMode) {
beginEditBlock();
- if (g.submode == InvertCaseSubMode) {
+ if (g.submode == InvertCaseSubMode)
invertCase(currentRange());
- dotCommand = QString::fromLatin1("g~");
- } else if (g.submode == DownCaseSubMode) {
+ else if (g.submode == DownCaseSubMode)
downCase(currentRange());
- dotCommand = QString::fromLatin1("gu");
- } else if (g.submode == UpCaseSubMode) {
+ else if (g.submode == UpCaseSubMode)
upCase(currentRange());
- dotCommand = QString::fromLatin1("gU");
- }
if (g.movetype == MoveLineWise)
handleStartOfLine();
endEditBlock();
@@ -3383,50 +3494,45 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
|| g.submode == ShiftLeftSubMode) {
recordJump();
pushUndoState(false);
- if (g.submode == IndentSubMode) {
+ if (g.submode == IndentSubMode)
indentSelectedText();
- dotCommand = _("=");
- } else if (g.submode == ShiftRightSubMode) {
+ else if (g.submode == ShiftRightSubMode)
shiftRegionRight(1);
- dotCommand = _(">");
- } else if (g.submode == ShiftLeftSubMode) {
+ else if (g.submode == ShiftLeftSubMode)
shiftRegionLeft(1);
- dotCommand = _("<");
- }
}
- if (!dotCommand.isEmpty() && !dotCommandMovement.isEmpty())
- setDotCommand(dotCommand + dotCommandMovement);
+ if (!dotCommandMovement.isEmpty()) {
+ const QString dotCommand = dotCommandFromSubMode(g.submode);
+ if (!dotCommand.isEmpty())
+ setDotCommand(dotCommand + dotCommandMovement);
+ }
// Change command continues in insert mode.
if (g.submode == ChangeSubMode) {
- clearCommandMode();
+ clearCurrentMode();
enterInsertMode();
} else {
- resetCommandMode();
+ leaveCurrentMode();
}
}
-void FakeVimHandler::Private::resetCommandMode()
+void FakeVimHandler::Private::leaveCurrentMode()
{
- if (g.returnToMode == CommandMode) {
+ if (isVisualMode())
+ enterCommandMode(g.returnToMode);
+ else if (g.returnToMode == CommandMode)
enterCommandMode();
- } else {
- clearCommandMode();
- const QString lastInsertion = m_buffer->lastInsertion;
- if (g.returnToMode == InsertMode)
- enterInsertMode();
- else
- enterReplaceMode();
- moveToTargetColumn();
- invalidateInsertState();
- m_buffer->lastInsertion = lastInsertion;
- }
+ else if (g.returnToMode == InsertMode)
+ enterInsertMode();
+ else
+ enterReplaceMode();
+
if (isNoVisualMode())
setAnchor();
}
-void FakeVimHandler::Private::clearCommandMode()
+void FakeVimHandler::Private::clearCurrentMode()
{
g.submode = NoSubMode;
g.subsubmode = NoSubSubMode;
@@ -3575,25 +3681,20 @@ void FakeVimHandler::Private::passShortcuts(bool enable)
bool FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
{
- //const int key = input.key;
bool handled = true;
+
if (g.subsubmode == FtSubSubMode) {
g.semicolonType = g.subsubdata;
g.semicolonKey = input.text();
- bool valid = handleFfTt(g.semicolonKey);
+ handled = handleFfTt(g.semicolonKey);
g.subsubmode = NoSubSubMode;
- if (!valid) {
- g.submode = NoSubMode;
- resetCommandMode();
- handled = false;
- } else {
+ if (handled) {
finishMovement(QString::fromLatin1("%1%2%3")
.arg(count())
.arg(g.semicolonType.text())
.arg(g.semicolonKey));
}
} else if (g.subsubmode == TextObjectSubSubMode) {
- bool ok = true;
if (input.is('w'))
selectWordTextObject(g.subsubdata.is('i'));
else if (input.is('W'))
@@ -3603,38 +3704,32 @@ bool FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
else if (input.is('p'))
selectParagraphTextObject(g.subsubdata.is('i'));
else if (input.is('[') || input.is(']'))
- ok = selectBlockTextObject(g.subsubdata.is('i'), '[', ']');
+ handled = selectBlockTextObject(g.subsubdata.is('i'), '[', ']');
else if (input.is('(') || input.is(')') || input.is('b'))
- ok = selectBlockTextObject(g.subsubdata.is('i'), '(', ')');
+ handled = selectBlockTextObject(g.subsubdata.is('i'), '(', ')');
else if (input.is('<') || input.is('>'))
- ok = selectBlockTextObject(g.subsubdata.is('i'), '<', '>');
+ handled = selectBlockTextObject(g.subsubdata.is('i'), '<', '>');
else if (input.is('{') || input.is('}') || input.is('B'))
- ok = selectBlockTextObject(g.subsubdata.is('i'), '{', '}');
+ handled = selectBlockTextObject(g.subsubdata.is('i'), '{', '}');
else if (input.is('"') || input.is('\'') || input.is('`'))
- ok = selectQuotedStringTextObject(g.subsubdata.is('i'), input.asChar());
+ handled = selectQuotedStringTextObject(g.subsubdata.is('i'), input.asChar());
else
- ok = false;
+ handled = false;
g.subsubmode = NoSubSubMode;
- if (ok) {
+ if (handled) {
finishMovement(QString::fromLatin1("%1%2%3")
.arg(count())
.arg(g.subsubdata.text())
.arg(input.text()));
- } else {
- resetCommandMode();
- handled = false;
}
} else if (g.subsubmode == MarkSubSubMode) {
setMark(input.asChar(), CursorPosition(m_cursor));
g.subsubmode = NoSubSubMode;
} else if (g.subsubmode == BackTickSubSubMode
|| g.subsubmode == TickSubSubMode) {
- if (jumpToMark(input.asChar(), g.subsubmode == BackTickSubSubMode)) {
+ handled = jumpToMark(input.asChar(), g.subsubmode == BackTickSubSubMode);
+ if (handled)
finishMovement();
- } else {
- resetCommandMode();
- handled = false;
- }
g.subsubmode = NoSubSubMode;
} else if (g.subsubmode == ZSubSubMode) {
handled = false;
@@ -3694,7 +3789,6 @@ bool FakeVimHandler::Private::handleCount(const Input &input)
bool FakeVimHandler::Private::handleMovement(const Input &input)
{
bool handled = true;
- QString movement;
int count = this->count();
if (handleCount(input)) {
@@ -3769,31 +3863,34 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
g.movetype = MoveLineWise;
} else if (input.is('|')) {
moveToStartOfLine();
- moveRight(qMin(count, rightDist()) - 1);
- setTargetColumn();
- } else if (input.is('}')) {
- handled = moveToNextParagraph(count);
- } else if (input.is('{')) {
- handled = moveToPreviousParagraph(count);
+ const int column = count - 1;
+ moveRight(qMin(column, rightDist() - 1));
+ m_targetColumn = column;
+ m_visualTargetColumn = column;
+ } else if (input.is('{') || input.is('}')) {
+ const int oldPosition = position();
+ handled = input.is('}')
+ ? moveToNextParagraph(count)
+ : moveToPreviousParagraph(count);
+ if (handled) {
+ recordJump(oldPosition);
+ setTargetColumn();
+ g.movetype = MoveExclusive;
+ }
} else if (input.isReturn()) {
moveToStartOfLine();
moveDown();
moveToFirstNonBlankOnLine();
- g.movetype = MoveLineWise;
} else if (input.is('-')) {
moveToStartOfLine();
moveUp(count);
moveToFirstNonBlankOnLine();
- g.movetype = MoveLineWise;
} else if (input.is('+')) {
moveToStartOfLine();
moveDown(count);
moveToFirstNonBlankOnLine();
- g.movetype = MoveLineWise;
} else if (input.isKey(Key_Home)) {
moveToStartOfLine();
- setTargetColumn();
- movement = _("<HOME>");
} else if (input.is('$') || input.isKey(Key_End)) {
if (g.gflag) {
if (count > 1)
@@ -3805,12 +3902,10 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
moveToEndOfLine();
}
g.movetype = atEmptyLine() ? MoveExclusive : MoveInclusive;
- setTargetColumn();
if (g.submode == NoSubMode)
m_targetColumn = -1;
if (isVisualMode())
m_visualTargetColumn = -1;
- movement = _("$");
} else if (input.is('%')) {
recordJump();
if (g.mvcount == 0) {
@@ -3824,37 +3919,22 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
g.movetype = MoveLineWise;
}
} else if (input.is('b') || input.isShift(Key_Left)) {
- g.movetype = MoveExclusive;
moveToNextWordStart(count, false, false);
- setTargetColumn();
- movement = _("b");
} else if (input.is('B')) {
- g.movetype = MoveExclusive;
moveToNextWordStart(count, true, false);
- setTargetColumn();
} else if (input.is('e') && g.gflag) {
- g.movetype = MoveInclusive;
moveToNextWordEnd(count, false, false);
- setTargetColumn();
} else if (input.is('e') || input.isShift(Key_Right)) {
- g.movetype = MoveInclusive;
moveToNextWordEnd(count, false, true, false);
- setTargetColumn();
- movement = _("e");
} else if (input.is('E') && g.gflag) {
- g.movetype = MoveInclusive;
moveToNextWordEnd(count, true, false);
- setTargetColumn();
} else if (input.is('E')) {
- g.movetype = MoveInclusive;
moveToNextWordEnd(count, true, true, false);
- setTargetColumn();
} else if (input.isControl('e')) {
// FIXME: this should use the "scroll" option, and "count"
if (cursorLineOnScreen() == 0)
moveDown(1);
scrollDown(1);
- movement = _("<C-E>");
} else if (input.is('f')) {
g.subsubmode = FtSubSubMode;
g.movetype = MoveInclusive;
@@ -3888,43 +3968,19 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
} else if (input.is('h') || input.isKey(Key_Left) || input.isBackspace()) {
g.movetype = MoveExclusive;
int n = qMin(count, leftDist());
- if (m_fakeEnd && block().length() > 1)
- ++n;
moveLeft(n);
- setTargetColumn();
- movement = _("h");
} else if (input.is('H')) {
const CursorPosition pos(lineToBlockNumber(lineOnTop(count)), 0);
setCursorPosition(&m_cursor, pos);
handleStartOfLine();
} else if (input.is('j') || input.isKey(Key_Down)
|| input.isControl('j') || input.isControl('n')) {
- if (g.gflag) {
- g.movetype = MoveExclusive;
- moveDownVisually(count);
- movement = _("gj");
- } else {
- g.movetype = MoveLineWise;
- moveDown(count);
- movement = _("j");
- }
+ moveVertically(count);
} else if (input.is('k') || input.isKey(Key_Up) || input.isControl('p')) {
- if (g.gflag) {
- g.movetype = MoveExclusive;
- moveUpVisually(count);
- movement = _("gk");
- } else {
- g.movetype = MoveLineWise;
- moveUp(count);
- movement = _("k");
- }
+ moveVertically(-count);
} else if (input.is('l') || input.isKey(Key_Right) || input.is(' ')) {
g.movetype = MoveExclusive;
- bool pastEnd = count >= rightDist() - 1;
moveRight(qMax(0, qMin(count, rightDist() - (g.submode == NoSubMode))));
- setTargetColumn();
- if (pastEnd && isVisualMode())
- m_visualTargetColumn = -1;
} else if (input.is('L')) {
const CursorPosition pos(lineToBlockNumber(lineOnBottom(count)), 0);
setCursorPosition(&m_cursor, pos);
@@ -3965,19 +4021,16 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
// 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 (g.submode == ChangeSubMode && !document()->characterAt(position()).isSpace()) {
+ if (g.submode == ChangeSubMode && !characterAtCursor().isSpace()) {
moveToWordEnd(count, simple, true);
- 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 (g.submode == DeleteSubMode && count == 1) {
- const QTextBlock currentBlock = document()->findBlock(anchor());
+ const QTextBlock currentBlock = blockAt(anchor());
setPosition(qMin(position(), currentBlock.position() + currentBlock.length()));
}
- g.movetype = MoveExclusive;
}
- setTargetColumn();
} else if (input.is('z')) {
g.movetype = MoveLineWise;
g.subsubmode = ZSubSubMode;
@@ -3988,24 +4041,22 @@ bool FakeVimHandler::Private::handleMovement(const Input &input)
} else if (input.isKey(Key_PageDown) || input.isControl('f')) {
movePageDown(count);
handleStartOfLine();
- movement = _("f");
} else if (input.isKey(Key_PageUp) || input.isControl('b')) {
movePageUp(count);
handleStartOfLine();
- movement = _("b");
} else {
handled = false;
}
if (handled && g.subsubmode == NoSubSubMode) {
if (g.submode == NoSubMode) {
- resetCommandMode();
+ leaveCurrentMode();
} else {
// finish movement for sub modes
const QString dotMovement =
(count > 1 ? QString::number(count) : QString())
+ _(g.gflag ? "g" : "")
- + (movement.isNull() ? QString(input.asChar()) : movement);
+ + input.toString();
finishMovement(dotMovement);
setTargetColumn();
}
@@ -4029,8 +4080,10 @@ EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
handled = handleCommandSubSubMode(input);
} else if (g.submode == NoSubMode) {
handled = handleNoSubMode(input);
- } else if (g.submode == ChangeSubMode || g.submode == DeleteSubMode) {
- handled = handleChangeDeleteSubModes(input);
+ } else if (g.submode == ChangeSubMode
+ || g.submode == DeleteSubMode
+ || g.submode == YankSubMode) {
+ handled = handleChangeDeleteYankSubModes(input);
} else if (g.submode == ReplaceSubMode) {
handled = handleReplaceSubMode(input);
} else if (g.submode == FilterSubMode) {
@@ -4039,8 +4092,6 @@ EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
handled = handleRegisterSubMode(input);
} else if (g.submode == WindowSubMode) {
handled = handleWindowSubMode(input);
- } else if (g.submode == YankSubMode) {
- handled = handleYankSubMode(input);
} else if (g.submode == ZSubMode) {
handled = handleZSubMode(input);
} else if (g.submode == CapitalZSubMode) {
@@ -4068,7 +4119,7 @@ EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
(g.mode == CommandMode && g.submode == NoSubMode && g.subsubmode == NoSubSubMode);
clearCount = clearCount && noMode && !g.gflag;
if (clearCount && clearRegister) {
- resetCommandMode();
+ leaveCurrentMode();
} else {
// Use gflag only for next input.
if (clearGflag)
@@ -4082,8 +4133,10 @@ EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
else
g.currentCommand.append(input.toString());
}
+
+ saveLastVisualMode();
} else {
- resetCommandMode();
+ leaveCurrentMode();
//qDebug() << "IGNORED IN COMMAND MODE: " << key << text
// << " VISUAL: " << g.visualMode;
@@ -4093,8 +4146,6 @@ EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
handled = false;
}
- updateMiniBuffer();
-
m_positionPastEnd = (m_visualTargetColumn == -1) && isVisualMode() && !atEmptyLine();
return handled ? EventHandled : EventCancelled;
@@ -4104,7 +4155,7 @@ bool FakeVimHandler::Private::handleEscape()
{
if (isVisualMode())
leaveVisualMode();
- resetCommandMode();
+ leaveCurrentMode();
return true;
}
@@ -4112,6 +4163,12 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
{
bool handled = true;
+ const int oldRevision = revision();
+ QString dotCommand = visualDotCommand()
+ + _(g.gflag ? "g" : "")
+ + QString::number(count())
+ + input.toString();
+
if (input.is('&')) {
handleExCommand(g.gflag ? _("%s//~/&") : _("s"));
} else if (input.is(':')) {
@@ -4127,41 +4184,35 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
} else if (input.is('.')) {
//qDebug() << "REPEATING" << quoteUnprintable(g.dotCommand) << count()
// << input;
+ dotCommand.clear();
QString savedCommand = g.dotCommand;
g.dotCommand.clear();
beginLargeEditBlock();
replay(savedCommand);
endEditBlock();
- resetCommandMode();
+ leaveCurrentMode();
g.dotCommand = savedCommand;
} else if (input.is('<') || input.is('>') || input.is('=')) {
- if (isNoVisualMode()) {
- if (input.is('<'))
- g.submode = ShiftLeftSubMode;
- else if (input.is('>'))
- g.submode = ShiftRightSubMode;
- else
- g.submode = IndentSubMode;
- setAnchor();
- } else {
+ g.submode = indentModeFromInput(input);
+ if (isVisualMode()) {
leaveVisualMode();
- const int lines = qAbs(lineForPosition(position()) - lineForPosition(anchor())) + 1;
const int repeat = count();
- if (input.is('<'))
+ if (g.submode == ShiftLeftSubMode)
shiftRegionLeft(repeat);
- else if (input.is('>'))
+ else if (g.submode == ShiftRightSubMode)
shiftRegionRight(repeat);
else
indentSelectedText();
- const QString selectDotCommand =
- (lines > 1) ? QString::fromLatin1("V%1j").arg(lines - 1): QString();
- setDotCommand(selectDotCommand + QString::fromLatin1("%1%2%2").arg(repeat).arg(input.raw()));
+ g.submode = NoSubMode;
+ } else {
+ setAnchor();
}
} else if ((!isVisualMode() && input.is('a')) || (isVisualMode() && input.is('A'))) {
if (isVisualMode()) {
+ if (!isVisualBlockMode())
+ dotCommand = QString::number(count()) + _("a");
enterVisualInsertMode(QLatin1Char('A'));
} else {
- setDotCommand(_("%1a"), count());
moveRight(qMin(rightDist(), 1));
breakEditBlock();
enterInsertMode();
@@ -4172,20 +4223,17 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
setAnchor();
enterInsertMode();
setTargetColumn();
- setDotCommand(_("%1A"), count());
} else if (input.isControl('a')) {
- if (changeNumberTextObject(count()))
- setDotCommand(_("%1<c-a>"), count());
- } else if ((input.is('c') || input.is('d')) && isNoVisualMode()) {
+ changeNumberTextObject(count());
+ } else if ((input.is('c') || input.is('d') || input.is('y')) && isNoVisualMode()) {
setAnchor();
g.opcount = g.mvcount;
g.mvcount = 0;
g.rangemode = RangeCharMode;
g.movetype = MoveExclusive;
- g.submode = input.is('c') ? ChangeSubMode : DeleteSubMode;
+ g.submode = changeDeleteYankModeFromInput(input);
} else if ((input.is('c') || input.is('C') || input.is('s') || input.is('R'))
&& (isVisualCharMode() || isVisualLineMode())) {
- setDotCommand(visualDotCommand() + input.asChar());
leaveVisualMode();
g.submode = ChangeSubMode;
finishMovement();
@@ -4193,12 +4241,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
resetCount();
enterVisualInsertMode(input.asChar());
} else if (input.is('C')) {
- setAnchor();
- moveToEndOfLine();
- g.rangemode = RangeCharMode;
- g.submode = ChangeSubMode;
- setDotCommand(QString(QLatin1Char('C')));
- finishMovement();
+ handleAs(_("%1c$"));
} else if (input.isControl('c')) {
if (isNoVisualMode())
showMessage(MessageInfo, Tr::tr("Type Alt-V, Alt-V to quit FakeVim mode."));
@@ -4206,49 +4249,15 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
leaveVisualMode();
} else if ((input.is('d') || input.is('x') || input.isKey(Key_Delete))
&& isVisualMode()) {
- pushUndoState();
- setDotCommand(visualDotCommand() + QLatin1Char('x'));
- if (isVisualCharMode()) {
- leaveVisualMode();
- g.submode = DeleteSubMode;
- finishMovement();
- } else if (isVisualLineMode()) {
- leaveVisualMode();
- yankText(currentRange(), m_register);
- removeText(currentRange());
- handleStartOfLine();
- } else if (isVisualBlockMode()) {
- leaveVisualMode();
- yankText(currentRange(), m_register);
- removeText(currentRange());
- setPosition(qMin(position(), anchor()));
- }
+ cutSelectedText();
} else if (input.is('D') && isNoVisualMode()) {
- pushUndoState();
- if (atEndOfLine())
- moveLeft();
- g.submode = DeleteSubMode;
- g.movetype = MoveInclusive;
- setAnchorAndPosition(position(), lastPositionInLine(cursorLine() + count()));
- setDotCommand(QString(QLatin1Char('D')));
- finishMovement();
- setTargetColumn();
- } else if ((input.is('D') || input.is('X')) &&
- (isVisualCharMode() || isVisualLineMode())) {
- setDotCommand(visualDotCommand() + QLatin1Char('X'));
- leaveVisualMode();
- 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();
- g.rangemode = RangeBlockAndTailMode;
- yankText(currentRange(), m_register);
- removeText(currentRange());
- setPosition(qMin(position(), anchor()));
+ handleAs(_("%1d$"));
+ } else if ((input.is('D') || input.is('X')) && isVisualMode()) {
+ if (isVisualCharMode())
+ toggleVisualMode(VisualLineMode);
+ if (isVisualBlockMode() && input.is('D'))
+ m_visualTargetColumn = -1;
+ cutSelectedText();
} else if (input.isControl('d')) {
const int scrollOffset = windowScrollOffset();
int sline = cursorLine() < scrollOffset ? scrollOffset : cursorLineOnScreen();
@@ -4259,22 +4268,20 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
} else if (!g.gflag && input.is('g')) {
g.gflag = true;
} else if (!isVisualMode() && (input.is('i') || input.isKey(Key_Insert))) {
- setDotCommand(_("%1i"), count());
breakEditBlock();
enterInsertMode();
if (atEndOfLine())
moveLeft();
} else if (input.is('I')) {
if (isVisualMode()) {
+ if (!isVisualBlockMode())
+ dotCommand = QString::number(count()) + _("i");
enterVisualInsertMode(QLatin1Char('I'));
} else {
- if (g.gflag) {
- setDotCommand(_("%1gI"), count());
+ if (g.gflag)
moveToStartOfLine();
- } else {
- setDotCommand(_("%1I"), count());
+ else
moveToFirstNonBlankOnLine();
- }
breakEditBlock();
enterInsertMode();
}
@@ -4287,7 +4294,6 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
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 (!g.gflag && input.is('m')) {
@@ -4301,7 +4307,6 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
m_visualTargetColumn = -1;
} else if (input.is('o') || input.is('O')) {
bool insertAfter = input.is('o');
- setDotCommand(_(insertAfter ? "%1o" : "%1O"), count());
pushUndoState();
// Prepend line only if on the first line and command is 'O'.
@@ -4324,8 +4329,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
m_buffer->insertState.newLineBefore = true;
} else {
moveUp();
- m_oldInternalPosition = position();
- m_buffer->insertState.pos1 = m_oldInternalPosition;
+ m_buffer->insertState.pos1 = position();
m_buffer->insertState.newLineAfter = true;
}
setTargetColumn();
@@ -4343,7 +4347,6 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
} else if (input.is('p') || input.is('P') || input.isShift(Qt::Key_Insert)) {
pasteText(!input.is('P'));
setTargetColumn();
- setDotCommand(_("%1p"), count());
finishMovement();
} else if (input.is('q')) {
if (g.isRecording) {
@@ -4362,32 +4365,14 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
breakEditBlock();
enterReplaceMode();
} else if (input.isControl('r')) {
+ dotCommand.clear();
int repeat = count();
while (--repeat >= 0)
redo();
} else if (input.is('s')) {
- pushUndoState();
- leaveVisualMode();
- if (atEndOfLine())
- moveLeft();
- setAnchor();
- moveRight(qMin(count(), rightDist()));
- setDotCommand(_("%1s"), count());
- g.submode = ChangeSubMode;
- g.movetype = MoveExclusive;
- finishMovement();
+ handleAs(_("c%1l"));
} else if (input.is('S')) {
- g.movetype = MoveLineWise;
- pushUndoState();
- if (!isVisualMode()) {
- const int line = cursorLine() + 1;
- const int anc = firstPositionInLine(line);
- const int pos = lastPositionInLine(line + count() - 1);
- setAnchorAndPosition(anc, pos);
- }
- setDotCommand(_("%1S"), count());
- g.submode = ChangeSubMode;
- finishMovement();
+ handleAs(_("%1cc"));
} else if (g.gflag && input.is('t')) {
handleExCommand(_("tabnext"));
} else if (g.gflag && input.is('T')) {
@@ -4395,6 +4380,7 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
} else if (input.isControl('t')) {
handleExCommand(_("pop"));
} else if (!g.gflag && input.is('u') && !isVisualMode()) {
+ dotCommand.clear();
int repeat = count();
while (--repeat >= 0)
undo();
@@ -4405,13 +4391,15 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
handleStartOfLine();
scrollToLine(cursorLine() - sline);
} else if (g.gflag && input.is('v')) {
- if (m_buffer->lastVisualMode != NoVisualMode) {
+ if (isNoVisualMode()) {
CursorPosition from = markLessPosition();
CursorPosition to = markGreaterPosition();
+ if (m_buffer->lastVisualModeInverted)
+ std::swap(from, to);
toggleVisualMode(m_buffer->lastVisualMode);
- setCursorPosition(m_buffer->lastVisualModeInverted ? to : from);
+ setCursorPosition(from);
setAnchor();
- setCursorPosition(m_buffer->lastVisualModeInverted ? from : to);
+ setCursorPosition(to);
setTargetColumn();
}
} else if (input.is('v')) {
@@ -4422,35 +4410,19 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
toggleVisualMode(VisualBlockMode);
} else if (input.isControl('w')) {
g.submode = WindowSubMode;
- } else if (input.is('x') && isNoVisualMode()) { // = _("dl")
- g.movetype = MoveExclusive;
- g.submode = DeleteSubMode;
- const int n = qMin(count(), rightDist());
- setAnchorAndPosition(position(), position() + n);
- setDotCommand(_("%1x"), count());
- finishMovement();
+ } else if (input.is('x') && isNoVisualMode()) {
+ handleAs(_("%1dl"));
} else if (input.isControl('x')) {
- if (changeNumberTextObject(-count()))
- setDotCommand(_("%1<c-x>"), count());
+ changeNumberTextObject(-count());
} else if (input.is('X')) {
- if (leftDist() > 0) {
- setAnchor();
- moveLeft(qMin(count(), leftDist()));
- yankText(currentRange(), m_register);
- removeText(currentRange());
- }
+ handleAs(_("%1dh"));
} else if (input.is('Y') && isNoVisualMode()) {
- handleYankSubMode(Input(QLatin1Char('y')));
+ handleAs(_("%1yy"));
} else if (input.isControl('y')) {
// FIXME: this should use the "scroll" option, and "count"
if (cursorLineOnScreen() == linesOnScreen() - 1)
moveUp(1);
scrollUp(1);
- } else if (input.is('y') && isNoVisualMode()) {
- setAnchor();
- g.rangemode = RangeCharMode;
- g.movetype = MoveExclusive;
- g.submode = YankSubMode;
} else if (input.is('y') && isVisualCharMode()) {
g.rangemode = RangeCharMode;
g.movetype = MoveInclusive;
@@ -4474,48 +4446,18 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
g.submode = CapitalZSubMode;
} else if ((input.is('~') || input.is('u') || input.is('U'))) {
g.movetype = MoveExclusive;
+ g.submode = letterCaseModeFromInput(input);
pushUndoState();
if (isVisualMode()) {
- setDotCommand(visualDotCommand() + QString::number(count()) + input.raw());
- if (isVisualLineMode())
- g.rangemode = RangeLineMode;
- else if (isVisualBlockMode())
- g.rangemode = RangeBlockMode;
leaveVisualMode();
- if (input.is('~'))
- g.submode = InvertCaseSubMode;
- else if (input.is('u'))
- g.submode = DownCaseSubMode;
- else if (input.is('U'))
- g.submode = UpCaseSubMode;
finishMovement();
- } else if (g.gflag || (input.is('~') && hasConfig(ConfigTildeOp))) {
+ } else if (g.gflag || (g.submode == InvertCaseSubMode && hasConfig(ConfigTildeOp))) {
if (atEndOfLine())
moveLeft();
setAnchor();
- if (input.is('~'))
- g.submode = InvertCaseSubMode;
- else if (input.is('u'))
- g.submode = DownCaseSubMode;
- else if (input.is('U'))
- g.submode = UpCaseSubMode;
} else {
- beginEditBlock();
- if (atEndOfLine())
- moveLeft();
- setAnchor();
- moveRight(qMin(count(), rightDist()));
- if (input.is('~')) {
- const int pos = position();
- invertCase(currentRange());
- setPosition(pos);
- } else if (input.is('u')) {
- downCase(currentRange());
- } else if (input.is('U')) {
- upCase(currentRange());
- }
- setDotCommand(QString::fromLatin1("%1%2").arg(count()).arg(input.raw()));
- endEditBlock();
+ const QString movementCommand = QString::fromLatin1("%1l%1l").arg(count());
+ handleAs(_("g") + input.toString() + movementCommand);
}
} else if (input.is('@')) {
g.submode = MacroExecuteSubMode;
@@ -4529,57 +4471,66 @@ bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
handleExCommand(_("tag"));
} else if (handleMovement(input)) {
// movement handled
+ dotCommand.clear();
} else {
handled = false;
}
+ // Set dot command if the current input changed document or entered insert mode.
+ if (handled && !dotCommand.isEmpty() && (oldRevision != revision() || isInsertMode()))
+ setDotCommand(dotCommand);
+
return handled;
}
-bool FakeVimHandler::Private::handleChangeDeleteSubModes(const Input &input)
+bool FakeVimHandler::Private::handleChangeDeleteYankSubModes(const Input &input)
{
- bool handled = false;
+ if (g.submode != changeDeleteYankModeFromInput(input))
+ return false;
- if ((g.submode == ChangeSubMode && input.is('c'))
- || (g.submode == DeleteSubMode && input.is('d'))) {
- g.movetype = MoveLineWise;
+ handleChangeDeleteYankSubModes();
+
+ return true;
+}
+
+void FakeVimHandler::Private::handleChangeDeleteYankSubModes()
+{
+ g.movetype = MoveLineWise;
+
+ const QString dotCommand = dotCommandFromSubMode(g.submode);
+
+ if (!dotCommand.isEmpty())
pushUndoState();
- const int anc = firstPositionInLine(cursorLine() + 1);
- moveDown(count() - 1);
- const int pos = lastPositionInLine(cursorLine() + 1);
- setAnchorAndPosition(anc, pos);
- if (g.submode == ChangeSubMode)
- setDotCommand(_("%1cc"), count());
- else
- setDotCommand(_("%1dd"), count());
- finishMovement();
- g.submode = NoSubMode;
- handled = true;
- }
- return handled;
+ const int anc = firstPositionInLine(cursorLine() + 1);
+ moveDown(count() - 1);
+ const int pos = lastPositionInLine(cursorLine() + 1);
+ setAnchorAndPosition(anc, pos);
+
+ if (!dotCommand.isEmpty())
+ setDotCommand(QString::fromLatin1("%2%1%1").arg(dotCommand), count());
+
+ finishMovement();
+
+ g.submode = NoSubMode;
}
bool FakeVimHandler::Private::handleReplaceSubMode(const Input &input)
{
bool handled = true;
- setDotCommand(visualDotCommand() + QLatin1Char('r') + input.asChar());
+ const QChar c = input.asChar();
+ setDotCommand(visualDotCommand() + QLatin1Char('r') + c);
if (isVisualMode()) {
pushUndoState();
- if (isVisualLineMode())
- g.rangemode = RangeLineMode;
- else if (isVisualBlockMode())
- g.rangemode = RangeBlockMode;
- else
- g.rangemode = RangeCharMode;
leaveVisualMode();
Range range = currentRange();
if (g.rangemode == RangeCharMode)
++range.endPos;
- Transformation tr =
- &FakeVimHandler::Private::replaceByCharTransform;
- transformText(range, tr, input.asChar());
+ // Replace each character but preserve lines.
+ transformText(range, [&c](const QString &text) {
+ return QString(text).replace(QRegExp(_("[^\\n]")), c);
+ });
} else if (count() <= rightDist()) {
pushUndoState();
setAnchor();
@@ -4591,7 +4542,7 @@ bool FakeVimHandler::Private::handleReplaceSubMode(const Input &input)
insertText(QString::fromLatin1("\n"));
endEditBlock();
} else {
- replaceText(range, QString(count(), input.asChar()));
+ replaceText(range, QString(count(), c));
moveRight(count() - 1);
}
setTargetColumn();
@@ -4617,7 +4568,6 @@ bool FakeVimHandler::Private::handleRegisterSubMode(const Input &input)
QChar reg = input.asChar();
if (QString::fromLatin1("*+.%#:-\"").contains(reg) || reg.isLetterOrNumber()) {
m_register = reg.unicode();
- g.rangemode = RangeLineMode;
handled = true;
}
g.submode = NoSubMode;
@@ -4627,40 +4577,36 @@ bool FakeVimHandler::Private::handleRegisterSubMode(const Input &input)
bool FakeVimHandler::Private::handleShiftSubMode(const Input &input)
{
- bool handled = false;
- 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;
- g.submode = NoSubMode;
- }
- return handled;
+ if (g.submode != indentModeFromInput(input))
+ return false;
+
+ g.movetype = MoveLineWise;
+ pushUndoState();
+ moveDown(count() - 1);
+ setDotCommand(QString::fromLatin1("%2%1%1").arg(input.asChar()), count());
+ finishMovement();
+ g.submode = NoSubMode;
+
+ return true;
}
bool FakeVimHandler::Private::handleChangeCaseSubMode(const Input &input)
{
- bool handled = false;
- if ((g.submode == InvertCaseSubMode && input.is('~'))
- || (g.submode == DownCaseSubMode && input.is('u'))
- || (g.submode == UpCaseSubMode && input.is('U'))) {
- if (!isFirstNonBlankOnLine(position())) {
- moveToStartOfLine();
- moveToFirstNonBlankOnLine();
- }
- setTargetColumn();
- pushUndoState();
- setAnchor();
- setPosition(lastPositionInLine(cursorLine() + count()) + 1);
- finishMovement(QString::fromLatin1("%1%2").arg(count()).arg(input.raw()));
- handled = true;
- g.submode = NoSubMode;
+ if (g.submode != letterCaseModeFromInput(input))
+ return false;
+
+ if (!isFirstNonBlankOnLine(position())) {
+ moveToStartOfLine();
+ moveToFirstNonBlankOnLine();
}
- return handled;
+ setTargetColumn();
+ pushUndoState();
+ setAnchor();
+ setPosition(lastPositionInLine(cursorLine() + count()) + 1);
+ finishMovement(QString::fromLatin1("%1%2").arg(count()).arg(input.raw()));
+ g.submode = NoSubMode;
+
+ return true;
}
bool FakeVimHandler::Private::handleWindowSubMode(const Input &input)
@@ -4669,26 +4615,12 @@ bool FakeVimHandler::Private::handleWindowSubMode(const Input &input)
return true;
leaveVisualMode();
+ leaveCurrentMode();
emit q->windowCommandRequested(input.toString(), count());
- g.submode = NoSubMode;
return true;
}
-bool FakeVimHandler::Private::handleYankSubMode(const Input &input)
-{
- bool handled = false;
- if (input.is('y')) {
- g.movetype = MoveLineWise;
- int endPos = firstPositionInLine(lineForPosition(position()) + count() - 1);
- Range range(position(), endPos, RangeLineMode);
- yankText(range, m_register);
- g.submode = NoSubMode;
- handled = true;
- }
- return handled;
-}
-
bool FakeVimHandler::Private::handleZSubMode(const Input &input)
{
bool handled = true;
@@ -4787,12 +4719,8 @@ EventResult FakeVimHandler::Private::handleInsertOrReplaceMode(const Input &inpu
invalidateInsertState();
breakEditBlock();
m_visualBlockInsert = NoneBlockInsertMode;
- } else if (m_oldInternalPosition == position()) {
- setTargetColumn();
}
- updateMiniBuffer();
-
// We don't want fancy stuff in insert mode.
return EventHandled;
}
@@ -4806,10 +4734,8 @@ void FakeVimHandler::Private::handleReplaceMode(const Input &input)
g.dotCommand.append(m_buffer->lastInsertion + _("<ESC>"));
} else if (input.isKey(Key_Left)) {
moveLeft();
- setTargetColumn();
} else if (input.isKey(Key_Right)) {
moveRight();
- setTargetColumn();
} else if (input.isKey(Key_Up)) {
moveUp();
} else if (input.isKey(Key_Down)) {
@@ -4828,6 +4754,7 @@ void FakeVimHandler::Private::handleReplaceMode(const Input &input)
const QString text = input.text();
setAnchor();
insertText(text);
+ setTargetColumn();
endEditBlock();
}
}
@@ -4868,7 +4795,7 @@ void FakeVimHandler::Private::finishInsertMode()
CursorPosition pos(lastAnchor.line, insertColumn);
if (change)
- pos.column = m_buffer->insertState.pos1 - document()->findBlock(m_buffer->insertState.pos1).position();
+ pos.column = columnAt(m_buffer->insertState.pos1);
// Cursor position after block insert is on the first selected line,
// last selected column for 's' command, otherwise first selected column.
@@ -4911,8 +4838,8 @@ void FakeVimHandler::Private::finishInsertMode()
m_buffer->lastInsertion.remove(0, m_buffer->lastInsertion.indexOf(QLatin1Char('\n')) + 1);
g.dotCommand.append(m_buffer->lastInsertion + _("<ESC>"));
- enterCommandMode();
setTargetColumn();
+ enterCommandMode();
}
void FakeVimHandler::Private::handleInsertMode(const Input &input)
@@ -4991,10 +4918,8 @@ void FakeVimHandler::Private::handleInsertMode(const Input &input)
g.mode = ReplaceMode;
} else if (input.isKey(Key_Left)) {
moveLeft();
- setTargetColumn();
} else if (input.isControl(Key_Left)) {
moveToNextWordStart(1, false, false);
- setTargetColumn();
} else if (input.isKey(Key_Down)) {
g.submode = NoSubMode;
moveDown();
@@ -5003,17 +4928,13 @@ void FakeVimHandler::Private::handleInsertMode(const Input &input)
moveUp();
} else if (input.isKey(Key_Right)) {
moveRight();
- setTargetColumn();
} else if (input.isControl(Key_Right)) {
moveToNextWordStart(1, false, true);
moveRight(); // we need one more move since we are in insert mode
- setTargetColumn();
} else if (input.isKey(Key_Home)) {
moveToStartOfLine();
- setTargetColumn();
} else if (input.isKey(Key_End)) {
moveBehindEndOfLine();
- setTargetColumn();
m_targetColumn = -1;
} else if (input.isReturn() || input.isControl('j') || input.isControl('m')) {
if (!input.isReturn() || !handleInsertInEditor(input)) {
@@ -5156,6 +5077,21 @@ void FakeVimHandler::Private::stopRecording()
g.recorded.clear();
}
+void FakeVimHandler::Private::handleAs(const QString &command)
+{
+ QString cmd = QString(_("\"%1")).arg(QChar(m_register));
+
+ if (command.contains(_("%1")))
+ cmd.append(command.arg(count()));
+ else
+ cmd.append(command);
+
+ leaveVisualMode();
+ beginLargeEditBlock();
+ replay(cmd);
+ endEditBlock();
+}
+
bool FakeVimHandler::Private::executeRegister(int reg)
{
QChar regChar(reg);
@@ -5181,7 +5117,7 @@ EventResult FakeVimHandler::Private::handleExMode(const Input &input)
{
if (input.isEscape()) {
g.commandBuffer.clear();
- resetCommandMode();
+ leaveCurrentMode();
g.submode = NoSubMode;
} else if (g.submode == CtrlVSubMode) {
g.commandBuffer.insertChar(input.raw());
@@ -5193,7 +5129,7 @@ EventResult FakeVimHandler::Private::handleExMode(const Input &input)
} else if (input.isBackspace()) {
if (g.commandBuffer.isEmpty()) {
leaveVisualMode();
- resetCommandMode();
+ leaveCurrentMode();
} else if (g.commandBuffer.hasSelection()) {
g.commandBuffer.deleteSelected();
} else {
@@ -5206,13 +5142,11 @@ EventResult FakeVimHandler::Private::handleExMode(const Input &input)
showMessage(MessageCommand, g.commandBuffer.display());
handleExCommand(g.commandBuffer.contents());
g.commandBuffer.clear();
- if (m_textedit || m_plaintextedit)
- leaveVisualMode();
} else if (!g.commandBuffer.handleInput(input)) {
qDebug() << "IGNORED IN EX-MODE: " << input.key() << input.text();
return EventUnhandled;
}
- updateMiniBuffer();
+
return EventHandled;
}
@@ -5226,7 +5160,7 @@ EventResult FakeVimHandler::Private::handleSearchSubSubMode(const Input &input)
scrollToLine(m_searchFromScreenLine);
} else if (input.isBackspace()) {
if (g.searchBuffer.isEmpty())
- resetCommandMode();
+ leaveCurrentMode();
else
g.searchBuffer.deleteChar();
} else if (input.isReturn()) {
@@ -5255,10 +5189,8 @@ EventResult FakeVimHandler::Private::handleSearchSubSubMode(const Input &input)
if (input.isReturn() || input.isEscape()) {
g.searchBuffer.clear();
- resetCommandMode();
- updateMiniBuffer();
+ leaveCurrentMode();
} else {
- updateMiniBuffer();
updateFind(false);
}
@@ -5356,7 +5288,7 @@ void FakeVimHandler::Private::setCurrentRange(const Range &range)
g.rangemode = range.rangemode;
}
-bool FakeVimHandler::Private::parseExCommmand(QString *line, ExCommand *cmd)
+bool FakeVimHandler::Private::parseExCommand(QString *line, ExCommand *cmd)
{
*cmd = ExCommand();
if (line->isEmpty())
@@ -5451,7 +5383,7 @@ void FakeVimHandler::Private::parseRangeCount(const QString &line, Range *range)
bool ok;
const int count = qAbs(line.trimmed().toInt(&ok));
if (ok) {
- const int beginLine = document()->findBlock(range->endPos).blockNumber() + 1;
+ const int beginLine = blockAt(range->endPos).blockNumber() + 1;
const int endLine = qMin(beginLine + count - 1, document()->blockCount());
range->beginPos = firstPositionInLine(beginLine, false);
range->endPos = lastPositionInLine(endLine, false);
@@ -5520,7 +5452,7 @@ bool FakeVimHandler::Private::handleExSubstituteCommand(const ExCommand &cmd)
QTextBlock firstBlock;
const bool global = g.lastSubstituteFlags.contains(QLatin1Char('g'));
for (int a = 0; a != count; ++a) {
- for (QTextBlock block = document()->findBlock(cmd.range.endPos);
+ for (QTextBlock block = blockAt(cmd.range.endPos);
block.isValid() && block.position() + block.length() > cmd.range.beginPos;
block = block.previous()) {
QString text = block.text();
@@ -5547,7 +5479,6 @@ bool FakeVimHandler::Private::handleExSubstituteCommand(const ExCommand &cmd)
setPosition(lastBlock.position());
setAnchor();
moveToFirstNonBlankOnLine();
- setTargetColumn();
endEditBlock();
}
@@ -5666,7 +5597,7 @@ bool FakeVimHandler::Private::handleExHistoryCommand(const ExCommand &cmd)
} else {
notImplementedYet();
}
- updateMiniBuffer();
+
return true;
}
@@ -5693,7 +5624,7 @@ bool FakeVimHandler::Private::handleExRegisterCommand(const ExCommand &cmd)
info += QString::fromLatin1("\"%1 %2\n").arg(reg).arg(value);
}
emit q->extraInformationChanged(info);
- updateMiniBuffer();
+
return true;
}
@@ -5818,8 +5749,8 @@ bool FakeVimHandler::Private::handleExMoveCommand(const ExCommand &cmd)
QString lineCode = cmd.args;
- const int startLine = document()->findBlock(cmd.range.beginPos).blockNumber();
- const int endLine = document()->findBlock(cmd.range.endPos).blockNumber();
+ const int startLine = blockAt(cmd.range.beginPos).blockNumber();
+ const int endLine = blockAt(cmd.range.endPos).blockNumber();
const int lines = endLine - startLine + 1;
int targetLine = lineCode == _("0") ? -1 : parseLineAddress(&lineCode);
@@ -5858,8 +5789,6 @@ bool FakeVimHandler::Private::handleExMoveCommand(const ExCommand &cmd)
if (hasConfig(ConfigStartOfLine))
moveToFirstNonBlankOnLine();
- // correct last selection
- leaveVisualMode();
if (lastAnchor.line >= startLine && lastAnchor.line <= endLine)
lastAnchor.line += targetLine - startLine + 1;
if (lastPosition.line >= startLine && lastPosition.line <= endLine)
@@ -5888,8 +5817,8 @@ bool FakeVimHandler::Private::handleExJoinCommand(const ExCommand &cmd)
setPosition(cmd.range.endPos);
} else {
setPosition(cmd.range.beginPos);
- const int startLine = document()->findBlock(cmd.range.beginPos).blockNumber();
- const int endLine = document()->findBlock(cmd.range.endPos).blockNumber();
+ const int startLine = blockAt(cmd.range.beginPos).blockNumber();
+ const int endLine = blockAt(cmd.range.endPos).blockNumber();
count = endLine - startLine + 1;
}
@@ -5971,7 +5900,6 @@ bool FakeVimHandler::Private::handleExReadCommand(const ExCommand &cmd)
beginEditBlock();
moveToStartOfLine();
- setTargetColumn();
moveDown();
int pos = position();
@@ -6076,7 +6004,7 @@ bool FakeVimHandler::Private::handleExUndoRedoCommand(const ExCommand &cmd)
return false;
undoRedo(undo);
- updateMiniBuffer();
+
return true;
}
@@ -6132,7 +6060,7 @@ bool FakeVimHandler::Private::handleExSourceCommand(const ExCommand &cmd)
//qDebug() << "EXECUTING: " << line;
ExCommand cmd;
QString commandLine = QString::fromLocal8Bit(line);
- while (parseExCommmand(&commandLine, &cmd)) {
+ while (parseExCommand(&commandLine, &cmd)) {
if (!handleExCommandHelper(cmd))
break;
}
@@ -6172,7 +6100,7 @@ void FakeVimHandler::Private::handleExCommand(const QString &line0)
beginLargeEditBlock();
ExCommand cmd;
QString lastCommand = line;
- while (parseExCommmand(&line, &cmd)) {
+ while (parseExCommand(&line, &cmd)) {
if (!handleExCommandHelper(cmd)) {
showMessage(MessageError, Tr::tr("Not an editor command: %1").arg(lastCommand));
break;
@@ -6186,7 +6114,9 @@ void FakeVimHandler::Private::handleExCommand(const QString &line0)
endEditBlock();
- resetCommandMode();
+ if (isVisualMode())
+ leaveVisualMode();
+ leaveCurrentMode();
}
bool FakeVimHandler::Private::handleExCommandHelper(ExCommand &cmd)
@@ -6240,7 +6170,7 @@ void FakeVimHandler::Private::searchBalanced(bool forward, QChar needle, QChar o
--pos;
if (pos == npos)
return;
- QChar c = document()->characterAt(pos);
+ QChar c = characterAt(pos);
if (c == other)
++level;
else if (c == needle)
@@ -6374,6 +6304,7 @@ void FakeVimHandler::Private::highlightMatches(const QString &needle)
void FakeVimHandler::Private::moveToFirstNonBlankOnLine()
{
+ g.movetype = MoveLineWise;
moveToFirstNonBlankOnLine(&m_cursor);
setTargetColumn();
}
@@ -6393,11 +6324,10 @@ void FakeVimHandler::Private::moveToFirstNonBlankOnLineVisually()
void FakeVimHandler::Private::moveToNonBlankOnLine(QTextCursor *tc)
{
- QTextDocument *doc = tc->document();
const QTextBlock block = tc->block();
const int maxPos = block.position() + block.length() - 1;
int i = tc->position();
- while (doc->characterAt(i).isSpace() && i < maxPos)
+ while (characterAt(i).isSpace() && i < maxPos)
++i;
tc->setPosition(i, KeepAnchor);
}
@@ -6425,8 +6355,8 @@ void FakeVimHandler::Private::indentSelectedText(QChar typedChar)
void FakeVimHandler::Private::indentText(const Range &range, QChar typedChar)
{
- int beginBlock = document()->findBlock(range.beginPos).blockNumber();
- int endBlock = document()->findBlock(range.endPos).blockNumber();
+ int beginBlock = blockAt(range.beginPos).blockNumber();
+ int endBlock = blockAt(range.endPos).blockNumber();
if (beginBlock > endBlock)
std::swap(beginBlock, endBlock);
@@ -6472,7 +6402,6 @@ void FakeVimHandler::Private::shiftRegionRight(int repeat)
setPosition(targetPos);
handleStartOfLine();
- setTargetColumn();
const int lines = endLine - beginLine + 1;
if (lines > 2) {
@@ -6542,7 +6471,7 @@ int FakeVimHandler::Private::charClass(QChar c, bool simple) const
void FakeVimHandler::Private::miniBufferTextEdited(const QString &text, int cursorPos,
int anchorPos)
{
- if (g.subsubmode != SearchSubSubMode && g.mode != ExMode) {
+ if (!isCommandLineMode()) {
editor()->setFocus();
} else if (text.isEmpty()) {
// editing cancelled
@@ -6551,7 +6480,6 @@ void FakeVimHandler::Private::miniBufferTextEdited(const QString &text, int curs
leaveFakeVim();
editor()->setFocus();
- updateCursorShape();
} else {
CommandBuffer &cmdBuf = (g.mode == ExMode) ? g.commandBuffer : g.searchBuffer;
int pos = qMax(1, cursorPos);
@@ -6570,7 +6498,7 @@ void FakeVimHandler::Private::miniBufferTextEdited(const QString &text, int curs
// update search expression
if (g.subsubmode == SearchSubSubMode) {
updateFind(false);
- exportSelection();
+ commitCursor();
}
}
}
@@ -6586,6 +6514,9 @@ void FakeVimHandler::Private::pullOrCreateBufferData()
m_buffer = BufferDataPtr(new BufferData);
document()->setProperty("FakeVimSharedData", QVariant::fromValue(m_buffer));
}
+
+ if (editor()->hasFocus())
+ m_buffer->currentHandler = this;
}
// Helper to parse a-z,A-Z,48-57,_
@@ -6619,17 +6550,16 @@ void FakeVimHandler::Private::setupCharClass()
void FakeVimHandler::Private::moveToBoundary(bool simple, bool forward)
{
- QTextDocument *doc = document();
- QTextCursor tc(doc);
+ QTextCursor tc(document());
tc.setPosition(position());
if (forward ? tc.atBlockEnd() : tc.atBlockStart())
return;
- QChar c = document()->characterAt(tc.position() + (forward ? -1 : 1));
+ QChar c = characterAt(tc.position() + (forward ? -1 : 1));
int lastClass = tc.atStart() ? -1 : charClass(c, simple);
QTextCursor::MoveOperation op = forward ? Right : Left;
while (true) {
- c = doc->characterAt(tc.position());
+ c = characterAt(tc.position());
int thisClass = charClass(c, simple);
if (thisClass != lastClass || (forward ? tc.atBlockEnd() : tc.atBlockStart())) {
if (tc != m_cursor)
@@ -6686,12 +6616,16 @@ void FakeVimHandler::Private::moveToNextWord(bool end, int count, bool simple, b
void FakeVimHandler::Private::moveToNextWordStart(int count, bool simple, bool forward, bool emptyLines)
{
+ g.movetype = MoveExclusive;
moveToNextWord(false, count, simple, forward, emptyLines);
+ setTargetColumn();
}
void FakeVimHandler::Private::moveToNextWordEnd(int count, bool simple, bool forward, bool emptyLines)
{
+ g.movetype = MoveInclusive;
moveToNextWord(true, count, simple, forward, emptyLines);
+ setTargetColumn();
}
void FakeVimHandler::Private::moveToWordStart(int count, bool simple, bool forward, bool emptyLines)
@@ -6712,14 +6646,13 @@ bool FakeVimHandler::Private::handleFfTt(const QString &key, bool repeats)
bool exclusive = g.subsubdata.is('t') || g.subsubdata.is('T');
int repeat = count();
int n = block().position() + (forward ? block().length() : - 1);
- QTextDocument *doc = document();
const int d = forward ? 1 : -1;
// FIXME: This also depends on whether 'cpositions' Vim option contains ';'.
const int skip = (repeats && repeat == 1 && exclusive) ? d : 0;
int pos = position() + d + skip;
for (; repeat > 0 && (forward ? pos < n : pos > n); pos += d) {
- if (doc->characterAt(pos).unicode() == key0)
+ if (characterAt(pos).unicode() == key0)
--repeat;
}
@@ -6742,7 +6675,7 @@ void FakeVimHandler::Private::moveToMatchingParanthesis()
// If no known parenthesis symbol is under cursor find one on the current line after cursor.
static const QString parenthesesChars(_("([{}])"));
- while (!parenthesesChars.contains(document()->characterAt(tc.position())) && !tc.atBlockEnd())
+ while (!parenthesesChars.contains(characterAt(tc.position())) && !tc.atBlockEnd())
tc.setPosition(tc.position() + 1);
if (tc.atBlockEnd())
@@ -6780,7 +6713,7 @@ int FakeVimHandler::Private::cursorLine() const
int FakeVimHandler::Private::cursorBlockNumber() const
{
- return document()->findBlock(qMin(anchor(), position())).blockNumber();
+ return blockAt(qMin(anchor(), position())).blockNumber();
}
int FakeVimHandler::Private::physicalCursorColumn() const
@@ -6978,50 +6911,11 @@ int FakeVimHandler::Private::lastPositionInDocument(bool ignoreMode) const
QString FakeVimHandler::Private::selectText(const Range &range) const
{
- if (range.rangemode == RangeCharMode) {
- QTextCursor tc(document());
- tc.setPosition(range.beginPos, MoveAnchor);
- tc.setPosition(range.endPos, KeepAnchor);
- return tc.selection().toPlainText();
- }
- if (range.rangemode == RangeLineMode) {
- const QTextBlock firstBlock = document()->findBlock(range.beginPos);
- int firstPos = firstBlock.isValid() ? firstBlock.position() : 0;
- QTextBlock lastBlock = document()->findBlock(range.endPos);
- bool endOfDoc = lastBlock == document()->lastBlock();
- int lastPos = endOfDoc ? lastPositionInDocument(true) : lastBlock.next().position();
- QTextCursor tc(document());
- tc.setPosition(firstPos, MoveAnchor);
- tc.setPosition(lastPos, KeepAnchor);
- return tc.selection().toPlainText() + _(endOfDoc? "\n" : "");
- }
- // FIXME: Performance?
- int beginLine = lineForPosition(range.beginPos);
- int endLine = lineForPosition(range.endPos);
- int beginColumn = 0;
- int endColumn = INT_MAX;
- if (range.rangemode == RangeBlockMode) {
- int column1 = range.beginPos - firstPositionInLine(beginLine);
- int column2 = range.endPos - firstPositionInLine(endLine);
- beginColumn = qMin(column1, column2);
- endColumn = qMax(column1, column2);
- }
- int len = endColumn - beginColumn + 1;
QString contents;
- QTextBlock block = document()->findBlockByLineNumber(beginLine - 1);
- for (int i = beginLine; i <= endLine && block.isValid(); ++i) {
- QString line = block.text();
- if (range.rangemode == RangeBlockMode) {
- line = line.mid(beginColumn, len);
- if (line.size() < len)
- line += QString(len - line.size(), QLatin1Char(' '));
- }
- contents += line;
- if (!contents.endsWith(QLatin1Char('\n')))
- contents += QLatin1Char('\n');
- block = block.next();
- }
- //qDebug() << "SELECTED: " << contents;
+ const QString lineEnd = range.rangemode == RangeBlockMode ? QString(QLatin1Char('\n')) : QString();
+ QTextCursor tc = m_cursor;
+ transformText(range, tc,
+ [&tc, &contents, &lineEnd]() { contents.append(tc.selection().toPlainText() + lineEnd); });
return contents;
}
@@ -7048,32 +6942,26 @@ void FakeVimHandler::Private::yankText(const Range &range, int reg)
setRegister('"', text, range.rangemode);
}
- const int lines = document()->findBlock(range.endPos).blockNumber()
- - document()->findBlock(range.beginPos).blockNumber() + 1;
+ const int lines = blockAt(range.endPos).blockNumber()
+ - blockAt(range.beginPos).blockNumber() + 1;
if (lines > 2)
showMessage(MessageInfo, Tr::tr("%n lines yanked.", 0, lines));
}
-void FakeVimHandler::Private::transformText(const Range &range,
- Transformation transformFunc, const QVariant &extra)
+void FakeVimHandler::Private::transformText(
+ const Range &range, QTextCursor &tc, const std::function<void()> &transform) const
{
- QTextCursor tc = m_cursor;
- int posAfter = range.beginPos;
switch (range.rangemode) {
case RangeCharMode: {
// This can span multiple lines.
- beginEditBlock();
tc.setPosition(range.beginPos, MoveAnchor);
tc.setPosition(range.endPos, KeepAnchor);
- TransformationData td(tc.selectedText(), extra);
- (this->*transformFunc)(&td);
- insertText(tc, td.to);
- endEditBlock();
+ transform();
+ tc.setPosition(range.beginPos);
break;
}
case RangeLineMode:
case RangeLineModeExclusive: {
- beginEditBlock();
tc.setPosition(range.beginPos, MoveAnchor);
tc.movePosition(StartOfLine, MoveAnchor);
tc.setPosition(range.endPos, KeepAnchor);
@@ -7095,62 +6983,56 @@ void FakeVimHandler::Private::transformText(const Range &range,
tc.movePosition(Right, KeepAnchor, 1);
}
}
- TransformationData td(tc.selectedText(), extra);
- (this->*transformFunc)(&td);
- posAfter = tc.anchor();
- insertText(tc, td.to);
- endEditBlock();
+ const int posAfter = tc.anchor();
+ transform();
+ tc.setPosition(posAfter);
break;
}
case RangeBlockAndTailMode:
case RangeBlockMode: {
- int beginLine = lineForPosition(range.beginPos);
- int endLine = lineForPosition(range.endPos);
- int column1 = range.beginPos - firstPositionInLine(beginLine);
- int column2 = range.endPos - firstPositionInLine(endLine);
- int beginColumn = qMin(column1, column2);
- int endColumn = qMax(column1, column2);
+ int beginColumn = columnAt(range.beginPos);
+ int endColumn = columnAt(range.endPos);
+ if (endColumn < beginColumn)
+ std::swap(beginColumn, endColumn);
if (range.rangemode == RangeBlockAndTailMode)
endColumn = INT_MAX - 1;
- QTextBlock block = document()->findBlockByLineNumber(endLine - 1);
- beginEditBlock();
- for (int i = beginLine; i <= endLine && block.isValid(); ++i) {
+ QTextBlock block = document()->findBlock(range.beginPos);
+ const QTextBlock lastBlock = document()->findBlock(range.endPos);
+ while (block.isValid() && block.position() <= lastBlock.position()) {
int bCol = qMin(beginColumn, block.length() - 1);
int eCol = qMin(endColumn + 1, block.length() - 1);
tc.setPosition(block.position() + bCol, MoveAnchor);
tc.setPosition(block.position() + eCol, KeepAnchor);
- TransformationData td(tc.selectedText(), extra);
- (this->*transformFunc)(&td);
- insertText(tc, td.to);
- block = block.previous();
+ transform();
+ block = block.next();
}
- endEditBlock();
+ tc.setPosition(range.beginPos);
break;
}
}
+}
- setPosition(posAfter);
+void FakeVimHandler::Private::transformText(const Range &range, const Transformation &transform)
+{
+ beginEditBlock();
+ transformText(range, m_cursor,
+ [this, &transform] { m_cursor.insertText(transform(m_cursor.selection().toPlainText())); });
+ endEditBlock();
setTargetColumn();
}
void FakeVimHandler::Private::insertText(QTextCursor &tc, const QString &text)
{
if (hasConfig(ConfigPassKeys)) {
- QTextCursor oldTc = m_cursor;
- m_cursor = tc;
-
if (tc.hasSelection() && text.isEmpty()) {
QKeyEvent event(QEvent::KeyPress, Qt::Key_Delete, Qt::NoModifier, QString());
- passEventToEditor(event);
+ passEventToEditor(event, tc);
}
foreach (QChar c, text) {
QKeyEvent event(QEvent::KeyPress, -1, Qt::NoModifier, QString(c));
- passEventToEditor(event);
+ passEventToEditor(event, tc);
}
-
- tc = m_cursor;
- m_cursor = oldTc;
} else {
tc.insertText(text);
}
@@ -7167,66 +7049,35 @@ void FakeVimHandler::Private::insertText(const Register &reg)
void FakeVimHandler::Private::removeText(const Range &range)
{
- //qDebug() << "REMOVE: " << range;
- transformText(range, &FakeVimHandler::Private::removeTransform);
-}
-
-void FakeVimHandler::Private::removeTransform(TransformationData *td)
-{
- Q_UNUSED(td);
+ transformText(range, [](const QString &) { return QString(); });
}
void FakeVimHandler::Private::downCase(const Range &range)
{
- transformText(range, &FakeVimHandler::Private::downCaseTransform);
-}
-
-void FakeVimHandler::Private::downCaseTransform(TransformationData *td)
-{
- td->to = td->from.toLower();
+ transformText(range, [](const QString &text) { return text.toLower(); } );
}
void FakeVimHandler::Private::upCase(const Range &range)
{
- transformText(range, &FakeVimHandler::Private::upCaseTransform);
-}
-
-void FakeVimHandler::Private::upCaseTransform(TransformationData *td)
-{
- td->to = td->from.toUpper();
+ transformText(range, [](const QString &text) { return text.toUpper(); } );
}
void FakeVimHandler::Private::invertCase(const Range &range)
{
- transformText(range, &FakeVimHandler::Private::invertCaseTransform);
-}
-
-void FakeVimHandler::Private::invertCaseTransform(TransformationData *td)
-{
- foreach (QChar c, td->from)
- td->to += c.isUpper() ? c.toLower() : c.toUpper();
+ transformText(range,
+ [] (const QString &text) -> QString {
+ QString result = text;
+ for (int i = 0; i < result.length(); ++i) {
+ QCharRef c = result[i];
+ c = c.isUpper() ? c.toLower() : c.toUpper();
+ }
+ return result;
+ });
}
void FakeVimHandler::Private::replaceText(const Range &range, const QString &str)
{
- Transformation tr = &FakeVimHandler::Private::replaceByStringTransform;
- transformText(range, tr, str);
-}
-
-void FakeVimHandler::Private::replaceByStringTransform(TransformationData *td)
-{
- td->to = td->extraData.toString();
-}
-
-void FakeVimHandler::Private::replaceByCharTransform(TransformationData *td)
-{
- // Replace each character but preserve lines.
- const int len = td->from.size();
- td->to = QString(len, td->extraData.toChar());
- for (int i = 0; i < len; ++i) {
- if (td->from.at(i) == ParagraphSeparator)
- td->to[i] = ParagraphSeparator;
- }
+ transformText(range, [&str](const QString &) { return str; } );
}
void FakeVimHandler::Private::pasteText(bool afterCursor)
@@ -7239,30 +7090,8 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
// In visual mode paste text only inside selection.
bool pasteAfter = isVisualMode() ? false : afterCursor;
- bool visualCharMode = isVisualCharMode();
- if (visualCharMode) {
- leaveVisualMode();
- g.rangemode = RangeCharMode;
- Range range = currentRange();
- range.endPos++;
- yankText(range, m_register);
- removeText(range);
- } else if (isVisualLineMode()) {
- leaveVisualMode();
- g.rangemode = RangeLineMode;
- Range range = currentRange();
- range.endPos++;
- yankText(range, m_register);
- removeText(range);
- handleStartOfLine();
- } else if (isVisualBlockMode()) {
- leaveVisualMode();
- g.rangemode = RangeBlockMode;
- Range range = currentRange();
- yankText(range, m_register);
- removeText(range);
- setPosition(qMin(position(), anchor()));
- }
+ if (isVisualMode())
+ cutSelectedText();
switch (rangeMode) {
case RangeCharMode: {
@@ -7280,10 +7109,7 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
case RangeLineMode:
case RangeLineModeExclusive: {
QTextCursor tc = m_cursor;
- if (visualCharMode)
- tc.insertBlock();
- else
- moveToStartOfLine();
+ moveToStartOfLine();
m_targetColumn = 0;
bool lastLine = false;
if (pasteAfter) {
@@ -7346,6 +7172,28 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
endEditBlock();
}
+void FakeVimHandler::Private::cutSelectedText()
+{
+ pushUndoState();
+
+ bool visualMode = isVisualMode();
+ leaveVisualMode();
+
+ Range range = currentRange();
+ if (visualMode && g.rangemode == RangeCharMode)
+ ++range.endPos;
+
+ g.submode = DeleteSubMode;
+ yankText(range, m_register);
+ removeText(range);
+ g.submode = NoSubMode;
+
+ if (g.rangemode == RangeLineMode)
+ handleStartOfLine();
+ else if (g.rangemode == RangeBlockMode)
+ setPosition(qMin(position(), anchor()));
+}
+
void FakeVimHandler::Private::joinLines(int count, bool preserveSpace)
{
int pos = position();
@@ -7370,7 +7218,7 @@ void FakeVimHandler::Private::insertNewLine()
{
if ( m_buffer->editBlockLevel <= 1 && hasConfig(ConfigPassKeys) ) {
QKeyEvent event(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier, QLatin1String("\n"));
- if (passEventToEditor(event))
+ if (passEventToEditor(event, m_cursor))
return;
}
@@ -7387,27 +7235,30 @@ bool FakeVimHandler::Private::handleInsertInEditor(const Input &input)
QKeyEvent event(QEvent::KeyPress, input.key(), input.modifiers(), input.text());
setAnchor();
- if (!passEventToEditor(event))
+ if (!passEventToEditor(event, m_cursor))
return !m_textedit && !m_plaintextedit; // Mark event as handled if it has destroyed editor.
endEditBlock();
+ setTargetColumn();
+
return true;
}
-bool FakeVimHandler::Private::passEventToEditor(QEvent &event)
+bool FakeVimHandler::Private::passEventToEditor(QEvent &event, QTextCursor &tc)
{
removeEventFilter();
+ emit q->requestDisableBlockSelection();
+
+ setThinCursor();
+ EDITOR(setTextCursor(tc));
- EDITOR(setOverwriteMode(false));
- commitCursor();
bool accepted = QApplication::sendEvent(editor(), &event);
if (!m_textedit && !m_plaintextedit)
return false;
- updateCursorShape();
if (accepted)
- pullCursor();
+ tc = EDITOR(textCursor());
return accepted;
}
@@ -7517,14 +7368,29 @@ int FakeVimHandler::Private::lineNumber(const QTextBlock &block) const
return block2.firstLineNumber() + 1;
}
+int FakeVimHandler::Private::columnAt(int pos) const
+{
+ return pos - blockAt(pos).position();
+}
+
+int FakeVimHandler::Private::blockNumberAt(int pos) const
+{
+ return blockAt(pos).blockNumber();
+}
+
+QTextBlock FakeVimHandler::Private::blockAt(int pos) const
+{
+ return document()->findBlock(pos);
+}
+
QTextBlock FakeVimHandler::Private::nextLine(const QTextBlock &block) const
{
- return document()->findBlock(block.position() + block.length());
+ return blockAt(block.position() + block.length());
}
QTextBlock FakeVimHandler::Private::previousLine(const QTextBlock &block) const
{
- return document()->findBlock(block.position() - 1);
+ return blockAt(block.position() - 1);
}
int FakeVimHandler::Private::firstPositionInLine(int line, bool onlyVisibleLines) const
@@ -7561,7 +7427,7 @@ int FakeVimHandler::Private::lastPositionInLine(int line, bool onlyVisibleLines)
int FakeVimHandler::Private::lineForPosition(int pos) const
{
- const QTextBlock block = document()->findBlock(pos);
+ const QTextBlock block = blockAt(pos);
if (!block.isValid())
return 0;
const int positionInBlock = pos - block.position();
@@ -7578,7 +7444,6 @@ void FakeVimHandler::Private::toggleVisualMode(VisualMode visualMode)
m_anchorPastEnd = false;
g.visualMode = visualMode;
m_buffer->lastVisualMode = visualMode;
- updateMiniBuffer();
}
}
@@ -7587,9 +7452,6 @@ void FakeVimHandler::Private::leaveVisualMode()
if (!isVisualMode())
return;
- setMark(QLatin1Char('<'), markLessPosition());
- setMark(QLatin1Char('>'), markGreaterPosition());
- m_buffer->lastVisualModeInverted = anchor() > position();
if (isVisualLineMode()) {
g.rangemode = RangeLineMode;
g.movetype = MoveLineWise;
@@ -7597,12 +7459,21 @@ void FakeVimHandler::Private::leaveVisualMode()
g.rangemode = RangeCharMode;
g.movetype = MoveInclusive;
} else if (isVisualBlockMode()) {
- g.rangemode = RangeBlockMode;
+ g.rangemode = m_visualTargetColumn == -1 ? RangeBlockAndTailMode : RangeBlockMode;
g.movetype = MoveInclusive;
}
g.visualMode = NoVisualMode;
- updateMiniBuffer();
+}
+
+void FakeVimHandler::Private::saveLastVisualMode()
+{
+ if (isVisualMode() && g.mode == CommandMode && g.submode == NoSubMode) {
+ setMark(QLatin1Char('<'), markLessPosition());
+ setMark(QLatin1Char('>'), markGreaterPosition());
+ m_buffer->lastVisualModeInverted = anchor() > position();
+ m_buffer->lastVisualMode = g.visualMode;
+ }
}
QWidget *FakeVimHandler::Private::editor() const
@@ -7658,10 +7529,11 @@ void FakeVimHandler::Private::endEditBlock()
void FakeVimHandler::Private::onContentsChanged(int position, int charsRemoved, int charsAdded)
{
// Record inserted and deleted text in insert mode.
- if (isInsertMode() && (charsAdded > 0 || charsRemoved > 0)) {
+ if (isInsertMode() && (charsAdded > 0 || charsRemoved > 0) && canModifyBufferData()) {
BufferData::InsertState &insertState = m_buffer->insertState;
+ const int oldPosition = insertState.pos2;
if (!isInsertStateValid()) {
- insertState.pos1 = m_oldInternalPosition;
+ insertState.pos1 = oldPosition;
g.dotCommand = _("i");
resetCount();
}
@@ -7672,7 +7544,7 @@ void FakeVimHandler::Private::onContentsChanged(int position, int charsRemoved,
if (position < insertState.pos1) {
// backspaces
const int bs = insertState.pos1 - position;
- const QString inserted = textAt(position, m_oldInternalPosition);
+ const QString inserted = textAt(position, oldPosition);
const QString removed = insertState.textBeforeCursor.right(bs);
// Ignore backspaces if same text was just inserted.
if ( !inserted.endsWith(removed) ) {
@@ -7686,17 +7558,15 @@ void FakeVimHandler::Private::onContentsChanged(int position, int charsRemoved,
}
} else if (charsAdded > 0 && insertState.insertingSpaces) {
for (int i = position; i < position + charsAdded; ++i) {
- const QChar c = document()->characterAt(i);
+ const QChar c = characterAt(i);
if (c.unicode() == ' ' || c.unicode() == '\t')
insertState.spaces.insert(i);
}
}
- insertState.pos2 = qMax(insertState.pos2 + charsAdded - charsRemoved,
- position + charsAdded);
- m_oldInternalPosition = position + charsAdded;
- insertState.textBeforeCursor = textAt(document()->findBlock(m_oldInternalPosition).position(),
- m_oldInternalPosition);
+ const int newPosition = position + charsAdded;
+ insertState.pos2 = qMax(insertState.pos2 + charsAdded - charsRemoved, newPosition);
+ insertState.textBeforeCursor = textAt(block().position(), newPosition);
}
}
@@ -7704,8 +7574,23 @@ void FakeVimHandler::Private::onContentsChanged(int position, int charsRemoved,
emit q->highlightMatches(m_highlighted);
}
+void FakeVimHandler::Private::onCursorPositionChanged()
+{
+ if (!m_inFakeVim) {
+ m_cursorNeedsUpdate = true;
+
+ // Selecting text with mouse disables the thick cursor so it's more obvious
+ // that extra character under cursor is not selected when moving text around or
+ // making operations on text outside FakeVim mode.
+ setThinCursor(g.mode == InsertMode || EDITOR(textCursor()).hasSelection());
+ }
+}
+
void FakeVimHandler::Private::onUndoCommandAdded()
{
+ if (!canModifyBufferData())
+ return;
+
// Undo commands removed?
UNDO_DEBUG("Undo added" << "previous: REV" << m_buffer->lastRevision);
if (m_buffer->lastRevision >= revision()) {
@@ -7725,6 +7610,19 @@ void FakeVimHandler::Private::onUndoCommandAdded()
m_buffer->undo.push(State());
}
+void FakeVimHandler::Private::onInputTimeout()
+{
+ enterFakeVim();
+ EventResult result = handleKey(Input());
+ leaveFakeVim(result);
+}
+
+void FakeVimHandler::Private::onFixCursorTimeout()
+{
+ if (editor())
+ fixExternalCursorPosition(editor()->hasFocus() && !isCommandLineMode());
+}
+
char FakeVimHandler::Private::currentModeCode() const
{
if (g.mode == ExMode)
@@ -7781,15 +7679,15 @@ void FakeVimHandler::Private::undoRedo(bool undo)
--m_buffer->editBlockLevel;
if (state.isValid()) {
- m_buffer->lastChangePosition = state.position;
Marks marks = m_buffer->marks;
marks.swap(state.marks);
updateMarks(marks);
m_buffer->lastVisualMode = state.lastVisualMode;
m_buffer->lastVisualModeInverted = state.lastVisualModeInverted;
+ setMark(QLatin1Char('.'), state.position);
setMark(QLatin1Char('\''), lastPos);
setMark(QLatin1Char('`'), lastPos);
- setCursorPosition(m_buffer->lastChangePosition);
+ setCursorPosition(state.position);
setAnchor();
state.revision = previousRevision;
} else {
@@ -7817,11 +7715,22 @@ void FakeVimHandler::Private::redo()
void FakeVimHandler::Private::updateCursorShape()
{
- bool thinCursor = g.mode == ExMode
- || g.subsubmode == SearchSubSubMode
- || g.mode == InsertMode
- || (isVisualMode() && !isVisualCharMode());
- EDITOR(setOverwriteMode(!thinCursor));
+ setThinCursor(
+ g.mode == InsertMode
+ || isVisualLineMode()
+ || isVisualBlockMode()
+ || isCommandLineMode()
+ || !editor()->hasFocus());
+}
+
+void FakeVimHandler::Private::setThinCursor(bool enable)
+{
+ EDITOR(setOverwriteMode(!enable));
+}
+
+bool FakeVimHandler::Private::hasThinCursor() const
+{
+ return !EDITOR(overwriteMode());
}
void FakeVimHandler::Private::enterReplaceMode()
@@ -7840,17 +7749,26 @@ void FakeVimHandler::Private::enterInsertOrReplaceMode(Mode mode)
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();
+
+ if (g.returnToMode == mode) {
+ // Returning to insert mode after <C-O>.
+ clearCurrentMode();
+ moveToTargetColumn();
+ invalidateInsertState();
+ } else {
+ // Entering insert mode from command mode.
+ if (mode == InsertMode) {
+ // m_targetColumn shouldn't be -1 (end of line).
+ if (m_targetColumn == -1)
+ setTargetColumn();
+ }
+
+ g.submode = NoSubMode;
+ g.subsubmode = NoSubSubMode;
+ g.returnToMode = mode;
+ clearLastInsertion();
+ }
}
void FakeVimHandler::Private::enterVisualInsertMode(QChar command)
@@ -7859,7 +7777,6 @@ void FakeVimHandler::Private::enterVisualInsertMode(QChar command)
bool append = command == QLatin1Char('A');
bool change = command == QLatin1Char('s') || command == QLatin1Char('c');
- setDotCommand(visualDotCommand() + QString::number(count()) + command);
leaveVisualMode();
const CursorPosition lastAnchor = markLessPosition();
@@ -7873,11 +7790,8 @@ void FakeVimHandler::Private::enterVisualInsertMode(QChar command)
: AppendBlockInsertMode;
} else if (change) {
m_visualBlockInsert = ChangeBlockInsertMode;
- pushUndoState();
beginEditBlock();
- Range range(position(), anchor(), RangeBlockMode);
- yankText(range, m_register);
- removeText(range);
+ cutSelectedText();
endEditBlock();
} else {
m_visualBlockInsert = InsertBlockInsertMode;
@@ -7890,13 +7804,11 @@ void FakeVimHandler::Private::enterVisualInsertMode(QChar command)
m_visualBlockInsert = NoneBlockInsertMode;
leaveVisualMode();
if (command == QLatin1Char('I')) {
- setDotCommand(_("%1i"), count());
if (lineForPosition(anchor()) <= lineForPosition(position())) {
setPosition(qMin(anchor(), position()));
moveToStartOfLine();
}
} else if (command == QLatin1Char('A')) {
- setDotCommand(_("%1a"), count());
if (lineForPosition(anchor()) <= lineForPosition(position())) {
setPosition(position());
moveRight(qMin(rightDist(), 1));
@@ -7915,11 +7827,23 @@ void FakeVimHandler::Private::enterVisualInsertMode(QChar command)
void FakeVimHandler::Private::enterCommandMode(Mode returnToMode)
{
- if (isNoVisualMode() && atEndOfLine())
- moveLeft();
+ if (g.isRecording && isCommandLineMode())
+ record(Input(Key_Escape, NoModifier));
+
+ if (isNoVisualMode()) {
+ if (atEndOfLine()) {
+ m_cursor.movePosition(Left, KeepAnchor);
+ if (m_targetColumn != -1)
+ setTargetColumn();
+ }
+ setAnchor();
+ }
+
g.mode = CommandMode;
- clearCommandMode();
+ clearCurrentMode();
g.returnToMode = returnToMode;
+ m_positionPastEnd = false;
+ m_anchorPastEnd = false;
}
void FakeVimHandler::Private::enterExMode(const QString &contents)
@@ -7933,6 +7857,7 @@ void FakeVimHandler::Private::enterExMode(const QString &contents)
g.mode = ExMode;
g.submode = NoSubMode;
g.subsubmode = NoSubSubMode;
+ unfocus();
}
void FakeVimHandler::Private::recordJump(int position)
@@ -7960,6 +7885,7 @@ void FakeVimHandler::Private::jump(int distance)
setCursorPosition(from.top());
from.pop();
}
+ setTargetColumn();
}
Column FakeVimHandler::Private::indentation(const QString &line) const
@@ -8024,7 +7950,7 @@ void FakeVimHandler::Private::replay(const QString &command, int repeat)
return;
//qDebug() << "REPLAY: " << quoteUnprintable(command);
- clearCommandMode();
+ clearCurrentMode();
Inputs inputs(command);
for (int i = 0; i < repeat; ++i) {
foreach (const Input &in, inputs) {
@@ -8082,13 +8008,9 @@ void FakeVimHandler::Private::selectTextObject(bool simple, bool inner)
moveToBoundaryStart(1, simple, false);
setAnchor();
} else if (forward) {
- moveRight();
- if (atEndOfLine())
- moveRight();
+ moveToNextCharacter();
} else {
- moveLeft();
- if (atBlockStart())
- moveLeft();
+ moveToPreviousCharacter();
}
if (inner) {
@@ -8112,7 +8034,7 @@ void FakeVimHandler::Private::selectTextObject(bool simple, bool inner)
moveToWordStart(1, simple, false);
// select trailing spaces if no leading space
- QChar afterCursor = document()->characterAt(position() + direction);
+ QChar afterCursor = characterAt(position() + direction);
if (!leadingSpace && afterCursor.isSpace() && afterCursor != ParagraphSeparator
&& !atBlockStart()) {
if (forward)
@@ -8126,21 +8048,16 @@ void FakeVimHandler::Private::selectTextObject(bool simple, bool inner)
if (setupAnchor && (!characterAtCursor().isSpace() || atBlockEnd())) {
int min = block().position();
int pos = anchor();
- while (pos >= min && document()->characterAt(--pos).isSpace()) {}
+ while (pos >= min && characterAt(--pos).isSpace()) {}
if (pos >= min)
setAnchorAndPosition(pos + 1, position());
}
if (i + 1 < repeat) {
- if (forward) {
- moveRight();
- if (atEndOfLine())
- moveRight();
- } else {
- moveLeft();
- if (atBlockStart())
- moveLeft();
- }
+ if (forward)
+ moveToNextCharacter();
+ else
+ moveToPreviousCharacter();
}
}
}
@@ -8149,13 +8066,10 @@ void FakeVimHandler::Private::selectTextObject(bool simple, bool inner)
g.movetype = MoveInclusive;
} else {
g.movetype = MoveExclusive;
- if (isNoVisualMode()) {
- moveRight();
- if (atEndOfLine())
- moveRight();
- } else if (isVisualLineMode()) {
+ if (isNoVisualMode())
+ moveToNextCharacter();
+ else if (isVisualLineMode())
g.visualMode = VisualCharMode;
- }
}
setTargetColumn();
@@ -8178,7 +8092,81 @@ void FakeVimHandler::Private::selectSentenceTextObject(bool inner)
void FakeVimHandler::Private::selectParagraphTextObject(bool inner)
{
- Q_UNUSED(inner);
+ const QTextCursor oldCursor = m_cursor;
+ const VisualMode oldVisualMode = g.visualMode;
+
+ const int anchorBlock = blockNumberAt(anchor());
+ const int positionBlock = blockNumberAt(position());
+ const bool setupAnchor = anchorBlock == positionBlock;
+ int repeat = count();
+
+ // If anchor and position are in the same block,
+ // start line selection at beginning of current paragraph.
+ if (setupAnchor) {
+ moveToParagraphStartOrEnd(-1);
+ setAnchor();
+
+ if (!isVisualLineMode() && isVisualMode())
+ toggleVisualMode(VisualLineMode);
+ }
+
+ const bool forward = anchor() <= position();
+ const int d = forward ? 1 : -1;
+
+ bool startsAtParagraph = !atEmptyLine(position());
+
+ moveToParagraphStartOrEnd(d);
+
+ // If selection already changed, decreate count.
+ if ((setupAnchor && g.submode != NoSubMode)
+ || oldVisualMode != g.visualMode
+ || m_cursor != oldCursor)
+ {
+ --repeat;
+ if (!inner) {
+ moveDown(d);
+ moveToParagraphStartOrEnd(d);
+ startsAtParagraph = !startsAtParagraph;
+ }
+ }
+
+ if (repeat > 0) {
+ bool isCountEven = repeat % 2 == 0;
+ bool endsOnParagraph =
+ inner ? isCountEven == startsAtParagraph : startsAtParagraph;
+
+ if (inner) {
+ repeat = repeat / 2;
+ if (!isCountEven || endsOnParagraph)
+ ++repeat;
+ } else {
+ if (endsOnParagraph)
+ ++repeat;
+ }
+
+ if (!moveToNextParagraph(d * repeat)) {
+ m_cursor = oldCursor;
+ g.visualMode = oldVisualMode;
+ return;
+ }
+
+ if (endsOnParagraph && atEmptyLine())
+ moveUp(d);
+ else
+ moveToParagraphStartOrEnd(d);
+ }
+
+ if (!inner && setupAnchor && !atEmptyLine() && !atEmptyLine(anchor())) {
+ // If position cannot select empty lines, try to select them with anchor.
+ setAnchorAndPosition(position(), anchor());
+ moveToNextParagraph(-d);
+ moveToParagraphStartOrEnd(-d);
+ setAnchorAndPosition(position(), anchor());
+ }
+
+ recordJump(oldCursor.position());
+ setTargetColumn();
+ g.movetype = MoveLineWise;
}
bool FakeVimHandler::Private::selectBlockTextObject(bool inner,
@@ -8195,16 +8183,26 @@ bool FakeVimHandler::Private::selectBlockTextObject(bool inner,
if (p2 == -1)
return false;
- if (inner)
+ g.movetype = MoveExclusive;
+
+ if (inner) {
p1 += sleft.size();
- else
+ bool moveStart = characterAt(p1) == ParagraphSeparator;
+ bool moveEnd = isFirstNonBlankOnLine(p2);
+ if (moveStart)
+ ++p1;
+ if (moveEnd)
+ p2 = blockAt(p2).position() - 1;
+ if (moveStart && moveEnd)
+ g.movetype = MoveLineWise;
+ } else {
p2 -= sright.size() - 2;
+ }
if (isVisualMode())
--p2;
setAnchorAndPosition(p1, p2);
- g.movetype = MoveExclusive;
return true;
}
@@ -8295,7 +8293,7 @@ bool FakeVimHandler::Private::selectQuotedStringTextObject(bool inner,
int p2 = tc2.position();
if (inner) {
p2 = qMax(p1, p2 - sz);
- if (document()->characterAt(p1) == ParagraphSeparator)
+ if (characterAt(p1) == ParagraphSeparator)
++p1;
} else {
p1 -= sz;
@@ -8319,8 +8317,7 @@ Mark FakeVimHandler::Private::mark(QChar code) const
if (code == QLatin1Char('>'))
return CursorPosition(document(), qMax(anchor(), position()));
}
- if (code == QLatin1Char('.'))
- return m_buffer->lastChangePosition;
+
if (code.isUpper())
return g.marks.value(code);
@@ -8372,7 +8369,7 @@ RangeMode FakeVimHandler::Private::registerRangeMode(int reg) const
{
bool isClipboard;
bool isSelection;
- getRegisterType(reg, &isClipboard, &isSelection);
+ getRegisterType(&reg, &isClipboard, &isSelection);
if (isClipboard || isSelection) {
QClipboard *clipboard = QApplication::clipboard();
@@ -8400,11 +8397,15 @@ void FakeVimHandler::Private::setRegister(int reg, const QString &contents, Rang
{
bool copyToClipboard;
bool copyToSelection;
- getRegisterType(reg, &copyToClipboard, &copyToSelection);
+ bool append;
+ getRegisterType(&reg, &copyToClipboard, &copyToSelection, &append);
QString contents2 = contents;
- if (mode == RangeLineMode && !contents2.endsWith(QLatin1Char('\n')))
+ if ((mode == RangeLineMode || mode == RangeLineModeExclusive)
+ && !contents2.endsWith(QLatin1Char('\n')))
+ {
contents2.append(QLatin1Char('\n'));
+ }
if (copyToClipboard || copyToSelection) {
if (copyToClipboard)
@@ -8412,7 +8413,10 @@ void FakeVimHandler::Private::setRegister(int reg, const QString &contents, Rang
if (copyToSelection)
setClipboardData(contents2, mode, QClipboard::Selection);
} else {
- g.registers[reg].contents = contents2;
+ if (append)
+ g.registers[reg].contents.append(contents2);
+ else
+ g.registers[reg].contents = contents2;
g.registers[reg].rangemode = mode;
}
}
@@ -8421,7 +8425,7 @@ QString FakeVimHandler::Private::registerContents(int reg) const
{
bool copyFromClipboard;
bool copyFromSelection;
- getRegisterType(reg, &copyFromClipboard, &copyFromSelection);
+ getRegisterType(&reg, &copyFromClipboard, &copyFromSelection);
if (copyFromClipboard || copyFromSelection) {
QClipboard *clipboard = QApplication::clipboard();
@@ -8434,18 +8438,25 @@ QString FakeVimHandler::Private::registerContents(int reg) const
return g.registers[reg].contents;
}
-void FakeVimHandler::Private::getRegisterType(int reg, bool *isClipboard, bool *isSelection) const
+void FakeVimHandler::Private::getRegisterType(int *reg, bool *isClipboard, bool *isSelection, bool *append) const
{
bool clipboard = false;
bool selection = false;
- if (reg == QLatin1Char('"')) {
+ // If register is uppercase, append content to lower case register on yank/delete.
+ const QChar c(*reg);
+ if (append != 0)
+ *append = c.isUpper();
+ if (c.isUpper())
+ *reg = c.toLower().unicode();
+
+ if (c == QLatin1Char('"')) {
QStringList list = config(ConfigClipboard).toString().split(QLatin1Char(','));
clipboard = list.contains(_("unnamedplus"));
selection = list.contains(_("unnamed"));
- } else if (reg == QLatin1Char('+')) {
+ } else if (c == QLatin1Char('+')) {
clipboard = true;
- } else if (reg == QLatin1Char('*')) {
+ } else if (c == QLatin1Char('*')) {
selection = true;
}
@@ -8499,28 +8510,6 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
return QObject::eventFilter(ob, ev);
#endif
- // Catch mouse events on the viewport.
- QWidget *viewport = 0;
- if (d->m_plaintextedit)
- viewport = d->m_plaintextedit->viewport();
- else if (d->m_textedit)
- viewport = d->m_textedit->viewport();
- if (ob == viewport) {
- if (ev->type() == QEvent::MouseButtonRelease) {
- QMouseEvent *mev = static_cast<QMouseEvent *>(ev);
- if (mev->button() == Qt::LeftButton) {
- d->importSelection();
- //return true;
- }
- }
- if (ev->type() == QEvent::MouseButtonPress) {
- QMouseEvent *mev = static_cast<QMouseEvent *>(ev);
- if (mev->button() == Qt::LeftButton)
- Private::g.visualMode = NoVisualMode;
- }
- return QObject::eventFilter(ob, ev);
- }
-
if (ev->type() == QEvent::Shortcut) {
d->passShortcuts(false);
return false;
@@ -8552,6 +8541,11 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
return true;
}
+ if (ev->type() == QEvent::FocusOut && ob == d->editor()) {
+ d->unfocus();
+ return false;
+ }
+
if (ev->type() == QEvent::FocusIn && ob == d->editor())
d->focus();
@@ -8646,7 +8640,6 @@ void FakeVimHandler::setTextCursorPosition(int position)
d->setPosition(pos);
else
d->setAnchorAndPosition(pos, pos);
- d->m_fakeEnd = false;
d->setTargetColumn();
if (!d->m_inFakeVim)
diff --git a/src/plugins/fakevim/fakevimplugin.cpp b/src/plugins/fakevim/fakevimplugin.cpp
index bce7697a040..453d8da4656 100644
--- a/src/plugins/fakevim/fakevimplugin.cpp
+++ b/src/plugins/fakevim/fakevimplugin.cpp
@@ -1394,7 +1394,7 @@ void FakeVimPluginPrivate::showSettingsDialog()
void FakeVimPluginPrivate::triggerAction(Id id)
{
- Core::Command *cmd = ActionManager::command(id);
+ Command *cmd = ActionManager::command(id);
QTC_ASSERT(cmd, qDebug() << "UNKNOWN CODE: " << id.name(); return);
QAction *action = cmd->action();
QTC_ASSERT(action, return);
@@ -1403,7 +1403,7 @@ void FakeVimPluginPrivate::triggerAction(Id id)
void FakeVimPluginPrivate::setActionChecked(Id id, bool check)
{
- Core::Command *cmd = ActionManager::command(id);
+ Command *cmd = ActionManager::command(id);
QTC_ASSERT(cmd, return);
QAction *action = cmd->action();
QTC_ASSERT(action, return);
@@ -1709,7 +1709,7 @@ void FakeVimPluginPrivate::foldGoTo(int count, bool current)
void FakeVimPluginPrivate::jumpToGlobalMark(QChar mark, bool backTickMode,
const QString &fileName)
{
- Core::IEditor *iedit = Core::EditorManager::openEditor(fileName);
+ IEditor *iedit = EditorManager::openEditor(fileName);
if (!iedit)
return;
FakeVimHandler *handler = m_editorToHandler.value(iedit, 0);
@@ -1810,7 +1810,7 @@ void FakeVimPluginPrivate::editorOpened(IEditor *editor)
connect(ICore::instance(), SIGNAL(saveSettingsRequested()),
SLOT(writeSettings()));
- handler->setCurrentFileName(editor->document()->filePath());
+ handler->setCurrentFileName(editor->document()->filePath().toString());
handler->installEventFilter();
// pop up the bar
@@ -1853,8 +1853,8 @@ void FakeVimPluginPrivate::setUseFakeVim(const QVariant &value)
{
//qDebug() << "SET USE FAKEVIM" << value;
bool on = value.toBool();
- if (Core::FindPlugin::instance())
- Core::FindPlugin::instance()->setUseFakeVim(on);
+ if (FindPlugin::instance())
+ FindPlugin::instance()->setUseFakeVim(on);
setUseFakeVimInternal(on);
setShowRelativeLineNumbers(theFakeVimSetting(ConfigRelativeNumber)->value());
}
@@ -1970,7 +1970,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()->filePath() == fileName) {
+ if (editor && editor->document()->filePath().toString() == fileName) {
// Handle that as a special case for nicer interaction with core
DocumentManager::saveDocument(editor->document());
// Check result by reading back.
@@ -2050,7 +2050,7 @@ void FakeVimPluginPrivate::handleExCommand(bool *handled, const ExCommand &cmd)
const QString &id = it.key();
QRegExp re = it.value();
if (!re.pattern().isEmpty() && re.indexIn(cmd.cmd) != -1) {
- triggerAction(Core::Id::fromString(id));
+ triggerAction(Id::fromString(id));
return;
}
}
@@ -2188,7 +2188,7 @@ void FakeVimPluginPrivate::highlightMatches(const QString &needle)
{
foreach (IEditor *editor, EditorManager::visibleEditors()) {
QWidget *w = editor->widget();
- Core::IFindSupport *find = Aggregation::query<Core::IFindSupport>(w);
+ IFindSupport *find = Aggregation::query<IFindSupport>(w);
if (find != 0)
find->highlightAll(needle, FindRegularExpression | FindCaseSensitively);
}
@@ -2272,10 +2272,11 @@ void FakeVimPlugin::extensionsInitialized()
void FakeVimPlugin::setupTest(QString *title, FakeVimHandler **handler, QWidget **edit)
{
*title = QString::fromLatin1("test.cpp");
- Core::IEditor *iedit = Core::EditorManager::openEditorWithContents(Core::Id(), title);
- Core::EditorManager::activateEditor(iedit);
+ IEditor *iedit = EditorManager::openEditorWithContents(Id(), title);
+ EditorManager::activateEditor(iedit);
*edit = iedit->widget();
*handler = d->m_editorToHandler.value(iedit, 0);
+ (*handler)->setupWidget();
(*handler)->handleCommand(_("set startofline"));
// *handler = 0;
diff --git a/src/plugins/fakevim/fakevimplugin.h b/src/plugins/fakevim/fakevimplugin.h
index 3bfbe3e4392..ece5052ad2e 100644
--- a/src/plugins/fakevim/fakevimplugin.h
+++ b/src/plugins/fakevim/fakevimplugin.h
@@ -61,17 +61,37 @@ private:
#ifdef WITH_TESTS
private slots:
void cleanup();
+
void test_vim_movement();
+
+ void test_vim_target_column_normal();
+ void test_vim_target_column_visual_char();
+ void test_vim_target_column_visual_block();
+ void test_vim_target_column_visual_line();
+ void test_vim_target_column_insert();
+ void test_vim_target_column_replace();
+
void test_vim_insert();
void test_vim_fFtT();
void test_vim_transform_numbers();
void test_vim_delete();
+
void test_vim_delete_inner_word();
void test_vim_delete_a_word();
void test_vim_change_a_word();
+
void test_vim_change_replace();
+
void test_vim_block_selection();
void test_vim_block_selection_insert();
+
+ void test_vim_delete_inner_paragraph();
+ void test_vim_delete_a_paragraph();
+ void test_vim_change_inner_paragraph();
+ void test_vim_change_a_paragraph();
+ void test_vim_select_inner_paragraph();
+ void test_vim_select_a_paragraph();
+
void test_vim_repeat();
void test_vim_search();
void test_vim_indent();
@@ -142,6 +162,7 @@ private slots:
void test_vim_visual_d();
void test_vim_Visual_d();
+ void test_vim_visual_block_D();
void test_macros();
diff --git a/src/plugins/genericprojectmanager/cppmodelmanagerhelper.cpp b/src/plugins/genericprojectmanager/cppmodelmanagerhelper.cpp
deleted file mode 100644
index f359b3614c1..00000000000
--- a/src/plugins/genericprojectmanager/cppmodelmanagerhelper.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "cppmodelmanagerhelper.h"
-
-#include <QCoreApplication>
-#include <QTest>
-#include <QThread>
-
-using namespace CppTools;
-using namespace GenericProjectManager::Internal::Tests;
-
-CppModelManagerHelper::CppModelManagerHelper(QObject *parent)
- : QObject(parent)
- , m_spy(cppModelManager(), SIGNAL(sourceFilesRefreshed(const QSet<QString> &)))
-{
- connect(cppModelManager(), &CppModelManager::sourceFilesRefreshed,
- this, &CppModelManagerHelper::onSourceFilesRefreshed);
-}
-
-CppModelManager *CppModelManagerHelper::cppModelManager()
-{
- return CppModelManager::instance();
-}
-
-void CppModelManagerHelper::waitForSourceFilesRefreshed(const QString &file, int timeOut)
-{
- waitForSourceFilesRefreshed(QStringList() << file, timeOut);
-}
-
-void CppModelManagerHelper::waitForSourceFilesRefreshed(const QStringList &files, int timeOut)
-{
- QTime t;
- t.start();
-
- foreach (const QString &file, files) {
- while (!m_refreshedSourceFiles.contains(file))
- QCoreApplication::processEvents();
- QVERIFY(t.elapsed() <= timeOut);
- }
- QCOMPARE(m_spy.count(), 1);
-}
-
-void CppModelManagerHelper::onSourceFilesRefreshed(const QSet<QString> &files)
-{
- m_refreshedSourceFiles.unite(files);
-}
diff --git a/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp b/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp
index aca9f9da411..5e4bc5446b3 100644
--- a/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp
+++ b/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp
@@ -115,7 +115,7 @@ void FilesSelectionWizardPage::createApplyButton(QVBoxLayout *layout)
hbox->addWidget(m_applyFilterButton);
layout->addLayout(hbox);
- connect(m_applyFilterButton, SIGNAL(clicked()), this, SLOT(applyFilter()));
+ connect(m_applyFilterButton, &QPushButton::clicked, this, &FilesSelectionWizardPage::applyFilter);
}
void FilesSelectionWizardPage::initializePage()
@@ -123,10 +123,10 @@ void FilesSelectionWizardPage::initializePage()
m_view->setModel(0);
delete m_model;
m_model = new ProjectExplorer::SelectableFilesModel(this);
- connect(m_model, SIGNAL(parsingProgress(QString)),
- this, SLOT(parsingProgress(QString)));
- connect(m_model, SIGNAL(parsingFinished()),
- this, SLOT(parsingFinished()));
+ connect(m_model, &ProjectExplorer::SelectableFilesModel::parsingProgress,
+ this, &FilesSelectionWizardPage::parsingProgress);
+ connect(m_model, &ProjectExplorer::SelectableFilesModel::parsingFinished,
+ this, &FilesSelectionWizardPage::parsingFinished);
m_model->startParsing(m_genericProjectWizardDialog->path());
m_hideFilesFilterLabel->setVisible(false);
diff --git a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
index 6b90d283f4f..8c0b6686cac 100644
--- a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
+++ b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
@@ -95,7 +95,7 @@ int GenericBuildConfigurationFactory::priority(const Target *parent) const
QList<BuildInfo *> GenericBuildConfigurationFactory::availableBuilds(const Target *parent) const
{
- QList<ProjectExplorer::BuildInfo *> result;
+ QList<BuildInfo *> result;
BuildInfo *info = createBuildInfo(parent->kit(), parent->project()->projectDirectory());
result << info;
return result;
@@ -110,7 +110,7 @@ int GenericBuildConfigurationFactory::priority(const Kit *k, const QString &proj
QList<BuildInfo *> GenericBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const
{
QList<BuildInfo *> result;
- BuildInfo *info = createBuildInfo(k, ProjectExplorer::Project::projectDirectory(Utils::FileName::fromString(projectPath)));
+ BuildInfo *info = createBuildInfo(k, Project::projectDirectory(Utils::FileName::fromString(projectPath)));
//: The name of the build configuration created by default for a generic project.
info->displayName = tr("Default");
result << info;
@@ -184,7 +184,7 @@ bool GenericBuildConfigurationFactory::canHandle(const Target *t) const
return qobject_cast<GenericProject *>(t->project());
}
-BuildInfo *GenericBuildConfigurationFactory::createBuildInfo(const ProjectExplorer::Kit *k,
+BuildInfo *GenericBuildConfigurationFactory::createBuildInfo(const Kit *k,
const Utils::FileName &buildDir) const
{
BuildInfo *info = new BuildInfo(this);
@@ -215,7 +215,8 @@ GenericBuildSettingsWidget::GenericBuildSettingsWidget(GenericBuildConfiguration
m_pathChooser->setHistoryCompleter(QLatin1String("Generic.BuildDir.History"));
m_pathChooser->setEnabled(true);
fl->addRow(tr("Build directory:"), m_pathChooser);
- connect(m_pathChooser, SIGNAL(changed(QString)), this, SLOT(buildDirectoryChanged()));
+ connect(m_pathChooser, &Utils::PathChooser::changed,
+ this, &GenericBuildSettingsWidget::buildDirectoryChanged);
m_buildConfiguration = bc;
m_pathChooser->setBaseFileName(bc->target()->project()->projectDirectory());
@@ -223,7 +224,8 @@ GenericBuildSettingsWidget::GenericBuildSettingsWidget(GenericBuildConfiguration
m_pathChooser->setPath(m_buildConfiguration->rawBuildDirectory().toString());
setDisplayName(tr("Generic Manager"));
- connect(bc, SIGNAL(environmentChanged()), this, SLOT(environmentHasChanged()));
+ connect(bc, &GenericBuildConfiguration::environmentChanged,
+ this, &GenericBuildSettingsWidget::environmentHasChanged);
}
void GenericBuildSettingsWidget::buildDirectoryChanged()
diff --git a/src/plugins/genericprojectmanager/genericmakestep.cpp b/src/plugins/genericprojectmanager/genericmakestep.cpp
index c85b98cd4ca..1235c8ed0b6 100644
--- a/src/plugins/genericprojectmanager/genericmakestep.cpp
+++ b/src/plugins/genericprojectmanager/genericmakestep.cpp
@@ -245,12 +245,12 @@ GenericMakeStepConfigWidget::GenericMakeStepConfigWidget(GenericMakeStep *makeSt
updateMakeOverrrideLabel();
updateDetails();
- connect(m_ui->targetsList, SIGNAL(itemChanged(QListWidgetItem*)),
- this, SLOT(itemChanged(QListWidgetItem*)));
- connect(m_ui->makeLineEdit, SIGNAL(textEdited(QString)),
- this, SLOT(makeLineEditTextEdited()));
- connect(m_ui->makeArgumentsLineEdit, SIGNAL(textEdited(QString)),
- this, SLOT(makeArgumentsLineEditTextEdited()));
+ connect(m_ui->targetsList, &QListWidget::itemChanged,
+ this, &GenericMakeStepConfigWidget::itemChanged);
+ connect(m_ui->makeLineEdit, &QLineEdit::textEdited,
+ this, &GenericMakeStepConfigWidget::makeLineEditTextEdited);
+ connect(m_ui->makeArgumentsLineEdit, &QLineEdit::textEdited,
+ this, &GenericMakeStepConfigWidget::makeArgumentsLineEditTextEdited);
connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
this, SLOT(updateMakeOverrrideLabel()));
@@ -260,10 +260,10 @@ GenericMakeStepConfigWidget::GenericMakeStepConfigWidget(GenericMakeStep *makeSt
connect(m_makeStep->target(), SIGNAL(kitChanged()),
this, SLOT(updateMakeOverrrideLabel()));
- connect(pro, SIGNAL(environmentChanged()),
- this, SLOT(updateMakeOverrrideLabel()));
- connect(pro, SIGNAL(environmentChanged()),
- this, SLOT(updateDetails()));
+ connect(pro, &GenericProject::environmentChanged,
+ this, &GenericMakeStepConfigWidget::updateMakeOverrrideLabel);
+ connect(pro, &GenericProject::environmentChanged,
+ this, &GenericMakeStepConfigWidget::updateDetails);
}
GenericMakeStepConfigWidget::~GenericMakeStepConfigWidget()
diff --git a/src/plugins/genericprojectmanager/genericproject.cpp b/src/plugins/genericprojectmanager/genericproject.cpp
index 9f32515e8a7..9265fc4e544 100644
--- a/src/plugins/genericprojectmanager/genericproject.cpp
+++ b/src/plugins/genericprojectmanager/genericproject.cpp
@@ -352,16 +352,14 @@ void GenericProject::refreshCppCodeModel()
m_codeModelFuture.cancel();
- CppTools::ProjectInfo pInfo = modelManager->projectInfo(this);
- pInfo.clearProjectParts();
-
+ CppTools::ProjectInfo pInfo = CppTools::ProjectInfo(this);
CppTools::ProjectPartBuilder ppBuilder(pInfo);
ppBuilder.setIncludePaths(projectIncludePaths());
ppBuilder.setConfigFileName(configFileName());
ppBuilder.setCxxFlags(QStringList() << QLatin1String("-std=c++11"));
- const QList<Core::Id> languages = ppBuilder.createProjectPartsForFiles(files());
- foreach (Core::Id language, languages)
+ const QList<Id> languages = ppBuilder.createProjectPartsForFiles(files());
+ foreach (Id language, languages)
setProjectLanguage(language, true);
pInfo.finish();
@@ -449,7 +447,7 @@ GenericProjectFile::GenericProjectFile(GenericProject *parent, QString fileName,
{
setId("Generic.ProjectFile");
setMimeType(QLatin1String(Constants::GENERICMIMETYPE));
- setFilePath(fileName);
+ setFilePath(Utils::FileName::fromString(fileName));
}
bool GenericProjectFile::save(QString *, const QString &, bool)
diff --git a/src/plugins/genericprojectmanager/genericprojectmanager.pro b/src/plugins/genericprojectmanager/genericprojectmanager.pro
index 72911ca6889..c0da34edc92 100644
--- a/src/plugins/genericprojectmanager/genericprojectmanager.pro
+++ b/src/plugins/genericprojectmanager/genericprojectmanager.pro
@@ -23,7 +23,6 @@ RESOURCES += genericproject.qrc
FORMS += genericmakestep.ui
equals(TEST, 1) {
- SOURCES += genericprojectplugin_test.cpp cppmodelmanagerhelper.cpp
- HEADERS += cppmodelmanagerhelper.h
+ SOURCES += genericprojectplugin_test.cpp
DEFINES += SRCDIR=\\\"$$PWD\\\"
}
diff --git a/src/plugins/genericprojectmanager/genericprojectmanager.qbs b/src/plugins/genericprojectmanager/genericprojectmanager.qbs
index 62572d4457b..9de35a1d494 100644
--- a/src/plugins/genericprojectmanager/genericprojectmanager.qbs
+++ b/src/plugins/genericprojectmanager/genericprojectmanager.qbs
@@ -40,10 +40,7 @@ QtcPlugin {
Group {
name: "Tests"
condition: project.testsEnabled
- files: [
- "cppmodelmanagerhelper.cpp", "cppmodelmanagerhelper.h",
- "genericprojectplugin_test.cpp",
- ]
+ files: [ "genericprojectplugin_test.cpp" ]
cpp.defines: outer.concat(['SRCDIR="' + FileInfo.path(filePath) + '"'])
}
diff --git a/src/plugins/genericprojectmanager/genericprojectnodes.cpp b/src/plugins/genericprojectmanager/genericprojectnodes.cpp
index 07d51f57188..75bbb4d6bcd 100644
--- a/src/plugins/genericprojectmanager/genericprojectnodes.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectnodes.cpp
@@ -43,9 +43,11 @@ namespace GenericProjectManager {
namespace Internal {
GenericProjectNode::GenericProjectNode(GenericProject *project, Core::IDocument *projectFile)
- : ProjectNode(projectFile->filePath()), m_project(project), m_projectFile(projectFile)
+ : ProjectNode(projectFile->filePath().toString())
+ , m_project(project)
+ , m_projectFile(projectFile)
{
- setDisplayName(QFileInfo(projectFile->filePath()).completeBaseName());
+ setDisplayName(projectFile->filePath().toFileInfo().completeBaseName());
}
Core::IDocument *GenericProjectNode::projectFile() const
@@ -55,7 +57,7 @@ Core::IDocument *GenericProjectNode::projectFile() const
QString GenericProjectNode::projectFilePath() const
{
- return m_projectFile->filePath();
+ return m_projectFile->filePath().toString();
}
QHash<QString, QStringList> sortFilesIntoPaths(const QString &base, const QSet<QString> &files)
@@ -211,7 +213,7 @@ bool GenericProjectNode::showInSimpleTree() const
return true;
}
-QList<ProjectExplorer::ProjectAction> GenericProjectNode::supportedActions(Node *node) const
+QList<ProjectAction> GenericProjectNode::supportedActions(Node *node) const
{
Q_UNUSED(node);
return QList<ProjectAction>()
diff --git a/src/plugins/genericprojectmanager/genericprojectplugin.cpp b/src/plugins/genericprojectmanager/genericprojectplugin.cpp
index ce482d621a9..32f5466671f 100644
--- a/src/plugins/genericprojectmanager/genericprojectplugin.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectplugin.cpp
@@ -44,7 +44,7 @@
#include <coreplugin/actionmanager/actioncontainer.h>
#include <projectexplorer/projectexplorerconstants.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/selectablefilesmodel.h>
#include <QtPlugin>
@@ -82,10 +82,9 @@ bool GenericProjectPlugin::initialize(const QStringList &, QString *errorMessage
command->setAttribute(Command::CA_Hide);
mproject->addAction(command, ProjectExplorer::Constants::G_PROJECT_FILES);
- connect(editFilesAction, &QAction::triggered,
- this, &GenericProjectPlugin::editFiles);
+ connect(editFilesAction, &QAction::triggered, this, &GenericProjectPlugin::editFiles);
- connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::aboutToShowContextMenu,
+ connect(ProjectTree::instance(), &ProjectTree::aboutToShowContextMenu,
[this] (Project *project, Node *) { m_contextMenuProject = project; });
return true;
diff --git a/src/plugins/genericprojectmanager/genericprojectplugin_test.cpp b/src/plugins/genericprojectmanager/genericprojectplugin_test.cpp
index d1e8d641e86..2be04fd3d70 100644
--- a/src/plugins/genericprojectmanager/genericprojectplugin_test.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectplugin_test.cpp
@@ -28,100 +28,61 @@
**
****************************************************************************/
-#include "cppmodelmanagerhelper.h"
#include "genericprojectplugin.h"
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
+#include <cpptools/cppmodelmanager.h>
+#include <cpptools/cpptoolstestcase.h>
+
#include <QFileInfo>
#include <QTest>
using namespace CppTools;
+using namespace CppTools::Tests;
using namespace GenericProjectManager;
using namespace GenericProjectManager::Internal;
-using namespace GenericProjectManager::Internal::Tests;
using namespace ProjectExplorer;
-inline static QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
-inline static QString projectFilePath(const QString &project)
+namespace {
+
+inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
+inline QString sourceProjectPath(const QString &project)
{
const QString fileName(_(SRCDIR "/../../../tests/genericprojectmanager/") + project);
return QFileInfo(fileName).absoluteFilePath();
}
-namespace {
-class ProjectExplorerHelper
-{
-public:
- ProjectExplorerHelper()
- {
- QVERIFY(!SessionManager::hasProjects());
- }
-
- ~ProjectExplorerHelper()
- {
- foreach (Project *project, m_openProjects)
- ProjectExplorerPlugin::unloadProject(project);
- }
-
- Project *openProject(const QString &projectFile)
- {
- QString error;
- Project *project = ProjectExplorerPlugin::openProject(projectFile, &error);
- if (!error.isEmpty())
- qWarning() << error;
- if (!project)
- return 0;
- m_openProjects.append(project);
- return project;
- }
-
-private:
- QList<Project *> m_openProjects;
-};
} // anonymous namespace
-static ProjectInfo setupProject(const QByteArray &projectFile, const QByteArray &mainFile,
- ProjectExplorerHelper &pHelper)
-{
- CppModelManagerHelper cppHelper;
- Project *project = pHelper.openProject(projectFilePath(_(projectFile)));
- if (!project)
- return ProjectInfo();
-
- // Wait only for a single file: we don't really care if the file is refreshed or not, but at
- // this point we know that the C++ model manager got notified of all project parts and we can
- // retrieve them for inspection.
- cppHelper.waitForSourceFilesRefreshed(projectFilePath(_(mainFile)));
-
- CppModelManager *mm = cppHelper.cppModelManager();
- return mm->projectInfo(project);
-}
-
void GenericProjectPlugin::test_simple()
{
- ProjectExplorerHelper pHelper;
+ Tests::VerifyCleanCppModelManager verify;
+
+ TemporaryCopiedDir temporaryDir(sourceProjectPath(_("testdata_simpleproject")));
+ QVERIFY(temporaryDir.isValid());
+ const QString mainFile = temporaryDir.absolutePath("main.cpp");
+ const QString projectFile = temporaryDir.absolutePath("simpleproject.creator");
- const QByteArray mainFile("testdata_simpleproject/main.cpp");
- ProjectInfo pInfo(
- setupProject("testdata_simpleproject/simpleproject.creator", mainFile, pHelper));
+ ProjectOpenerAndCloser projects;
+ const ProjectInfo pInfo = projects.open(projectFile);
QVERIFY(pInfo.isValid());
QCOMPARE(pInfo.projectParts().size(), 1);
ProjectPart::Ptr pPart = pInfo.projectParts().first();
QVERIFY(pPart);
QCOMPARE(pPart->files.size(), 1);
- QCOMPARE(pPart->files.first().path, projectFilePath(_(mainFile)));
+ QCOMPARE(pPart->files.first().path, mainFile);
QCOMPARE(pPart->files.first().kind, ProjectFile::CXXSource);
}
-static QStringList simplify(const QList<CppTools::ProjectFile> &files, const QString &prefix)
+static QStringList simplify(const QList<ProjectFile> &files, const QString &prefix)
{
QStringList result;
- foreach (const CppTools::ProjectFile &file, files) {
+ foreach (const ProjectFile &file, files) {
if (file.path.startsWith(prefix))
result.append(file.path.mid(prefix.size()));
else
@@ -133,11 +94,14 @@ static QStringList simplify(const QList<CppTools::ProjectFile> &files, const QSt
void GenericProjectPlugin::test_mixed1()
{
- ProjectExplorerHelper pHelper;
- ProjectInfo pInfo(
- setupProject("testdata_mixedproject1/mixedproject1.creator",
- "testdata_mixedproject1/main.cpp",
- pHelper));
+ Tests::VerifyCleanCppModelManager verify;
+
+ TemporaryCopiedDir temporaryDir(sourceProjectPath(_("testdata_mixedproject1/")));
+ QVERIFY(temporaryDir.isValid());
+ const QString projectFile = temporaryDir.absolutePath("mixedproject1.creator");
+
+ ProjectOpenerAndCloser projects;
+ const ProjectInfo pInfo = projects.open(projectFile);
QVERIFY(pInfo.isValid());
QCOMPARE(pInfo.projectParts().size(), 3);
@@ -147,9 +111,10 @@ void GenericProjectPlugin::test_mixed1()
return p1->displayName < p2->displayName;
});
- QStringList part0files = simplify(parts[0]->files,projectFilePath(_("testdata_mixedproject1/")));
- QStringList part1files = simplify(parts[1]->files,projectFilePath(_("testdata_mixedproject1/")));
- QStringList part2files = simplify(parts[2]->files,projectFilePath(_("testdata_mixedproject1/")));
+ const QString dirPathWithSlash = temporaryDir.path() + QLatin1Char('/');
+ const QStringList part0files = simplify(parts[0]->files, dirPathWithSlash);
+ const QStringList part1files = simplify(parts[1]->files, dirPathWithSlash);
+ const QStringList part2files = simplify(parts[2]->files, dirPathWithSlash);
QCOMPARE(parts[0]->displayName, _("mixedproject1 (C++11)"));
QCOMPARE(parts[0]->files.size(), 4);
@@ -178,11 +143,14 @@ void GenericProjectPlugin::test_mixed1()
void GenericProjectPlugin::test_mixed2()
{
- ProjectExplorerHelper pHelper;
- ProjectInfo pInfo(
- setupProject("testdata_mixedproject2/mixedproject2.creator",
- "testdata_mixedproject2/main.cpp",
- pHelper));
+ Tests::VerifyCleanCppModelManager verify;
+
+ TemporaryCopiedDir temporaryDir(sourceProjectPath(_("testdata_mixedproject2/")));
+ QVERIFY(temporaryDir.isValid());
+ const QString projectFile = temporaryDir.absolutePath("mixedproject2.creator");
+
+ ProjectOpenerAndCloser projects;
+ const ProjectInfo pInfo = projects.open(projectFile);
QVERIFY(pInfo.isValid());
QCOMPARE(pInfo.projectParts().size(), 2);
@@ -192,8 +160,9 @@ void GenericProjectPlugin::test_mixed2()
return p1->displayName < p2->displayName;
});
- QStringList part0files = simplify(parts[0]->files,projectFilePath(_("testdata_mixedproject2/")));
- QStringList part1files = simplify(parts[1]->files,projectFilePath(_("testdata_mixedproject2/")));
+ const QString dirPathWithSlash = temporaryDir.path() + QLatin1Char('/');
+ const QStringList part0files = simplify(parts[0]->files, dirPathWithSlash);
+ const QStringList part1files = simplify(parts[1]->files, dirPathWithSlash);
QCOMPARE(parts[0]->displayName, _("mixedproject2 (C++11)"));
QCOMPARE(parts[0]->files.size(), 2);
diff --git a/src/plugins/git/branchadddialog.cpp b/src/plugins/git/branchadddialog.cpp
index 7cb616605e6..b4caca3500b 100644
--- a/src/plugins/git/branchadddialog.cpp
+++ b/src/plugins/git/branchadddialog.cpp
@@ -114,7 +114,7 @@ BranchAddDialog::BranchAddDialog(const QStringList &localBranches, bool addBranc
m_ui->setupUi(this);
setWindowTitle(addBranch ? tr("Add Branch") : tr("Rename Branch"));
m_ui->branchNameEdit->setValidator(new BranchNameValidator(localBranches, this));
- connect(m_ui->branchNameEdit, SIGNAL(textChanged(QString)), this, SLOT(updateButtonStatus()));
+ connect(m_ui->branchNameEdit, &QLineEdit::textChanged, this, &BranchAddDialog::updateButtonStatus);
}
BranchAddDialog::~BranchAddDialog()
diff --git a/src/plugins/git/branchcheckoutdialog.cpp b/src/plugins/git/branchcheckoutdialog.cpp
index e94144db2a3..9748a008295 100644
--- a/src/plugins/git/branchcheckoutdialog.cpp
+++ b/src/plugins/git/branchcheckoutdialog.cpp
@@ -55,7 +55,8 @@ BranchCheckoutDialog::BranchCheckoutDialog(QWidget *parent,
foundNoLocalChanges();
}
- connect(m_ui->moveChangesRadioButton, SIGNAL(toggled(bool)), this, SLOT(updatePopStashCheckBox(bool)));
+ connect(m_ui->moveChangesRadioButton, &QRadioButton::toggled,
+ this, &BranchCheckoutDialog::updatePopStashCheckBox);
}
BranchCheckoutDialog::~BranchCheckoutDialog()
diff --git a/src/plugins/git/branchmodel.cpp b/src/plugins/git/branchmodel.cpp
index 3c0f6a1b71e..b34a4d3453c 100644
--- a/src/plugins/git/branchmodel.cpp
+++ b/src/plugins/git/branchmodel.cpp
@@ -614,7 +614,7 @@ QModelIndex BranchModel::addBranch(const QString &name, bool track, const QModel
local = child;
}
int pos = positionForName(local, leafName);
- BranchNode *newNode = new BranchNode(leafName, startSha, track ? trackedBranch : QString());
+ auto newNode = new BranchNode(leafName, startSha, track ? trackedBranch : QString());
if (!added)
beginInsertRows(nodeToIndex(local), pos, pos);
newNode->parent = local;
@@ -677,7 +677,7 @@ void BranchModel::parseOutputLine(const QString &line)
const QString name = nameParts.last();
nameParts.removeLast();
- BranchNode *newNode = new BranchNode(name, sha, lineParts.at(2));
+ auto newNode = new BranchNode(name, sha, lineParts.at(2));
root->insert(nameParts, newNode);
if (current)
m_currentBranch = newNode;
@@ -724,7 +724,7 @@ QString BranchModel::toolTip(const QString &sha) const
QStringList arguments(QLatin1String("-n1"));
arguments << sha;
if (!m_client->synchronousLog(m_workingDirectory, arguments, &output, &errorMessage,
- VcsBase::VcsBasePlugin::SuppressCommandLogging)) {
+ VcsBasePlugin::SuppressCommandLogging)) {
return errorMessage;
}
return output;
diff --git a/src/plugins/git/changeselectiondialog.cpp b/src/plugins/git/changeselectiondialog.cpp
index f9fd404254a..662e443f195 100644
--- a/src/plugins/git/changeselectiondialog.cpp
+++ b/src/plugins/git/changeselectiondialog.cpp
@@ -66,15 +66,24 @@ ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, Co
m_ui->changeNumberEdit->setFocus();
m_ui->changeNumberEdit->selectAll();
- connect(m_ui->changeNumberEdit, SIGNAL(textChanged(QString)), this, SLOT(changeTextChanged(QString)));
- connect(m_ui->workingDirectoryEdit, SIGNAL(textChanged(QString)), this, SLOT(recalculateDetails()));
- connect(m_ui->workingDirectoryEdit, SIGNAL(textChanged(QString)), this, SLOT(recalculateCompletion()));
- connect(m_ui->selectDirectoryButton, SIGNAL(clicked()), this, SLOT(chooseWorkingDirectory()));
- connect(m_ui->selectFromHistoryButton, SIGNAL(clicked()), this, SLOT(selectCommitFromRecentHistory()));
- connect(m_ui->showButton, SIGNAL(clicked()), this, SLOT(acceptShow()));
- connect(m_ui->cherryPickButton, SIGNAL(clicked()), this, SLOT(acceptCherryPick()));
- connect(m_ui->revertButton, SIGNAL(clicked()), this, SLOT(acceptRevert()));
- connect(m_ui->checkoutButton, SIGNAL(clicked()), this, SLOT(acceptCheckout()));
+ connect(m_ui->changeNumberEdit, &Utils::CompletingLineEdit::textChanged,
+ this, &ChangeSelectionDialog::changeTextChanged);
+ connect(m_ui->workingDirectoryEdit, &QLineEdit::textChanged,
+ this, &ChangeSelectionDialog::recalculateDetails);
+ connect(m_ui->workingDirectoryEdit, &QLineEdit::textChanged,
+ this, &ChangeSelectionDialog::recalculateCompletion);
+ connect(m_ui->selectDirectoryButton, &QPushButton::clicked,
+ this, &ChangeSelectionDialog::chooseWorkingDirectory);
+ connect(m_ui->selectFromHistoryButton, &QPushButton::clicked,
+ this, &ChangeSelectionDialog::selectCommitFromRecentHistory);
+ connect(m_ui->showButton, &QPushButton::clicked,
+ this, &ChangeSelectionDialog::acceptShow);
+ connect(m_ui->cherryPickButton, &QPushButton::clicked,
+ this, &ChangeSelectionDialog::acceptCherryPick);
+ connect(m_ui->revertButton, &QPushButton::clicked,
+ this, &ChangeSelectionDialog::acceptRevert);
+ connect(m_ui->checkoutButton, &QPushButton::clicked,
+ this, &ChangeSelectionDialog::acceptCheckout);
if (id == "Git.Revert")
m_ui->revertButton->setDefault(true);
@@ -85,7 +94,7 @@ ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, Co
else
m_ui->showButton->setDefault(true);
m_changeModel = new QStringListModel(this);
- QCompleter *changeCompleter = new QCompleter(m_changeModel, this);
+ auto changeCompleter = new QCompleter(m_changeModel, this);
m_ui->changeNumberEdit->setCompleter(changeCompleter);
changeCompleter->setCaseSensitivity(Qt::CaseInsensitive);
@@ -258,7 +267,8 @@ void ChangeSelectionDialog::recalculateDetails()
m_process->setWorkingDirectory(workingDir);
m_process->setProcessEnvironment(m_gitEnvironment);
- connect(m_process, SIGNAL(finished(int)), this, SLOT(setDetails(int)));
+ connect(m_process, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
+ this, &ChangeSelectionDialog::setDetails);
m_process->start(m_gitExecutable.toString(), args);
m_process->closeWriteChannel();
diff --git a/src/plugins/git/clonewizard.cpp b/src/plugins/git/clonewizard.cpp
index a55aa01488e..5570c0bd46d 100644
--- a/src/plugins/git/clonewizard.cpp
+++ b/src/plugins/git/clonewizard.cpp
@@ -35,7 +35,7 @@
#include "gitversioncontrol.h"
#include <vcsbase/vcsbaseconstants.h>
-#include <vcsbase/vcsconfigurationpage.h>
+#include <vcsbase/wizard/vcsconfigurationpage.h>
#include <utils/qtcassert.h>
using namespace VcsBase;
@@ -54,9 +54,12 @@ CloneWizard::CloneWizard(const Utils::FileName &path, QWidget *parent) :
setStartedStatus(tr("Cloning started..."));
const Internal::GitVersionControl *vc = Internal::GitPlugin::instance()->gitVersionControl();
- if (!vc->isConfigured())
- addPage(new VcsConfigurationPage(vc));
- CloneWizardPage *cwp = new CloneWizardPage;
+ if (!vc->isConfigured()) {
+ auto configPage = new VcsConfigurationPage;
+ configPage->setVersionControl(vc);
+ addPage(configPage);
+ }
+ auto cwp = new CloneWizardPage;
cwp->setPath(path.toString());
addPage(cwp);
}
diff --git a/src/plugins/git/clonewizardpage.cpp b/src/plugins/git/clonewizardpage.cpp
index d04255d211d..5ba51b19a65 100644
--- a/src/plugins/git/clonewizardpage.cpp
+++ b/src/plugins/git/clonewizardpage.cpp
@@ -123,8 +123,8 @@ VcsCommand *CloneWizardPage::createCheckoutJob(Utils::FileName *checkoutPath) co
if (d->recursiveCheckBox->isChecked())
args << QLatin1String("--recursive");
args << QLatin1String("--progress") << repository() << checkoutDir;
- VcsCommand *command = new VcsCommand(client->gitExecutable(), workingDirectory,
- client->processEnvironment());
+ auto command = new VcsCommand(client->gitExecutable(), workingDirectory,
+ client->processEnvironment());
command->addFlags(VcsBasePlugin::MergeOutputChannels);
command->addJob(args, -1);
return command;
diff --git a/src/plugins/git/commitdata.cpp b/src/plugins/git/commitdata.cpp
index db08f984c07..b0004cf3d3c 100644
--- a/src/plugins/git/commitdata.cpp
+++ b/src/plugins/git/commitdata.cpp
@@ -205,7 +205,7 @@ QStringList CommitData::filterFiles(const FileStates &state) const
{
QStringList result;
foreach (const StateFilePair &p, files) {
- if (state == p.first)
+ if (state == (p.first & ~(UnmergedFile | UnmergedUs | UnmergedThem)))
result.append(p.second);
}
return result;
diff --git a/src/plugins/git/gerrit/gerritdialog.cpp b/src/plugins/git/gerrit/gerritdialog.cpp
index 67ec7f9e111..3eabebbe060 100644
--- a/src/plugins/git/gerrit/gerritdialog.cpp
+++ b/src/plugins/git/gerrit/gerritdialog.cpp
@@ -33,6 +33,7 @@
#include "gerritparameters.h"
#include <utils/qtcassert.h>
+#include <utils/fancylineedit.h>
#include <utils/itemviews.h>
#include <coreplugin/icore.h>
@@ -58,6 +59,24 @@ namespace Internal {
static const int layoutSpacing = 5;
static const int maxTitleWidth = 350;
+class QueryValidatingLineEdit : public Utils::FancyLineEdit
+{
+ Q_OBJECT
+
+public:
+ explicit QueryValidatingLineEdit(QWidget *parent = 0);
+ void setTextColor(const QColor &c);
+
+public slots:
+ void setValid();
+ void setInvalid();
+
+private:
+ bool m_valid;
+ const QColor m_okTextColor;
+ const QColor m_errorTextColor;
+};
+
QueryValidatingLineEdit::QueryValidatingLineEdit(QWidget *parent)
: Utils::FancyLineEdit(parent)
, m_valid(true)
@@ -319,3 +338,5 @@ void GerritDialog::fetchFinished()
} // namespace Internal
} // namespace Gerrit
+
+#include "gerritdialog.moc"
diff --git a/src/plugins/git/gerrit/gerritdialog.h b/src/plugins/git/gerrit/gerritdialog.h
index 701e62949d8..bbcb2524166 100644
--- a/src/plugins/git/gerrit/gerritdialog.h
+++ b/src/plugins/git/gerrit/gerritdialog.h
@@ -31,7 +31,6 @@
#ifndef GERRIT_INTERNAL_GERRITDIALOG_H
#define GERRIT_INTERNAL_GERRITDIALOG_H
-#include <utils/fancylineedit.h>
#include <utils/pathchooser.h>
#include <QDialog>
@@ -49,31 +48,17 @@ class QDialogButtonBox;
class QTextBrowser;
QT_END_NAMESPACE
-namespace Utils { class TreeView; }
+namespace Utils {
+class FancyLineEdit;
+class TreeView;
+}
namespace Gerrit {
namespace Internal {
class GerritParameters;
class GerritModel;
class GerritChange;
-
-class QueryValidatingLineEdit : public Utils::FancyLineEdit
-{
- Q_OBJECT
-
-public:
- explicit QueryValidatingLineEdit(QWidget *parent = 0);
- void setTextColor(const QColor &c);
-
-public slots:
- void setValid();
- void setInvalid();
-
-private:
- bool m_valid;
- const QColor m_okTextColor;
- const QColor m_errorTextColor;
-};
+class QueryValidatingLineEdit;
class GerritDialog : public QDialog
{
diff --git a/src/plugins/git/gerrit/gerritmodel.cpp b/src/plugins/git/gerrit/gerritmodel.cpp
index 9a707c5a099..bc04fa25544 100644
--- a/src/plugins/git/gerrit/gerritmodel.cpp
+++ b/src/plugins/git/gerrit/gerritmodel.cpp
@@ -52,6 +52,7 @@
#include <QScopedPointer>
#include <QTimer>
#include <QApplication>
+#include <QFutureWatcher>
enum { debug = 0 };
@@ -242,6 +243,7 @@ private slots:
private:
void startQuery(const QString &query);
void errorTermination(const QString &msg);
+ void terminate();
const QSharedPointer<GerritParameters> m_parameters;
const QStringList m_queries;
@@ -251,6 +253,7 @@ private:
QByteArray m_output;
int m_currentQuery;
QFutureInterface<void> m_progress;
+ QFutureWatcher<void> m_watcher;
QStringList m_baseArguments;
};
@@ -273,6 +276,9 @@ QueryContext::QueryContext(const QStringList &queries,
this, SLOT(processFinished(int,QProcess::ExitStatus)));
connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
this, SLOT(processError(QProcess::ProcessError)));
+ connect(&m_watcher, &QFutureWatcherBase::canceled,
+ this, &QueryContext::terminate);
+ m_watcher.setFuture(m_progress.future());
m_process.setProcessEnvironment(Git::Internal::GitPlugin::instance()->
gitClient()->processEnvironment());
m_progress.setProgressRange(0, m_queries.size());
@@ -296,7 +302,7 @@ QueryContext::~QueryContext()
if (m_timer.isActive())
m_timer.stop();
m_process.disconnect(this);
- Utils::SynchronousProcess::stopProcess(m_process);
+ terminate();
}
void QueryContext::start()
@@ -312,7 +318,7 @@ void QueryContext::startQuery(const QString &query)
{
QStringList arguments = m_baseArguments;
arguments.push_back(query);
- VcsBase::VcsOutputWindow::appendCommand(
+ VcsOutputWindow::appendCommand(
m_process.workingDirectory(), Utils::FileName::fromString(m_binary), arguments);
m_timer.start();
m_process.start(m_binary, arguments);
@@ -321,19 +327,25 @@ void QueryContext::startQuery(const QString &query)
void QueryContext::errorTermination(const QString &msg)
{
+ if (!m_progress.isCanceled())
+ VcsOutputWindow::appendError(msg);
m_progress.reportCanceled();
m_progress.reportFinished();
- VcsBase::VcsOutputWindow::appendError(msg);
emit finished();
}
+void QueryContext::terminate()
+{
+ Utils::SynchronousProcess::stopProcess(m_process);
+}
+
void QueryContext::processError(QProcess::ProcessError e)
{
const QString msg = tr("Error running %1: %2").arg(m_binary, m_process.errorString());
if (e == QProcess::FailedToStart)
errorTermination(msg);
else
- VcsBase::VcsOutputWindow::appendError(msg);
+ VcsOutputWindow::appendError(msg);
}
void QueryContext::processFinished(int exitCode, QProcess::ExitStatus es)
@@ -361,7 +373,7 @@ void QueryContext::processFinished(int exitCode, QProcess::ExitStatus es)
void QueryContext::readyReadStandardError()
{
- VcsBase::VcsOutputWindow::appendError(QString::fromLocal8Bit(m_process.readAllStandardError()));
+ VcsOutputWindow::appendError(QString::fromLocal8Bit(m_process.readAllStandardError()));
}
void QueryContext::readyReadStandardOutput()
@@ -389,7 +401,7 @@ void QueryContext::timeout()
if (m_process.state() != QProcess::Running)
return;
if (box.clickedButton() == terminateButton)
- Utils::SynchronousProcess::stopProcess(m_process);
+ terminate();
else
m_timer.start();
}
@@ -597,7 +609,7 @@ static bool parseOutput(const QSharedPointer<GerritParameters> &parameters,
.arg(QString::fromLocal8Bit(line))
.arg(error.errorString());
qWarning() << errorMessage;
- VcsBase::VcsOutputWindow::appendError(errorMessage);
+ VcsOutputWindow::appendError(errorMessage);
res = false;
continue;
}
@@ -685,7 +697,7 @@ QList<QStandardItem *> GerritModel::changeToRow(const GerritChangePtr &c) const
item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
row.append(item);
}
- row[NumberColumn]->setText(QString::number(c->number));
+ row[NumberColumn]->setData(c->number, Qt::DisplayRole);
row[TitleColumn]->setText(c->title);
row[OwnerColumn]->setText(c->owner);
// Shorten columns: Display time if it is today, else date
diff --git a/src/plugins/git/gerrit/gerritplugin.cpp b/src/plugins/git/gerrit/gerritplugin.cpp
index 1982aefc900..06fc7418ccf 100644
--- a/src/plugins/git/gerrit/gerritplugin.cpp
+++ b/src/plugins/git/gerrit/gerritplugin.cpp
@@ -57,6 +57,7 @@
#include <vcsbase/vcsoutputwindow.h>
#include <utils/synchronousprocess.h>
+#include <coreplugin/messagebox.h>
#include <QDebug>
#include <QProcess>
@@ -67,6 +68,7 @@
#include <QTemporaryFile>
#include <QDir>
#include <QMap>
+#include <QFutureWatcher>
using namespace Core;
using namespace Git::Internal;
@@ -126,6 +128,7 @@ private:
void show();
void cherryPick();
void checkout();
+ void terminate();
const QSharedPointer<GerritChange> m_change;
const QString m_repository;
@@ -135,6 +138,7 @@ private:
State m_state;
QProcess m_process;
QFutureInterface<void> m_progress;
+ QFutureWatcher<void> m_watcher;
};
FetchContext::FetchContext(const QSharedPointer<GerritChange> &change,
@@ -157,6 +161,9 @@ FetchContext::FetchContext(const QSharedPointer<GerritChange> &change,
this, SLOT(processReadyReadStandardError()));
connect(&m_process, SIGNAL(readyReadStandardOutput()),
this, SLOT(processReadyReadStandardOutput()));
+ connect(&m_watcher, &QFutureWatcher<void>::canceled,
+ this, &FetchContext::terminate);
+ m_watcher.setFuture(m_progress.future());
m_process.setWorkingDirectory(repository);
m_process.setProcessEnvironment(gitClient()->processEnvironment());
m_process.closeWriteChannel();
@@ -167,7 +174,7 @@ FetchContext::~FetchContext()
if (m_progress.isRunning())
m_progress.reportFinished();
m_process.disconnect(this);
- Utils::SynchronousProcess::stopProcess(m_process);
+ terminate();
}
void FetchContext::start()
@@ -228,7 +235,8 @@ void FetchContext::processReadyReadStandardOutput()
void FetchContext::handleError(const QString &e)
{
m_state = ErrorState;
- VcsBase::VcsOutputWindow::appendError(e);
+ if (!m_progress.isCanceled())
+ VcsBase::VcsOutputWindow::appendError(e);
m_progress.reportCanceled();
m_progress.reportFinished();
deleteLater();
@@ -236,6 +244,8 @@ void FetchContext::handleError(const QString &e)
void FetchContext::processError(QProcess::ProcessError e)
{
+ if (m_progress.isCanceled())
+ return;
const QString msg = tr("Error running %1: %2").arg(m_git.toUserOutput(), m_process.errorString());
if (e == QProcess::FailedToStart)
handleError(msg);
@@ -263,6 +273,11 @@ void FetchContext::checkout()
gitClient()->stashAndCheckout(m_repository, QLatin1String("FETCH_HEAD"));
}
+void FetchContext::terminate()
+{
+ Utils::SynchronousProcess::stopProcess(m_process);
+}
+
GerritPlugin::GerritPlugin(QObject *parent)
: QObject(parent)
@@ -305,7 +320,7 @@ void GerritPlugin::updateActions(bool hasTopLevel)
m_pushToGerritCommand->action()->setEnabled(hasTopLevel);
}
-void GerritPlugin::addToLocator(Core::CommandLocator *locator)
+void GerritPlugin::addToLocator(CommandLocator *locator)
{
locator->appendCommand(m_gerritCommand);
locator->appendCommand(m_pushToGerritCommand);
@@ -316,7 +331,7 @@ void GerritPlugin::push(const QString &topLevel)
// QScopedPointer is required to delete the dialog when leaving the function
GerritPushDialog dialog(topLevel, m_reviewers, ICore::mainWindow());
- if (!dialog.valid()) {
+ if (!dialog.isValid()) {
QMessageBox::warning(ICore::mainWindow(), tr("Initialization Failed"),
tr("Failed to initialize dialog. Aborting."));
return;
@@ -357,8 +372,8 @@ void GerritPlugin::openView()
{
if (m_dialog.isNull()) {
while (!m_parameters->isValid()) {
- QMessageBox::warning(ICore::dialogParent(), tr("Error"),
- tr("Invalid Gerrit configuration. Host, user and ssh binary are mandatory."));
+ Core::AsynchronousMessageBox::warning(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;
@@ -439,7 +454,7 @@ void GerritPlugin::fetch(const QSharedPointer<GerritChange> &change, int mode)
QString repository;
bool verifiedRepository = false;
if (!m_dialog.isNull() && !m_parameters.isNull() && QFile::exists(m_dialog->repositoryPath()))
- repository = Core::VcsManager::findTopLevelForDirectory(m_dialog->repositoryPath());
+ repository = VcsManager::findTopLevelForDirectory(m_dialog->repositoryPath());
if (!repository.isEmpty()) {
// Check if remote from a working dir is the same as remote from patch
@@ -536,7 +551,7 @@ QString GerritPlugin::findLocalRepository(QString project, const QString &branch
branchRegexp.reset(); // Oops.
}
foreach (const QString &repository, gitRepositories) {
- const QString fileName = QFileInfo(repository).fileName();
+ const QString fileName = Utils::FileName::fromString(repository).fileName();
if ((!branchRegexp.isNull() && branchRegexp->exactMatch(fileName))
|| fileName == project) {
// Perform a check on the branch.
@@ -550,7 +565,7 @@ QString GerritPlugin::findLocalRepository(QString project, const QString &branch
} // branchRegexp or file name match
} // for repositories
// No match, do we have a projects folder?
- if (Core::DocumentManager::useProjectsDirectory())
+ if (DocumentManager::useProjectsDirectory())
return DocumentManager::projectsDirectory();
return QDir::currentPath();
diff --git a/src/plugins/git/gerrit/gerritpushdialog.cpp b/src/plugins/git/gerrit/gerritpushdialog.cpp
index bb16b24d911..df58cda6c68 100644
--- a/src/plugins/git/gerrit/gerritpushdialog.cpp
+++ b/src/plugins/git/gerrit/gerritpushdialog.cpp
@@ -136,7 +136,7 @@ GerritPushDialog::GerritPushDialog(const QString &workingDir, const QString &rev
QDialog(parent),
m_workingDir(workingDir),
m_ui(new Ui::GerritPushDialog),
- m_valid(false)
+ m_isValid(false)
{
m_client = GitPlugin::instance()->gitClient();
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
@@ -166,7 +166,7 @@ GerritPushDialog::GerritPushDialog(const QString &workingDir, const QString &rev
m_ui->reviewersLineEdit->setValidator(noSpaceValidator);
m_ui->topicLineEdit->setValidator(noSpaceValidator);
- m_valid = true;
+ m_isValid = true;
}
GerritPushDialog::~GerritPushDialog()
@@ -216,9 +216,9 @@ void GerritPushDialog::setChangeRange()
.arg(calculateChangeRange(branch)));
}
-bool GerritPushDialog::valid() const
+bool GerritPushDialog::isValid() const
{
- return m_valid;
+ return m_isValid;
}
void GerritPushDialog::setRemoteBranches(bool includeOld)
diff --git a/src/plugins/git/gerrit/gerritpushdialog.h b/src/plugins/git/gerrit/gerritpushdialog.h
index 2ba3f2f0d39..9dfc2496fce 100644
--- a/src/plugins/git/gerrit/gerritpushdialog.h
+++ b/src/plugins/git/gerrit/gerritpushdialog.h
@@ -58,7 +58,7 @@ public:
QString selectedPushType() const;
QString selectedTopic() const;
QString reviewers() const;
- bool valid() const;
+ bool isValid() const;
private slots:
void setChangeRange();
@@ -76,7 +76,7 @@ private:
QString m_suggestedRemoteBranch;
Ui::GerritPushDialog *m_ui;
RemoteBranchesMap m_remoteBranches;
- bool m_valid;
+ bool m_isValid;
Git::Internal::GitClient *m_client;
};
diff --git a/src/plugins/git/gitclient.cpp b/src/plugins/git/gitclient.cpp
index 232cca6dbbe..d234bbcbf7b 100644
--- a/src/plugins/git/gitclient.cpp
+++ b/src/plugins/git/gitclient.cpp
@@ -33,6 +33,7 @@
#include "commitdata.h"
#include "gitconstants.h"
+#include "giteditor.h"
#include "gitplugin.h"
#include "gitsubmiteditor.h"
#include "gitversioncontrol.h"
@@ -88,6 +89,7 @@ static const char noColorOption[] = "--no-color";
static const char decorateOption[] = "--decorate";
using namespace Core;
+using namespace DiffEditor;
using namespace Utils;
using namespace VcsBase;
@@ -105,8 +107,7 @@ class GitDiffHandler : public QObject
Q_OBJECT
public:
- GitDiffHandler(DiffEditor::DiffEditorController *controller,
- const QString &workingDirectory);
+ GitDiffHandler(DiffEditorController *controller, const QString &workingDirectory);
// index -> working tree
void diffFile(const QString &fileName);
@@ -142,7 +143,7 @@ private:
QProcessEnvironment processEnvironment() const;
FileName gitPath() const;
- QPointer<DiffEditor::DiffEditorController> m_controller;
+ QPointer<DiffEditorController> m_controller;
const QString m_workingDirectory;
GitClient *m_gitClient;
const QString m_waitMessage;
@@ -150,7 +151,7 @@ private:
QString m_id;
};
-GitDiffHandler::GitDiffHandler(DiffEditor::DiffEditorController *controller,
+GitDiffHandler::GitDiffHandler(DiffEditorController *controller,
const QString &workingDirectory)
: m_controller(controller),
m_workingDirectory(workingDirectory),
@@ -222,11 +223,10 @@ void GitDiffHandler::postCollectShowDescription(const QString &id)
m_controller->requestSaveState();
m_controller->clear(m_waitMessage);
- VcsCommand *command = new VcsCommand(gitPath(), m_workingDirectory, processEnvironment());
+ auto command = new VcsCommand(gitPath(), m_workingDirectory, processEnvironment());
command->setCodec(m_gitClient->encoding(m_workingDirectory,
"i18n.commitEncoding"));
- connect(command, SIGNAL(output(QString)),
- this, SLOT(slotShowDescriptionReceived(QString)));
+ connect(command, &VcsCommand::output, this, &GitDiffHandler::slotShowDescriptionReceived);
QStringList arguments;
arguments << QLatin1String("show")
<< QLatin1String("-s")
@@ -311,10 +311,9 @@ void GitDiffHandler::postCollectTextualDiffOutput(const QString &gitCommand, con
m_controller->requestSaveState();
m_controller->clear(m_waitMessage);
- VcsCommand *command = new VcsCommand(gitPath(), m_workingDirectory, processEnvironment());
+ auto command = new VcsCommand(gitPath(), m_workingDirectory, processEnvironment());
command->setCodec(EditorManager::defaultTextCodec());
- connect(command, SIGNAL(output(QString)),
- this, SLOT(slotTextualDiffOutputReceived(QString)));
+ connect(command, &VcsCommand::output, this, &GitDiffHandler::slotTextualDiffOutputReceived);
command->addFlags(diffExecutionFlags());
for (int i = 0; i < argumentsList.count(); i++)
@@ -331,8 +330,7 @@ void GitDiffHandler::slotTextualDiffOutputReceived(const QString &contents)
}
bool ok;
- QList<DiffEditor::FileData> fileDataList
- = DiffEditor::DiffUtils::readPatch(contents, &ok);
+ QList<FileData> fileDataList = DiffUtils::readPatch(contents, &ok);
m_controller->setDiffFiles(fileDataList, m_workingDirectory);
m_controller->requestRestoreState();
deleteLater();
@@ -355,7 +353,7 @@ FileName GitDiffHandler::gitPath() const
/////////////////////////////////////
-class GitDiffEditorReloader : public DiffEditor::DiffEditorReloader
+class GitDiffEditorReloader : public DiffEditorReloader
{
Q_OBJECT
public:
@@ -415,9 +413,8 @@ GitDiffEditorReloader::GitDiffEditorReloader()
void GitDiffEditorReloader::reload()
{
- GitDiffHandler *handler = new GitDiffHandler(controller(),
- m_workingDirectory);
- connect(handler, SIGNAL(destroyed()), this, SLOT(reloadFinished()));
+ auto handler = new GitDiffHandler(controller(), m_workingDirectory);
+ connect(handler, &GitDiffHandler::destroyed, this, &GitDiffEditorReloader::reloadFinished);
switch (m_diffType) {
case DiffRepository:
@@ -450,32 +447,24 @@ class BaseGitDiffArgumentsWidget : public VcsBaseEditorParameterWidget
Q_OBJECT
public:
- BaseGitDiffArgumentsWidget(GitClient *client, const QString &directory,
- const QStringList &args) :
- m_workingDirectory(directory),
- m_client(client)
+ BaseGitDiffArgumentsWidget(GitSettings *settings, QWidget *parent = 0) :
+ VcsBaseEditorParameterWidget(parent)
{
- QTC_ASSERT(!directory.isEmpty(), return);
- QTC_ASSERT(m_client, return);
+ QTC_ASSERT(settings, return);
m_patienceButton = addToggleButton(
QLatin1String("--patience"),
tr("Patience"),
tr("Use the patience algorithm for calculating the differences."));
- mapSetting(m_patienceButton, client->settings()->boolPointer(
- GitSettings::diffPatienceKey));
+ mapSetting(m_patienceButton, settings->boolPointer(GitSettings::diffPatienceKey));
m_ignoreWSButton = addToggleButton(
QLatin1String("--ignore-space-change"), tr("Ignore Whitespace"),
tr("Ignore whitespace only changes."));
mapSetting(m_ignoreWSButton,
- m_client->settings()->boolPointer(GitSettings::ignoreSpaceChangesInDiffKey));
-
- setBaseArguments(args);
+ settings->boolPointer(GitSettings::ignoreSpaceChangesInDiffKey));
}
protected:
- QString m_workingDirectory;
- GitClient *m_client;
QToolButton *m_patienceButton;
QToolButton *m_ignoreWSButton;
};
@@ -485,44 +474,16 @@ class GitBlameArgumentsWidget : public VcsBaseEditorParameterWidget
Q_OBJECT
public:
- GitBlameArgumentsWidget(Git::Internal::GitClient *client,
- const QString &directory,
- const QStringList &args,
- const QString &revision, const QString &fileName) :
- m_editor(0),
- m_client(client),
- m_workingDirectory(directory),
- m_revision(revision),
- m_fileName(fileName)
+ GitBlameArgumentsWidget(GitSettings *settings, QWidget *parent = 0) :
+ VcsBaseEditorParameterWidget(parent)
{
mapSetting(addToggleButton(QString(), tr("Omit Date"),
tr("Hide the date of a change from the output.")),
- m_client->settings()->boolPointer(GitSettings::omitAnnotationDateKey));
+ settings->boolPointer(GitSettings::omitAnnotationDateKey));
mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace"),
tr("Ignore whitespace only changes.")),
- m_client->settings()->boolPointer(GitSettings::ignoreSpaceChangesInBlameKey));
-
- setBaseArguments(args);
+ settings->boolPointer(GitSettings::ignoreSpaceChangesInBlameKey));
}
-
- void setEditor(VcsBaseEditorWidget *editor)
- {
- QTC_ASSERT(editor, return);
- m_editor = editor;
- }
-
- void executeCommand()
- {
- int line = VcsBaseEditor::lineNumberOfCurrentEditor();
- m_client->blame(m_workingDirectory, baseArguments(), m_fileName, m_revision, line);
- }
-
-private:
- VcsBaseEditorWidget *m_editor;
- GitClient *m_client;
- QString m_workingDirectory;
- QString m_revision;
- QString m_fileName;
};
class GitLogArgumentsWidget : public BaseGitDiffArgumentsWidget
@@ -530,22 +491,14 @@ class GitLogArgumentsWidget : public BaseGitDiffArgumentsWidget
Q_OBJECT
public:
- GitLogArgumentsWidget(Git::Internal::GitClient *client,
- const QString &directory,
- bool enableAnnotationContextMenu,
- const QStringList &args,
- const QString &fileName) :
- BaseGitDiffArgumentsWidget(client, directory, args),
- m_client(client),
- m_workingDirectory(directory),
- m_enableAnnotationContextMenu(enableAnnotationContextMenu)
+ GitLogArgumentsWidget(GitSettings *settings, QWidget *parent = 0) :
+ BaseGitDiffArgumentsWidget(settings, parent)
{
- QTC_ASSERT(!directory.isEmpty(), return);
QToolButton *diffButton = addToggleButton(QLatin1String("--patch"), tr("Show Diff"),
tr("Show difference."));
- mapSetting(diffButton, m_client->settings()->boolPointer(GitSettings::logDiffKey));
- connect(diffButton, SIGNAL(toggled(bool)), m_patienceButton, SLOT(setVisible(bool)));
- connect(diffButton, SIGNAL(toggled(bool)), m_ignoreWSButton, SLOT(setVisible(bool)));
+ mapSetting(diffButton, settings->boolPointer(GitSettings::logDiffKey));
+ connect(diffButton, &QToolButton::toggled, m_patienceButton, &QToolButton::setVisible);
+ connect(diffButton, &QToolButton::toggled, m_ignoreWSButton, &QToolButton::setVisible);
m_patienceButton->setVisible(diffButton->isChecked());
m_ignoreWSButton->setVisible(diffButton->isChecked());
QStringList graphArguments(QLatin1String("--graph"));
@@ -553,25 +506,8 @@ public:
graphArguments << (QLatin1String("--pretty=format:") + QLatin1String(graphLogFormatC));
QToolButton *graphButton = addToggleButton(graphArguments, tr("Graph"),
tr("Show textual graph log."));
- mapSetting(graphButton, m_client->settings()->boolPointer(GitSettings::graphLogKey));
- setFileName(fileName);
+ mapSetting(graphButton, settings->boolPointer(GitSettings::graphLogKey));
}
-
- void setFileName(const QString &fileNames)
- {
- m_fileName = fileNames;
- }
-
- void executeCommand()
- {
- m_client->log(m_workingDirectory, m_fileName, m_enableAnnotationContextMenu, baseArguments());
- }
-
-private:
- GitClient *m_client;
- QString m_workingDirectory;
- bool m_enableAnnotationContextMenu;
- QString m_fileName;
};
class ConflictHandler : public QObject
@@ -587,8 +523,8 @@ public:
{
if (parentCommand) {
parentCommand->addFlags(VcsBasePlugin::ExpectRepoChanges);
- connect(parentCommand, SIGNAL(output(QString)), this, SLOT(readStdOut(QString)));
- connect(parentCommand, SIGNAL(errorText(QString)), this, SLOT(readStdErr(QString)));
+ connect(parentCommand, &VcsCommand::output, this, &ConflictHandler::readStdOut);
+ connect(parentCommand, &VcsCommand::errorText, this, &ConflictHandler::readStdErr);
}
}
@@ -698,7 +634,7 @@ static inline QString msgCannotLaunch(const QString &binary)
static inline QString currentDocumentPath()
{
if (IDocument *document= EditorManager::currentDocument())
- return QFileInfo(document->filePath()).path();
+ return document->filePath().toFileInfo().path();
return QString();
}
@@ -727,12 +663,11 @@ const char *GitClient::stashNamePrefix = "stash@{";
GitClient::GitClient(GitSettings *settings) :
m_cachedGitVersion(0),
- m_msgWait(tr("Waiting for data...")),
m_settings(settings),
m_disableEditor(false)
{
QTC_CHECK(settings);
- connect(ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
+ connect(ICore::instance(), &ICore::saveSettingsRequested, this, &GitClient::saveSettings);
m_gitQtcEditor = QString::fromLatin1("\"%1\" -client -block -pid %2")
.arg(QCoreApplication::applicationFilePath())
.arg(QCoreApplication::applicationPid());
@@ -797,7 +732,7 @@ VcsBaseEditorWidget *GitClient::findExistingVCSEditor(const char *registerDynami
// Exists already
EditorManager::activateEditor(outputEditor);
- outputEditor->document()->setContents(m_msgWait.toUtf8());
+ outputEditor->document()->setContents(QByteArray()); // clear
rc = VcsBaseEditor::getVcsBaseEditor(outputEditor);
return rc;
@@ -808,27 +743,28 @@ GitDiffEditorReloader *GitClient::findOrCreateDiffEditor(const QString &document
const QString &title,
const QString &workingDirectory) const
{
- DiffEditor::DiffEditorController *controller = 0;
+ DiffEditorController *controller = 0;
GitDiffEditorReloader *reloader = 0;
- DiffEditor::DiffEditorDocument *diffEditorDocument = DiffEditor::DiffEditorManager::find(documentId);
+ DiffEditorDocument *diffEditorDocument = DiffEditorManager::find(documentId);
if (diffEditorDocument) {
controller = diffEditorDocument->controller();
reloader = static_cast<GitDiffEditorReloader *>(controller->reloader());
} else {
- diffEditorDocument = DiffEditor::DiffEditorManager::findOrCreate(documentId, title);
+ diffEditorDocument = DiffEditorManager::findOrCreate(documentId, title);
QTC_ASSERT(diffEditorDocument, return 0);
controller = diffEditorDocument->controller();
- connect(controller, SIGNAL(chunkActionsRequested(QMenu*,bool)),
- this, SLOT(slotChunkActionsRequested(QMenu*,bool)), Qt::DirectConnection);
- connect(controller, SIGNAL(expandBranchesRequested(QString)),
- this, SLOT(branchesForCommit(QString)));
+ connect(controller, &DiffEditorController::chunkActionsRequested,
+ this, &GitClient::slotChunkActionsRequested, Qt::DirectConnection);
+ connect(controller, &DiffEditorController::requestBranchList,
+ this, &GitClient::branchesForCommit);
reloader = new GitDiffEditorReloader();
controller->setReloader(reloader);
reloader->setWorkingDirectory(workingDirectory);
}
+ QTC_ASSERT(reloader, return 0);
VcsBasePlugin::setSource(diffEditorDocument, source);
EditorManager::activateEditorForDocument(diffEditorDocument);
@@ -839,11 +775,11 @@ void GitClient::slotChunkActionsRequested(QMenu *menu, bool isValid)
{
menu->addSeparator();
QAction *stageChunkAction = menu->addAction(tr("Stage Chunk"));
- connect(stageChunkAction, SIGNAL(triggered()), this, SLOT(slotStageChunk()));
+ connect(stageChunkAction, &QAction::triggered, this, &GitClient::slotStageChunk);
QAction *unstageChunkAction = menu->addAction(tr("Unstage Chunk"));
- connect(unstageChunkAction, SIGNAL(triggered()), this, SLOT(slotUnstageChunk()));
+ connect(unstageChunkAction, &QAction::triggered, this, &GitClient::slotUnstageChunk);
- m_contextController = qobject_cast<DiffEditor::DiffEditorController *>(sender());
+ m_contextController = qobject_cast<DiffEditorController *>(sender());
if (!isValid || !m_contextController) {
stageChunkAction->setEnabled(false);
@@ -925,12 +861,11 @@ VcsBaseEditorWidget *GitClient::createVcsEditor(
QTC_CHECK(!findExistingVCSEditor(registerDynamicProperty, dynamicPropertyValue));
// Create new, set wait message, set up with source and codec
- IEditor *outputEditor = EditorManager::openEditorWithContents(id, &title,
- m_msgWait.toUtf8());
+ IEditor *outputEditor = EditorManager::openEditorWithContents(id, &title);
outputEditor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
rc = VcsBaseEditor::getVcsBaseEditor(outputEditor);
- connect(rc, SIGNAL(annotateRevisionRequested(QString,QString,QString,int)),
- this, SLOT(slotBlameRevisionRequested(QString,QString,QString,int)));
+ connect(rc, &VcsBaseEditorWidget::annotateRevisionRequested,
+ this, &GitClient::slotBlameRevisionRequested);
QTC_ASSERT(rc, return 0);
rc->setSource(source);
if (codecType == CodecSource)
@@ -1012,7 +947,7 @@ void GitClient::diffBranch(const QString &workingDirectory,
void GitClient::merge(const QString &workingDirectory,
const QStringList &unmergedFileNames)
{
- MergeTool *mergeTool = new MergeTool(this);
+ auto mergeTool = new MergeTool(this);
if (!mergeTool->start(workingDirectory, unmergedFileNames))
delete mergeTool;
}
@@ -1023,7 +958,7 @@ void GitClient::status(const QString &workingDirectory)
statusArgs << QLatin1String("status") << QLatin1String("-u");
VcsOutputWindow::setRepository(workingDirectory);
VcsCommand *command = executeGit(workingDirectory, statusArgs, 0, true);
- connect(command, SIGNAL(finished(bool,int,QVariant)), VcsOutputWindow::instance(), SLOT(clearRepository()),
+ connect(command, &VcsCommand::finished, VcsOutputWindow::instance(), &VcsOutputWindow::clearRepository,
Qt::QueuedConnection);
}
@@ -1035,11 +970,13 @@ void GitClient::log(const QString &workingDirectory, const QString &fileName,
const Id editorId = Git::Constants::GIT_LOG_EDITOR_ID;
const QString sourceFile = VcsBaseEditor::getSource(workingDirectory, fileName);
VcsBaseEditorWidget *editor = findExistingVCSEditor("logFileName", sourceFile);
- if (!editor)
+ if (!editor) {
+ auto *argWidget = new GitLogArgumentsWidget(settings());
+ connect(argWidget, &VcsBaseEditorParameterWidget::commandExecutionRequested,
+ [=]() { this->log(workingDirectory, fileName, enableAnnotationContextMenu, args); });
editor = createVcsEditor(editorId, title, sourceFile, CodecLogOutput, "logFileName", sourceFile,
- new GitLogArgumentsWidget(this, workingDirectory,
- enableAnnotationContextMenu,
- args, fileName));
+ argWidget);
+ }
editor->setFileLogAnnotateEnabled(enableAnnotationContextMenu);
editor->setWorkingDirectory(workingDirectory);
@@ -1051,9 +988,8 @@ void GitClient::log(const QString &workingDirectory, const QString &fileName,
if (logCount > 0)
arguments << QLatin1String("-n") << QString::number(logCount);
- GitLogArgumentsWidget *argWidget = qobject_cast<GitLogArgumentsWidget *>(editor->configurationWidget());
+ auto *argWidget = editor->configurationWidget();
argWidget->setBaseArguments(args);
- argWidget->setFileName(fileName);
QStringList userArgs = argWidget->arguments();
arguments.append(userArgs);
@@ -1160,11 +1096,14 @@ void GitClient::blame(const QString &workingDirectory,
VcsBaseEditorWidget *editor = findExistingVCSEditor("blameFileName", id);
if (!editor) {
- GitBlameArgumentsWidget *argWidget =
- new GitBlameArgumentsWidget(this, workingDirectory, args,
- revision, fileName);
+ auto *argWidget = new GitBlameArgumentsWidget(settings());
+ argWidget->setBaseArguments(args);
+ connect(argWidget, &VcsBaseEditorParameterWidget::commandExecutionRequested,
+ [=] {
+ const int line = VcsBaseEditor::lineNumberOfCurrentEditor();
+ blame(workingDirectory, args, fileName, revision, line);
+ } );
editor = createVcsEditor(editorId, title, sourceFile, CodecSource, "blameFileName", id, argWidget);
- argWidget->setEditor(editor);
}
editor->setWorkingDirectory(workingDirectory);
@@ -1713,18 +1652,17 @@ void GitClient::branchesForCommit(const QString &revision)
arguments << QLatin1String("branch") << QLatin1String(noColorOption)
<< QLatin1String("-a") << QLatin1String("--contains") << revision;
- DiffEditor::DiffEditorController *controller
- = qobject_cast<DiffEditor::DiffEditorController *>(sender());
+ auto controller = qobject_cast<DiffEditorController *>(sender());
QString workingDirectory = controller->workingDirectory();
- VcsCommand *command = new VcsCommand(gitExecutable(), workingDirectory, processEnvironment());
+ auto command = new VcsCommand(gitExecutable(), workingDirectory, processEnvironment());
command->setCodec(getSourceCodec(currentDocumentPath()));
- connect(command, SIGNAL(output(QString)), controller,
- SLOT(branchesForCommitReceived(QString)));
+ connect(command, &VcsCommand::output, controller,
+ &DiffEditorController::branchesForCommitReceived);
command->addJob(arguments, -1);
- command->execute();
command->setCookie(workingDirectory);
+ command->execute();
}
bool GitClient::isRemoteCommit(const QString &workingDirectory, const QString &commit)
@@ -1835,18 +1773,22 @@ QString GitClient::synchronousStash(const QString &workingDirectory, const QStri
bool GitClient::executeSynchronousStash(const QString &workingDirectory,
const QString &message,
+ bool unstagedOnly,
QString *errorMessage) const
{
- QByteArray outputText;
- QByteArray errorText;
QStringList arguments;
- arguments << QLatin1String("stash");
+ arguments << QLatin1String("stash") << QLatin1String("save");
+ if (unstagedOnly)
+ arguments << QLatin1String("--keep-index");
if (!message.isEmpty())
- arguments << QLatin1String("save") << message;
- const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText,
- VcsBasePlugin::ExpectRepoChanges);
+ arguments << message;
+ const unsigned flags = VcsBasePlugin::ShowStdOutInLogWindow
+ | VcsBasePlugin::ExpectRepoChanges
+ | VcsBasePlugin::ShowSuccessMessage;
+ const SynchronousProcessResponse response = synchronousGit(workingDirectory, arguments, flags);
+ const bool rc = response.result == SynchronousProcessResponse::Finished;
if (!rc)
- msgCannotRun(arguments, workingDirectory, errorText, errorMessage);
+ msgCannotRun(arguments, workingDirectory, response.stdErr.toLocal8Bit(), errorMessage);
return rc;
}
@@ -2118,21 +2060,22 @@ VcsCommand *GitClient::createCommand(const QString &workingDirectory,
bool useOutputToWindow,
int editorLineNumber)
{
- VcsCommand *command = new VcsCommand(gitExecutable(), workingDirectory, processEnvironment());
+ GitEditorWidget *gitEditor = qobject_cast<GitEditorWidget *>(editor);
+ auto command = new VcsCommand(gitExecutable(), workingDirectory, processEnvironment());
command->setCodec(getSourceCodec(currentDocumentPath()));
command->setCookie(QVariant(editorLineNumber));
- if (editor) {
- editor->setCommand(command);
- connect(command, SIGNAL(finished(bool,int,QVariant)),
- editor, SLOT(commandFinishedGotoLine(bool,int,QVariant)));
+ if (gitEditor) {
+ gitEditor->setCommand(command);
+ connect(command, &VcsCommand::finished,
+ gitEditor, &GitEditorWidget::commandFinishedGotoLine);
}
if (useOutputToWindow) {
command->addFlags(VcsBasePlugin::ShowStdOutInLogWindow);
command->addFlags(VcsBasePlugin::ShowSuccessMessage);
if (editor) // assume that the commands output is the important thing
command->addFlags(VcsBasePlugin::SilentOutput);
- } else if (editor) {
- connect(command, SIGNAL(output(QString)), editor, SLOT(setPlainTextFiltered(QString)));
+ } else if (gitEditor) {
+ connect(command, &VcsCommand::output, gitEditor, &GitEditorWidget::setPlainTextFiltered);
}
return command;
@@ -2284,7 +2227,7 @@ void GitClient::updateSubmodulesIfNeeded(const QString &workingDirectory, bool p
VcsCommand *cmd = executeGit(workingDirectory, arguments, 0, true,
VcsBasePlugin::ExpectRepoChanges);
- connect(cmd, SIGNAL(finished(bool,int,QVariant)), this, SLOT(finishSubmoduleUpdate()));
+ connect(cmd, &VcsCommand::finished, this, &GitClient::finishSubmoduleUpdate);
}
void GitClient::finishSubmoduleUpdate()
@@ -2465,6 +2408,12 @@ QString GitClient::extendedShowDescription(const QString &workingDirectory, cons
modText.insert(lastHeaderLine, QLatin1String("Precedes: ") + precedes + QLatin1Char('\n'));
if (!follows.isEmpty())
modText.insert(lastHeaderLine, QLatin1String("Follows: ") + follows + QLatin1Char('\n'));
+
+ // Empty line before headers and commit message
+ const int emptyLine = modText.indexOf(QLatin1String("\n\n"));
+ if (emptyLine != -1)
+ modText.insert(emptyLine, QLatin1Char('\n') + QLatin1String(DiffEditor::Constants::EXPAND_BRANCHES));
+
return modText;
}
@@ -2571,13 +2520,14 @@ bool GitClient::tryLauchingGitK(const QProcessEnvironment &env,
// the child), but that does not have an environment parameter.
bool success = false;
if (!settings()->stringValue(GitSettings::pathKey).isEmpty()) {
- QProcess *process = new QProcess(this);
+ auto process = new QProcess(this);
process->setWorkingDirectory(workingDirectory);
process->setProcessEnvironment(env);
process->start(binary, arguments);
success = process->waitForStarted();
if (success)
- connect(process, SIGNAL(finished(int)), process, SLOT(deleteLater()));
+ connect(process, static_cast<void (QProcess::*)(int)>(&QProcess::finished),
+ process, &QProcess::deleteLater);
else
delete process;
} else {
@@ -3027,7 +2977,7 @@ void GitClient::fetch(const QString &workingDirectory, const QString &remote)
arguments << (remote.isEmpty() ? QLatin1String("--all") : remote);
VcsCommand *command = executeGit(workingDirectory, arguments, 0, true);
command->setCookie(workingDirectory);
- connect(command, SIGNAL(success(QVariant)), this, SLOT(fetchFinished(QVariant)));
+ connect(command, &VcsCommand::success, this, &GitClient::fetchFinished);
}
bool GitClient::executeAndHandleConflicts(const QString &workingDirectory,
@@ -3327,11 +3277,6 @@ void GitClient::stashPop(const QString &workingDirectory, const QString &stash)
new ConflictHandler(cmd, workingDirectory);
}
-void GitClient::stashPop(const QString &workingDirectory)
-{
- stashPop(workingDirectory, QString());
-}
-
bool GitClient::synchronousStashRestore(const QString &workingDirectory,
const QString &stash,
bool pop,
@@ -3465,20 +3410,6 @@ bool GitClient::cloneRepository(const QString &directory,const QByteArray &url)
}
}
-QString GitClient::vcsGetRepositoryURL(const QString &directory)
-{
- QStringList arguments(QLatin1String("config"));
- QByteArray outputText;
-
- arguments << QLatin1String("remote.origin.url");
-
- if (fullySynchronousGit(directory, arguments, &outputText, 0,
- VcsBasePlugin::SuppressCommandLogging)) {
- return commandOutputFromLocal8Bit(outputText);
- }
- return QString();
-}
-
GitSettings *GitClient::settings() const
{
return m_settings;
@@ -3602,8 +3533,9 @@ void GitClient::StashInfo::stashPrompt(const QString &command, const QString &st
} else if (msgBox.clickedButton() == cancelButton) {
m_stashResult = StashCanceled;
} else if (msgBox.clickedButton() == stashButton) {
- m_stashResult = m_client->executeSynchronousStash(m_workingDir,
- creatorStashMessage(command), errorMessage) ? StashUnchanged : StashFailed;
+ const bool result = m_client->executeSynchronousStash(
+ m_workingDir, creatorStashMessage(command), false, errorMessage);
+ m_stashResult = result ? StashUnchanged : StashFailed;
} else if (msgBox.clickedButton() == stashAndPopButton) {
executeStash(command, errorMessage);
}
@@ -3612,7 +3544,7 @@ void GitClient::StashInfo::stashPrompt(const QString &command, const QString &st
void GitClient::StashInfo::executeStash(const QString &command, QString *errorMessage)
{
m_message = creatorStashMessage(command);
- if (!m_client->executeSynchronousStash(m_workingDir, m_message, errorMessage))
+ if (!m_client->executeSynchronousStash(m_workingDir, m_message, false, errorMessage))
m_stashResult = StashFailed;
else
m_stashResult = Stashed;
diff --git a/src/plugins/git/gitclient.h b/src/plugins/git/gitclient.h
index 585b3ac7090..aa358367dc9 100644
--- a/src/plugins/git/gitclient.h
+++ b/src/plugins/git/gitclient.h
@@ -202,6 +202,7 @@ public:
bool executeSynchronousStash(const QString &workingDirectory,
const QString &message = QString(),
+ bool unstagedOnly = false,
QString *errorMessage = 0) const;
bool synchronousStashRestore(const QString &workingDirectory,
const QString &stash,
@@ -253,7 +254,6 @@ public:
bool isFastForwardMerge(const QString &workingDirectory, const QString &branch);
bool cloneRepository(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
void fetch(const QString &workingDirectory, const QString &remote);
bool synchronousPull(const QString &workingDirectory, bool rebase);
void push(const QString &workingDirectory, const QStringList &pushArgs = QStringList());
@@ -279,8 +279,7 @@ public:
void synchronousSubversionFetch(const QString &workingDirectory);
void subversionLog(const QString &workingDirectory);
- void stashPop(const QString &workingDirectory, const QString &stash);
- void stashPop(const QString &workingDirectory);
+ void stashPop(const QString &workingDirectory, const QString &stash = QString());
void revert(const QStringList &files, bool revertStaging);
bool synchronousStashList(const QString &workingDirectory,
QList<Stash> *stashes,
@@ -436,7 +435,6 @@ private:
mutable Utils::FileName m_gitVersionForBinary;
mutable unsigned m_cachedGitVersion;
- const QString m_msgWait;
GitSettings *m_settings;
QString m_gitQtcEditor;
QMap<QString, StashInfo> m_stashInfo;
diff --git a/src/plugins/git/giteditor.cpp b/src/plugins/git/giteditor.cpp
index ab392a680fd..e3658150f18 100644
--- a/src/plugins/git/giteditor.cpp
+++ b/src/plugins/git/giteditor.cpp
@@ -112,7 +112,7 @@ QString GitEditorWidget::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-VcsBase::BaseAnnotationHighlighter *GitEditorWidget::createAnnotationHighlighter(const QSet<QString> &changes) const
+BaseAnnotationHighlighter *GitEditorWidget::createAnnotationHighlighter(const QSet<QString> &changes) const
{
return new GitAnnotationHighlighter(changes);
}
@@ -181,7 +181,7 @@ void GitEditorWidget::setPlainTextFiltered(const QString &text)
// If desired, filter out the date from annotation
switch (contentType())
{
- case VcsBase::AnnotateOutput: {
+ case AnnotateOutput: {
const bool omitAnnotationDate = plugin->settings().boolValue(GitSettings::omitAnnotationDateKey);
if (omitAnnotationDate)
modText = removeAnnotationDate(text);
@@ -244,7 +244,7 @@ void GitEditorWidget::stageDiffChunk()
{
const QAction *a = qobject_cast<QAction *>(sender());
QTC_ASSERT(a, return);
- const VcsBase::DiffChunk chunk = qvariant_cast<VcsBase::DiffChunk>(a->data());
+ const DiffChunk chunk = qvariant_cast<DiffChunk>(a->data());
return applyDiffChunk(chunk, false);
}
@@ -252,11 +252,11 @@ void GitEditorWidget::unstageDiffChunk()
{
const QAction *a = qobject_cast<QAction *>(sender());
QTC_ASSERT(a, return);
- const VcsBase::DiffChunk chunk = qvariant_cast<VcsBase::DiffChunk>(a->data());
+ const DiffChunk chunk = qvariant_cast<DiffChunk>(a->data());
return applyDiffChunk(chunk, true);
}
-void GitEditorWidget::applyDiffChunk(const VcsBase::DiffChunk& chunk, bool revert)
+void GitEditorWidget::applyDiffChunk(const DiffChunk& chunk, bool revert)
{
QTemporaryFile patchFile;
if (!patchFile.open())
@@ -288,7 +288,7 @@ void GitEditorWidget::applyDiffChunk(const VcsBase::DiffChunk& chunk, bool rever
void GitEditorWidget::init()
{
- VcsBase::VcsBaseEditorWidget::init();
+ VcsBaseEditorWidget::init();
Core::Id editorId = textDocument()->id();
if (editorId == Git::Constants::GIT_COMMIT_TEXT_EDITOR_ID)
textDocument()->setSyntaxHighlighter(new GitSubmitHighlighter);
@@ -296,17 +296,17 @@ void GitEditorWidget::init()
textDocument()->setSyntaxHighlighter(new GitRebaseHighlighter);
}
-void GitEditorWidget::addDiffActions(QMenu *menu, const VcsBase::DiffChunk &chunk)
+void GitEditorWidget::addDiffActions(QMenu *menu, const DiffChunk &chunk)
{
menu->addSeparator();
QAction *stageAction = menu->addAction(tr("Stage Chunk..."));
stageAction->setData(qVariantFromValue(chunk));
- connect(stageAction, SIGNAL(triggered()), this, SLOT(stageDiffChunk()));
+ connect(stageAction, &QAction::triggered, this, &GitEditorWidget::stageDiffChunk);
QAction *unstageAction = menu->addAction(tr("Unstage Chunk..."));
unstageAction->setData(qVariantFromValue(chunk));
- connect(unstageAction, SIGNAL(triggered()), this, SLOT(unstageDiffChunk()));
+ connect(unstageAction, &QAction::triggered, this, &GitEditorWidget::unstageDiffChunk);
}
bool GitEditorWidget::open(QString *errorString, const QString &fileName, const QString &realFileName)
@@ -356,7 +356,7 @@ bool GitEditorWidget::isValidRevision(const QString &revision) const
void GitEditorWidget::addChangeActions(QMenu *menu, const QString &change)
{
m_currentChange = change;
- if (contentType() != VcsBase::OtherContent) {
+ if (contentType() != OtherContent) {
menu->addAction(tr("Cherry-Pick Change %1").arg(change), this, SLOT(cherryPickChange()));
menu->addAction(tr("Revert Change %1").arg(change), this, SLOT(revertChange()));
menu->addAction(tr("Checkout Change %1").arg(change), this, SLOT(checkoutChange()));
diff --git a/src/plugins/git/giteditor.h b/src/plugins/git/giteditor.h
index 068619e4f1b..2e385d78c3e 100644
--- a/src/plugins/git/giteditor.h
+++ b/src/plugins/git/giteditor.h
@@ -51,7 +51,7 @@ public:
public slots:
void setPlainTextFiltered(const QString &text);
- // Matches the signature of the finished signal of GitCommand
+ // Matches the signature of the finished signal of GitCommand
void commandFinishedGotoLine(bool ok, int exitCode, const QVariant &v);
private slots:
diff --git a/src/plugins/git/gitplugin.cpp b/src/plugins/git/gitplugin.cpp
index 4a75e4c2864..552d16232b3 100644
--- a/src/plugins/git/gitplugin.cpp
+++ b/src/plugins/git/gitplugin.cpp
@@ -63,6 +63,7 @@
#include <coreplugin/vcsmanager.h>
#include <coreplugin/coreconstants.h>
+#include <coreplugin/messagebox.h>
#include <utils/qtcassert.h>
#include <utils/parameteraction.h>
@@ -81,7 +82,6 @@
#include <QAction>
#include <QFileDialog>
-#include <QMessageBox>
#include <QScopedPointer>
#ifdef WITH_TESTS
@@ -103,23 +103,23 @@ const char RC_GIT_MIME_XML[] = ":/git/Git.mimetypes.xml";
const VcsBaseEditorParameters editorParameters[] = {
{
- VcsBase::OtherContent,
+ OtherContent,
Git::Constants::GIT_COMMAND_LOG_EDITOR_ID,
Git::Constants::GIT_COMMAND_LOG_EDITOR_DISPLAY_NAME,
"text/vnd.qtcreator.git.commandlog"},
-{ VcsBase::LogOutput,
+{ LogOutput,
Git::Constants::GIT_LOG_EDITOR_ID,
Git::Constants::GIT_LOG_EDITOR_DISPLAY_NAME,
"text/vnd.qtcreator.git.log"},
-{ VcsBase::AnnotateOutput,
+{ AnnotateOutput,
Git::Constants::GIT_BLAME_EDITOR_ID,
Git::Constants::GIT_BLAME_EDITOR_DISPLAY_NAME,
"text/vnd.qtcreator.git.annotation"},
-{ VcsBase::OtherContent,
+{ OtherContent,
Git::Constants::GIT_COMMIT_TEXT_EDITOR_ID,
Git::Constants::GIT_COMMIT_TEXT_EDITOR_DISPLAY_NAME,
"text/vnd.qtcreator.git.commit"},
-{ VcsBase::OtherContent,
+{ OtherContent,
Git::Constants::GIT_REBASE_EDITOR_ID,
Git::Constants::GIT_REBASE_EDITOR_DISPLAY_NAME,
"text/vnd.qtcreator.git.rebase"},
@@ -186,10 +186,10 @@ ParameterAction *GitPlugin::createParameterAction(ActionContainer *ac,
bool addToLocator, const QKeySequence &keys)
{
auto action = new ParameterAction(defaultText, parameterText, ParameterAction::EnabledWithParameter, this);
- Core::Command *command = ActionManager::registerAction(action, id, context);
+ Command *command = ActionManager::registerAction(action, id, context);
if (!keys.isEmpty())
command->setDefaultKeySequence(keys);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
ac->addAction(command);
if (addToLocator)
m_commandLocator->appendCommand(command);
@@ -226,8 +226,8 @@ QAction *GitPlugin::createRepositoryAction(ActionContainer *ac,
const Context &context, bool addToLocator,
const QKeySequence &keys)
{
- QAction *action = new QAction(text, this);
- Core::Command *command = ActionManager::registerAction(action, id, context);
+ auto action = new QAction(text, this);
+ Command *command = ActionManager::registerAction(action, id, context);
if (!keys.isEmpty())
command->setDefaultKeySequence(keys);
if (ac)
@@ -293,12 +293,12 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
addAutoReleasedObject(new VcsSubmitEditorFactory(&submitParameters,
[]() { return new GitSubmitEditor(&submitParameters); }));
- auto cloneWizardFactory = new VcsBase::BaseCheckoutWizardFactory;
+ auto cloneWizardFactory = new BaseCheckoutWizardFactory;
cloneWizardFactory->setId(QLatin1String(VcsBase::Constants::VCS_ID_GIT));
cloneWizardFactory->setIcon(QIcon(QLatin1String(":/git/images/git.png")));
cloneWizardFactory->setDescription(tr("Clones a Git repository and tries to load the contained project."));
cloneWizardFactory->setDisplayName(tr("Git Repository Clone"));
- cloneWizardFactory->setWizardCreator([this] (const Utils::FileName &path, QWidget *parent) {
+ cloneWizardFactory->setWizardCreator([this] (const FileName &path, QWidget *parent) {
return new CloneWizard(path, parent);
});
addAutoReleasedObject(cloneWizardFactory);
@@ -310,7 +310,7 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
//register actions
ActionContainer *toolsContainer = ActionManager::actionContainer(Core::Constants::M_TOOLS);
- Core::ActionContainer *gitContainer = ActionManager::createMenu("Git");
+ ActionContainer *gitContainer = ActionManager::createMenu("Git");
gitContainer->menu()->setTitle(tr("&Git"));
toolsContainer->addMenu(gitContainer);
m_menuAction = gitContainer->menu()->menuAction();
@@ -502,6 +502,11 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
context, true, SLOT(stash()));
action->setToolTip(tr("Saves the current state of your work and resets the repository."));
+ action = createRepositoryAction(stashMenu, tr("Stash Unstaged Files"), "Git.StashUnstaged",
+ context, true, SLOT(stashUnstaged()));
+ action->setToolTip(tr("Saves the current state of your unstaged files and resets the repository "
+ "to its staged state."));
+
action = createRepositoryAction(stashMenu, tr("Take Snapshot..."), "Git.StashSnapshot",
context, true, SLOT(stashSnapshot()));
action->setToolTip(tr("Saves the current state of your work."));
@@ -509,7 +514,7 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
stashMenu->addSeparator(context);
action = createRepositoryAction(stashMenu, tr("Stash Pop"), "Git.StashPop",
- context, true, &GitClient::stashPop);
+ context, true, SLOT(stashPop()));
action->setToolTip(tr("Restores changes saved to the stash list using \"Stash\"."));
@@ -624,7 +629,7 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
context, false, SLOT(startChangeRelatedAction()));
m_createRepositryAction = new QAction(tr("Create Repository..."), this);
- Core::Command *createRepositoryCommand = ActionManager::registerAction(
+ Command *createRepositoryCommand = ActionManager::registerAction(
m_createRepositryAction, "Git.CreateRepository", globalcontext);
connect(m_createRepositryAction, SIGNAL(triggered()), this, SLOT(createRepository()));
gitContainer->addAction(createRepositoryCommand);
@@ -632,8 +637,8 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
// Submit editor
Context submitContext(Constants::GITSUBMITEDITOR_ID);
m_submitCurrentAction = new QAction(VcsBaseSubmitEditor::submitIcon(), tr("Commit"), this);
- Core::Command *command = ActionManager::registerAction(m_submitCurrentAction, Constants::SUBMIT_CURRENT, submitContext);
- command->setAttribute(Core::Command::CA_UpdateText);
+ Command *command = ActionManager::registerAction(m_submitCurrentAction, Constants::SUBMIT_CURRENT, submitContext);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_submitCurrentAction, SIGNAL(triggered()), this, SLOT(submitCurrentLog()));
m_diffSelectedFilesAction = new QAction(VcsBaseSubmitEditor::diffIcon(), tr("Diff &Selected Files"), this);
@@ -1035,7 +1040,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->filePath());
+ const QFileInfo editorFile = editorDocument->filePath().toFileInfo();
const QFileInfo changeFile(m_commitMessageFileName);
// Paranoia!
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
@@ -1186,19 +1191,18 @@ void GitPlugin::cleanRepository(const QString &directory)
const bool gotFiles = m_gitClient->synchronousCleanList(directory, &files, &ignoredFiles, &errorMessage);
QApplication::restoreOverrideCursor();
- QWidget *parent = ICore::mainWindow();
if (!gotFiles) {
- QMessageBox::warning(parent, tr("Unable to retrieve file list"), errorMessage);
+ Core::AsynchronousMessageBox::warning(tr("Unable to retrieve file list"), errorMessage);
return;
}
if (files.isEmpty() && ignoredFiles.isEmpty()) {
- QMessageBox::information(parent, tr("Repository Clean"),
- tr("The repository is clean."));
+ Core::AsynchronousMessageBox::information(tr("Repository Clean"),
+ tr("The repository is clean."));
return;
}
// Show in dialog
- CleanDialog dialog(parent);
+ CleanDialog dialog(ICore::dialogParent());
dialog.setFileList(directory, files, ignoredFiles);
dialog.exec();
}
@@ -1260,7 +1264,7 @@ void GitPlugin::applyPatch(const QString &workingDirectory, QString file)
m_gitClient->endStashScope(workingDirectory);
}
-void GitPlugin::stash()
+void GitPlugin::stash(bool unstagedOnly)
{
if (!DocumentManager::saveAllModifiedDocuments())
return;
@@ -1268,11 +1272,15 @@ void GitPlugin::stash()
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- QString topLevel = state.topLevel();
- if (!m_gitClient->beginStashScope(topLevel, QString(), NoPrompt))
- return;
- if (m_gitClient->stashInfo(topLevel).result() == GitClient::StashInfo::Stashed && m_stashDialog)
- m_stashDialog->refresh(state.topLevel(), true);
+ const QString topLevel = state.topLevel();
+ m_gitClient->executeSynchronousStash(topLevel, QString(), unstagedOnly);
+ if (m_stashDialog)
+ m_stashDialog->refresh(topLevel, true);
+}
+
+void GitPlugin::stashUnstaged()
+{
+ stash(true);
}
void GitPlugin::stashSnapshot()
@@ -1286,6 +1294,16 @@ void GitPlugin::stashSnapshot()
m_stashDialog->refresh(state.topLevel(), true);
}
+void GitPlugin::stashPop()
+{
+ if (!DocumentManager::saveAllModifiedDocuments())
+ return;
+ const QString repository = currentState().topLevel();
+ m_gitClient->stashPop(repository);
+ if (m_stashDialog)
+ m_stashDialog->refresh(repository, true);
+}
+
// Create a non-modal dialog with refresh function or raise if it exists
template <class NonModalDialog>
inline void showNonModalDialog(const QString &topLevel,
diff --git a/src/plugins/git/gitplugin.h b/src/plugins/git/gitplugin.h
index e042f2e2867..1d01add9885 100644
--- a/src/plugins/git/gitplugin.h
+++ b/src/plugins/git/gitplugin.h
@@ -125,8 +125,10 @@ private slots:
void startAmendCommit();
void startFixupCommit();
- void stash();
+ void stash(bool unstagedOnly = false);
+ void stashUnstaged();
void stashSnapshot();
+ void stashPop();
void branchList();
void remoteList();
void stashList();
diff --git a/src/plugins/git/gitsubmiteditor.cpp b/src/plugins/git/gitsubmiteditor.cpp
index c9a9d2ebb42..aac3ccabeec 100644
--- a/src/plugins/git/gitsubmiteditor.cpp
+++ b/src/plugins/git/gitsubmiteditor.cpp
@@ -52,10 +52,10 @@ using namespace VcsBase;
namespace Git {
namespace Internal {
-class GitSubmitFileModel : public VcsBase::SubmitFileModel
+class GitSubmitFileModel : public SubmitFileModel
{
public:
- GitSubmitFileModel(QObject *parent = 0) : VcsBase::SubmitFileModel(parent)
+ GitSubmitFileModel(QObject *parent = 0) : SubmitFileModel(parent)
{ }
void updateSelections(SubmitFileModel *source)
@@ -124,7 +124,7 @@ private:
* option for staged files. So, we sort apart the diff file lists
* according to a type flag we add to the model. */
-GitSubmitEditor::GitSubmitEditor(const VcsBase::VcsBaseSubmitEditorParameters *parameters) :
+GitSubmitEditor::GitSubmitEditor(const VcsBaseSubmitEditorParameters *parameters) :
VcsBaseSubmitEditor(parameters, new GitSubmitEditorWidget),
m_model(0),
m_commitEncoding(0),
@@ -178,14 +178,14 @@ void GitSubmitEditor::setCommitData(const CommitData &d)
it != d.files.constEnd(); ++it) {
const FileStates state = it->first;
const QString file = it->second;
- VcsBase::CheckMode checkMode;
+ CheckMode checkMode;
if (state & UnmergedFile) {
- checkMode = VcsBase::Uncheckable;
+ checkMode = Uncheckable;
w->setHasUnmerged(true);
} else if (state & StagedFile) {
- checkMode = VcsBase::Checked;
+ checkMode = Checked;
} else {
- checkMode = VcsBase::Unchecked;
+ checkMode = Unchecked;
}
m_model->addFile(file, CommitData::stateDisplayName(state), checkMode,
QVariant(static_cast<int>(state)));
diff --git a/src/plugins/git/gitsubmiteditorwidget.cpp b/src/plugins/git/gitsubmiteditorwidget.cpp
index 351dd6ee1e5..582dea38c7d 100644
--- a/src/plugins/git/gitsubmiteditorwidget.cpp
+++ b/src/plugins/git/gitsubmiteditorwidget.cpp
@@ -58,10 +58,10 @@ GitSubmitEditorWidget::GitSubmitEditorWidget() :
m_emailValidator = new QRegExpValidator(QRegExp(QLatin1String("[^@ ]+@[^@ ]+\\.[a-zA-Z]+")), this);
- connect(m_gitSubmitPanelUi.authorLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(authorInformationChanged()));
- connect(m_gitSubmitPanelUi.emailLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(authorInformationChanged()));
+ connect(m_gitSubmitPanelUi.authorLineEdit, &QLineEdit::textChanged,
+ this, &GitSubmitEditorWidget::authorInformationChanged);
+ connect(m_gitSubmitPanelUi.emailLineEdit, &QLineEdit::textChanged,
+ this, &GitSubmitEditorWidget::authorInformationChanged);
}
void GitSubmitEditorWidget::setPanelInfo(const GitSubmitEditorPanelInfo &info)
@@ -94,12 +94,13 @@ void GitSubmitEditorWidget::initialize(CommitType commitType,
return;
m_isInitialized = true;
if (commitType == FixupCommit) {
- QGroupBox *logChangeGroupBox = new QGroupBox(tr("Select Change"));
- QVBoxLayout *logChangeLayout = new QVBoxLayout;
+ auto logChangeGroupBox = new QGroupBox(tr("Select Change"));
+ auto logChangeLayout = new QVBoxLayout;
logChangeGroupBox->setLayout(logChangeLayout);
m_logChangeWidget = new LogChangeWidget;
m_logChangeWidget->init(repository);
- connect(m_logChangeWidget, SIGNAL(activated(QString)), this, SIGNAL(show(QString)));
+ connect(m_logChangeWidget, &LogChangeWidget::activated,
+ this, &GitSubmitEditorWidget::show);
logChangeLayout->addWidget(m_logChangeWidget);
insertTopWidget(logChangeGroupBox);
m_gitSubmitPanelUi.editGroup->hide();
@@ -110,7 +111,7 @@ void GitSubmitEditorWidget::initialize(CommitType commitType,
setPanelInfo(info);
if (enablePush) {
- QMenu *menu = new QMenu(this);
+ auto 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()));
diff --git a/src/plugins/git/gitversioncontrol.cpp b/src/plugins/git/gitversioncontrol.cpp
index 067eea117d9..f33409abf0a 100644
--- a/src/plugins/git/gitversioncontrol.cpp
+++ b/src/plugins/git/gitversioncontrol.cpp
@@ -98,8 +98,6 @@ bool GitVersionControl::supportsOperation(Operation operation) const
case CreateRepositoryOperation:
case SnapshotOperations:
case AnnotateOperation:
- case CheckoutOperation:
- case GetRepositoryRootOperation:
return true;
}
return false;
@@ -134,16 +132,6 @@ bool GitVersionControl::vcsCreateRepository(const QString &directory)
return m_client->synchronousInit(directory);
}
-bool GitVersionControl::vcsCheckout(const QString &directory, const QByteArray &url)
-{
- return m_client->cloneRepository(directory,url);
-}
-
-QString GitVersionControl::vcsGetRepositoryURL(const QString &directory)
-{
- return m_client->vcsGetRepositoryURL(directory);
-}
-
QString GitVersionControl::vcsTopic(const QString &directory)
{
QString topic = Core::IVersionControl::vcsTopic(directory);
diff --git a/src/plugins/git/gitversioncontrol.h b/src/plugins/git/gitversioncontrol.h
index 8f971e79c6a..cc7faad3608 100644
--- a/src/plugins/git/gitversioncontrol.h
+++ b/src/plugins/git/gitversioncontrol.h
@@ -58,8 +58,6 @@ public:
bool vcsDelete(const QString &filename);
bool vcsMove(const QString &from, const QString &to);
bool vcsCreateRepository(const QString &directory);
- bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
bool vcsAnnotate(const QString &file, int line);
QString vcsTopic(const QString &directory);
diff --git a/src/plugins/git/logchangedialog.cpp b/src/plugins/git/logchangedialog.cpp
index 4cffc844827..7e7a967765d 100644
--- a/src/plugins/git/logchangedialog.cpp
+++ b/src/plugins/git/logchangedialog.cpp
@@ -171,7 +171,7 @@ bool LogChangeWidget::populateLog(const QString &repository, const QString &comm
if (colonPos != -1) {
QList<QStandardItem *> row;
for (int c = 0; c < ColumnCount; ++c) {
- QStandardItem *item = new QStandardItem;
+ auto item = new QStandardItem;
item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
if (line.endsWith(QLatin1Char(')'))) {
QFont font = item->font();
@@ -206,10 +206,10 @@ LogChangeDialog::LogChangeDialog(bool isReset, QWidget *parent) :
, m_dialogButtonBox(new QDialogButtonBox(this))
, m_resetTypeComboBox(0)
{
- QVBoxLayout *layout = new QVBoxLayout(this);
+ auto layout = new QVBoxLayout(this);
layout->addWidget(new QLabel(isReset ? tr("Reset to:") : tr("Select change:"), this));
layout->addWidget(m_widget);
- QHBoxLayout *popUpLayout = new QHBoxLayout;
+ auto popUpLayout = new QHBoxLayout;
if (isReset) {
popUpLayout->addWidget(new QLabel(tr("Reset type:"), this));
m_resetTypeComboBox = new QComboBox(this);
diff --git a/src/plugins/git/mergetool.cpp b/src/plugins/git/mergetool.cpp
index 3df455e5261..2cbace20b25 100644
--- a/src/plugins/git/mergetool.cpp
+++ b/src/plugins/git/mergetool.cpp
@@ -36,6 +36,7 @@
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
#include <vcsbase/vcsoutputwindow.h>
+#include <coreplugin/messagebox.h>
#include <QMessageBox>
#include <QProcess>
@@ -93,8 +94,8 @@ bool MergeTool::start(const QString &workingDirectory, const QStringList &files)
arguments << QLatin1String("mergetool") << QLatin1String("-y");
if (!files.isEmpty()) {
if (m_gitClient->gitVersion() < 0x010708) {
- QMessageBox::warning(Core::ICore::dialogParent(), tr("Error"),
- tr("File input for the merge tool requires Git 1.7.8, or later."));
+ Core::AsynchronousMessageBox::warning(tr("Error"),
+ tr("File input for the merge tool requires Git 1.7.8, or later."));
return false;
}
arguments << files;
diff --git a/src/plugins/git/remotedialog.cpp b/src/plugins/git/remotedialog.cpp
index 64bafdc42ff..50fed86a59f 100644
--- a/src/plugins/git/remotedialog.cpp
+++ b/src/plugins/git/remotedialog.cpp
@@ -98,11 +98,16 @@ RemoteDialog::RemoteDialog(QWidget *parent) :
m_ui->remoteView->setModel(m_remoteModel);
new Utils::HeaderViewStretcher(m_ui->remoteView->header(), 1);
- connect(m_ui->addButton, SIGNAL(clicked()), this, SLOT(addRemote()));
- connect(m_ui->fetchButton, SIGNAL(clicked()), this, SLOT(fetchFromRemote()));
- connect(m_ui->pushButton, SIGNAL(clicked()), this, SLOT(pushToRemote()));
- connect(m_ui->removeButton, SIGNAL(clicked()), this, SLOT(removeRemote()));
- connect(m_ui->refreshButton, SIGNAL(clicked()), this, SLOT(refreshRemotes()));
+ connect(m_ui->addButton, &QPushButton::clicked,
+ this, &RemoteDialog::addRemote);
+ connect(m_ui->fetchButton, &QPushButton::clicked,
+ this, &RemoteDialog::fetchFromRemote);
+ connect(m_ui->pushButton, &QPushButton::clicked,
+ this, &RemoteDialog::pushToRemote);
+ connect(m_ui->removeButton, &QPushButton::clicked,
+ this, &RemoteDialog::removeRemote);
+ connect(m_ui->refreshButton, &QPushButton::clicked,
+ this, &RemoteDialog::refreshRemotes);
connect(m_ui->remoteView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(updateButtonState()));
diff --git a/src/plugins/git/settingspage.cpp b/src/plugins/git/settingspage.cpp
index fb3eeac5b51..4c85840d3b5 100644
--- a/src/plugins/git/settingspage.cpp
+++ b/src/plugins/git/settingspage.cpp
@@ -35,11 +35,11 @@
#include <vcsbase/vcsbaseconstants.h>
#include <utils/hostosinfo.h>
+#include <coreplugin/messagebox.h>
#include <QDir>
#include <QDebug>
#include <QTextStream>
-#include <QMessageBox>
namespace Git {
namespace Internal {
@@ -118,7 +118,7 @@ void SettingsPage::apply()
QString errorMessage;
newSettings.gitExecutable(&gitFoundOk, &errorMessage);
if (!gitFoundOk)
- QMessageBox::warning(m_widget, tr("Git Settings"), errorMessage);
+ Core::AsynchronousMessageBox::warning(tr("Git Settings"), errorMessage);
}
GitPlugin::instance()->setSettings(newSettings);
diff --git a/src/plugins/git/stashdialog.cpp b/src/plugins/git/stashdialog.cpp
index f8491fd7dcc..a430ac252d9 100644
--- a/src/plugins/git/stashdialog.cpp
+++ b/src/plugins/git/stashdialog.cpp
@@ -59,11 +59,11 @@ static inline GitClient *gitClient()
static inline QList<QStandardItem*> stashModelRowItems(const Stash &s)
{
Qt::ItemFlags itemFlags = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
- QStandardItem *nameItem = new QStandardItem(s.name);
+ auto nameItem = new QStandardItem(s.name);
nameItem->setFlags(itemFlags);
- QStandardItem *branchItem = new QStandardItem(s.branch);
+ auto branchItem = new QStandardItem(s.branch);
branchItem->setFlags(itemFlags);
- QStandardItem *messageItem = new QStandardItem(s.message);
+ auto messageItem = new QStandardItem(s.message);
messageItem->setFlags(itemFlags);
QList<QStandardItem*> rc;
rc << nameItem << branchItem << messageItem;
@@ -120,17 +120,23 @@ StashDialog::StashDialog(QWidget *parent) :
ui->filterLineEdit->setFiltering(true);
// Buttons
ui->buttonBox->addButton(m_showCurrentButton, QDialogButtonBox::ActionRole);
- connect(m_showCurrentButton, SIGNAL(clicked()), this, SLOT(showCurrent()));
+ connect(m_showCurrentButton, &QPushButton::clicked,
+ this, &StashDialog::showCurrent);
ui->buttonBox->addButton(m_refreshButton, QDialogButtonBox::ActionRole);
- connect(m_refreshButton, SIGNAL(clicked()), this, SLOT(forceRefresh()));
+ connect(m_refreshButton, &QPushButton::clicked,
+ this, &StashDialog::forceRefresh);
ui->buttonBox->addButton(m_restoreCurrentButton, QDialogButtonBox::ActionRole);
- connect(m_restoreCurrentButton, SIGNAL(clicked()), this, SLOT(restoreCurrent()));
+ connect(m_restoreCurrentButton, &QPushButton::clicked,
+ this, &StashDialog::restoreCurrent);
ui->buttonBox->addButton(m_restoreCurrentInBranchButton, QDialogButtonBox::ActionRole);
- connect(m_restoreCurrentInBranchButton, SIGNAL(clicked()), this, SLOT(restoreCurrentInBranch()));
+ connect(m_restoreCurrentInBranchButton, &QPushButton::clicked,
+ this, &StashDialog::restoreCurrentInBranch);
ui->buttonBox->addButton(m_deleteSelectionButton, QDialogButtonBox::ActionRole);
- connect(m_deleteSelectionButton, SIGNAL(clicked()), this, SLOT(deleteSelection()));
+ connect(m_deleteSelectionButton, &QPushButton::clicked,
+ this, &StashDialog::deleteSelection);
ui->buttonBox->addButton(m_deleteAllButton, QDialogButtonBox::ActionRole);
- connect(m_deleteAllButton, SIGNAL(clicked()), this, SLOT(deleteAll()));
+ connect(m_deleteAllButton, &QPushButton::clicked,
+ this, &StashDialog::deleteAll);
// Models
m_proxyModel->setSourceModel(m_model);
m_proxyModel->setFilterKeyColumn(-1);
@@ -140,12 +146,14 @@ StashDialog::StashDialog(QWidget *parent) :
ui->stashView->setSelectionMode(QAbstractItemView::ExtendedSelection);
ui->stashView->setAllColumnsShowFocus(true);
ui->stashView->setUniformRowHeights(true);
- connect(ui->filterLineEdit, SIGNAL(filterChanged(QString)), m_proxyModel, SLOT(setFilterFixedString(QString)));
+ connect(ui->filterLineEdit, &Utils::FancyLineEdit::filterChanged,
+ m_proxyModel, &QSortFilterProxyModel::setFilterFixedString);
connect(ui->stashView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
this, SLOT(enableButtons()));
connect(ui->stashView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(enableButtons()));
- connect(ui->stashView, SIGNAL(activated(QModelIndex)), this, SLOT(showCurrent()));
+ connect(ui->stashView, &Utils::TreeView::activated,
+ this, &StashDialog::showCurrent);
ui->stashView->setFocus();
}
diff --git a/src/plugins/glsleditor/glslcompletionassist.cpp b/src/plugins/glsleditor/glslcompletionassist.cpp
index 144c259f2e1..003411c5b00 100644
--- a/src/plugins/glsleditor/glslcompletionassist.cpp
+++ b/src/plugins/glsleditor/glslcompletionassist.cpp
@@ -268,7 +268,7 @@ IAssistProposal *GlslCompletionAssistProcessor::perform(const AssistInterface *i
QList<GLSL::Symbol *> members;
QStringList specialMembers;
- QList<TextEditor::AssistProposalItem *> m_completions;
+ QList<AssistProposalItem *> m_completions;
bool functionCall = (ch == QLatin1Char('(') && pos == m_interface->position() - 1);
diff --git a/src/plugins/glsleditor/glsleditor.cpp b/src/plugins/glsleditor/glsleditor.cpp
index 124a1e86e7f..73901b3db59 100644
--- a/src/plugins/glsleditor/glsleditor.cpp
+++ b/src/plugins/glsleditor/glsleditor.cpp
@@ -82,7 +82,7 @@ enum {
UPDATE_DOCUMENT_DEFAULT_INTERVAL = 150
};
-class CreateRanges: protected GLSL::Visitor
+class CreateRanges: protected Visitor
{
QTextDocument *textDocument;
Document::Ptr glslDocument;
@@ -91,12 +91,12 @@ public:
CreateRanges(QTextDocument *textDocument, Document::Ptr glslDocument)
: textDocument(textDocument), glslDocument(glslDocument) {}
- void operator()(GLSL::AST *ast) { accept(ast); }
+ void operator()(AST *ast) { accept(ast); }
protected:
using GLSL::Visitor::visit;
- virtual void endVisit(GLSL::CompoundStatementAST *ast)
+ virtual void endVisit(CompoundStatementAST *ast)
{
if (ast->symbol) {
QTextCursor tc(textDocument);
@@ -213,13 +213,13 @@ void GlslEditorWidget::updateDocumentNow()
const QByteArray preprocessedCode = contents.toLatin1(); // ### use the QtCreator C++ preprocessor.
Document::Ptr doc(new Document());
- Engine *engine = new GLSL::Engine();
- doc->_engine = new GLSL::Engine();
+ Engine engine;
+ doc->_engine = new Engine();
Parser parser(doc->_engine, preprocessedCode.constData(), preprocessedCode.size(), variant);
TranslationUnitAST *ast = parser.parse();
if (ast != 0 || extraSelections(CodeWarningsSelection).isEmpty()) {
Semantic sem;
- Scope *globalScope = engine->newNamespace();
+ Scope *globalScope = engine.newNamespace();
doc->_globalScope = globalScope;
const GlslEditorPlugin::InitFile *file = GlslEditorPlugin::shaderInit(variant);
sem.translationUnit(file->ast, globalScope, file->engine);
@@ -231,7 +231,7 @@ void GlslEditorWidget::updateDocumentNow()
file = GlslEditorPlugin::fragmentShaderInit(variant);
sem.translationUnit(file->ast, globalScope, file->engine);
}
- sem.translationUnit(ast, globalScope, engine);
+ sem.translationUnit(ast, globalScope, &engine);
CreateRanges createRanges(document(), doc);
createRanges(ast);
@@ -247,7 +247,7 @@ void GlslEditorWidget::updateDocumentNow()
QList<QTextEdit::ExtraSelection> sels;
QSet<int> errors;
- foreach (const DiagnosticMessage &m, engine->diagnosticMessages()) {
+ foreach (const DiagnosticMessage &m, engine.diagnosticMessages()) {
if (! m.line())
continue;
else if (errors.contains(m.line()))
@@ -313,7 +313,7 @@ AssistInterface *GlslEditorWidget::createAssistInterface(
if (kind == Completion)
return new GlslCompletionAssistInterface(document(),
position(),
- textDocument()->filePath(),
+ textDocument()->filePath().toString(),
reason,
textDocument()->mimeType(),
m_glslDocument);
diff --git a/src/plugins/glsleditor/glslhighlighter.cpp b/src/plugins/glsleditor/glslhighlighter.cpp
index 32f8bca0ec6..8121095d1ba 100644
--- a/src/plugins/glsleditor/glslhighlighter.cpp
+++ b/src/plugins/glsleditor/glslhighlighter.cpp
@@ -43,20 +43,20 @@ namespace Internal {
GlslHighlighter::GlslHighlighter()
{
- static QVector<TextEditor::TextStyle> categories;
+ static QVector<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;
+ categories << C_NUMBER
+ << C_STRING
+ << C_TYPE
+ << C_KEYWORD
+ << C_OPERATOR
+ << C_PREPROCESSOR
+ << C_LABEL
+ << C_COMMENT
+ << C_DOXYGEN_COMMENT
+ << C_DOXYGEN_TAG
+ << C_VISUAL_WHITESPACE
+ << C_REMOVED_LINE;
}
setTextFormatCategories(categories);
}
diff --git a/src/plugins/help/docsettingspage.cpp b/src/plugins/help/docsettingspage.cpp
index 159dbf1ec65..a1d3eff3c72 100644
--- a/src/plugins/help/docsettingspage.cpp
+++ b/src/plugins/help/docsettingspage.cpp
@@ -63,9 +63,13 @@ QWidget *DocSettingsPage::widget()
m_ui.docsListWidget->installEventFilter(this);
const QStringList nameSpaces = HelpManager::registeredNamespaces();
+ const QSet<QString> userDocumentationPaths = HelpManager::userDocumentationPaths();
foreach (const QString &nameSpace, nameSpaces) {
- addItem(nameSpace, HelpManager::fileFromNamespace(nameSpace));
- m_filesToRegister.insert(nameSpace, HelpManager::fileFromNamespace(nameSpace));
+ const QString filePath = HelpManager::fileFromNamespace(nameSpace);
+ bool user = userDocumentationPaths.contains(filePath);
+ addItem(nameSpace, filePath, user);
+ m_filesToRegister.insert(nameSpace, filePath);
+ m_filesToRegisterUserManaged.insert(nameSpace, user);
}
m_filesToUnregister.clear();
@@ -98,8 +102,9 @@ void DocSettingsPage::addDocumentation()
continue;
}
- addItem(nameSpace, file);
+ addItem(nameSpace, file, true/*user managed*/);
m_filesToRegister.insert(nameSpace, QDir::toNativeSeparators(filePath));
+ m_filesToRegisterUserManaged.insert(nameSpace, true/*user managed*/);
// If the files to unregister contains the namespace, grab a copy of all paths added and try to
// remove the current file path. Afterwards remove the whole entry and add the clean list back.
@@ -150,7 +155,14 @@ void DocSettingsPage::removeDocumentation()
void DocSettingsPage::apply()
{
HelpManager::unregisterDocumentation(m_filesToUnregister.keys());
- HelpManager::registerDocumentation(m_filesToRegister.values());
+ QStringList files;
+ auto it = m_filesToRegisterUserManaged.constBegin();
+ while (it != m_filesToRegisterUserManaged.constEnd()) {
+ if (it.value()/*userManaged*/)
+ files << m_filesToRegister.value(it.key());
+ ++it;
+ }
+ HelpManager::registerUserDocumentation(files);
m_filesToUnregister.clear();
}
@@ -185,9 +197,10 @@ void DocSettingsPage::removeDocumentation(const QList<QListWidgetItem*> &items)
int row = 0;
foreach (QListWidgetItem* item, items) {
- const QString nameSpace = item->text();
+ const QString nameSpace = item->data(Qt::UserRole).toString();
m_filesToRegister.remove(nameSpace);
+ m_filesToRegisterUserManaged.remove(nameSpace);
m_filesToUnregister.insertMulti(nameSpace, QDir::cleanPath(HelpManager::fileFromNamespace(nameSpace)));
row = m_ui.docsListWidget->row(item);
@@ -198,9 +211,11 @@ void DocSettingsPage::removeDocumentation(const QList<QListWidgetItem*> &items)
QItemSelectionModel::ClearAndSelect);
}
-void DocSettingsPage::addItem(const QString &nameSpace, const QString &fileName)
+void DocSettingsPage::addItem(const QString &nameSpace, const QString &fileName, bool userManaged)
{
- QListWidgetItem* item = new QListWidgetItem(nameSpace);
+ const QString name = userManaged ? nameSpace : tr("%1 (auto-detected)").arg(nameSpace);
+ QListWidgetItem* item = new QListWidgetItem(name);
item->setToolTip(fileName);
+ item->setData(Qt::UserRole, nameSpace);
m_ui.docsListWidget->addItem(item);
}
diff --git a/src/plugins/help/docsettingspage.h b/src/plugins/help/docsettingspage.h
index 100308f1a44..b87cc1dbf72 100644
--- a/src/plugins/help/docsettingspage.h
+++ b/src/plugins/help/docsettingspage.h
@@ -57,7 +57,7 @@ private slots:
private:
bool eventFilter(QObject *object, QEvent *event);
void removeDocumentation(const QList<QListWidgetItem *> &items);
- void addItem(const QString &nameSpace, const QString &fileName);
+ void addItem(const QString &nameSpace, const QString &fileName, bool userManaged);
private:
Ui::DocSettingsPage m_ui;
@@ -67,6 +67,7 @@ private:
typedef QHash<QString, QString> NameSpaceToPathHash;
NameSpaceToPathHash m_filesToRegister;
+ QHash<QString, bool> m_filesToRegisterUserManaged;
NameSpaceToPathHash m_filesToUnregister;
};
diff --git a/src/plugins/help/filtersettingspage.cpp b/src/plugins/help/filtersettingspage.cpp
index 55643de63e5..f9ae9459e2e 100644
--- a/src/plugins/help/filtersettingspage.cpp
+++ b/src/plugins/help/filtersettingspage.cpp
@@ -60,14 +60,14 @@ QWidget *FilterSettingsPage::widget()
updateFilterPage();
- connect(m_ui.attributeWidget, SIGNAL(itemChanged(QTreeWidgetItem*,int)),
- this, SLOT(updateFilterMap()));
- connect(m_ui.filterWidget,
- SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), this,
- SLOT(updateAttributes(QListWidgetItem*)));
- connect(m_ui.filterAddButton, SIGNAL(clicked()), this, SLOT(addFilter()));
- connect(m_ui.filterRemoveButton, SIGNAL(clicked()), this,
- SLOT(removeFilter()));
+ connect(m_ui.attributeWidget, &QTreeWidget::itemChanged,
+ this, &FilterSettingsPage::updateFilterMap);
+ connect(m_ui.filterWidget, &QListWidget::currentItemChanged,
+ this, &FilterSettingsPage::updateAttributes);
+ connect(m_ui.filterAddButton, &QPushButton::clicked,
+ this, &FilterSettingsPage::addFilter);
+ connect(m_ui.filterRemoveButton, &QPushButton::clicked,
+ this, &FilterSettingsPage::removeFilter);
connect(HelpManager::instance(), SIGNAL(documentationChanged()),
this, SLOT(updateFilterPage()));
}
diff --git a/src/plugins/help/generalsettingspage.cpp b/src/plugins/help/generalsettingspage.cpp
index ade95e8add7..e216b93da88 100644
--- a/src/plugins/help/generalsettingspage.cpp
+++ b/src/plugins/help/generalsettingspage.cpp
@@ -99,20 +99,25 @@ QWidget *GeneralSettingsPage::widget()
m_ui->helpStartComboBox->setCurrentIndex(m_startOption);
m_contextOption = HelpManager::customValue(QLatin1String("ContextHelpOption"),
- Core::HelpManager::SideBySideIfPossible).toInt();
+ HelpManager::SideBySideIfPossible).toInt();
m_ui->contextHelpComboBox->setCurrentIndex(m_contextOption);
- connect(m_ui->currentPageButton, SIGNAL(clicked()), this, SLOT(setCurrentPage()));
- connect(m_ui->blankPageButton, SIGNAL(clicked()), this, SLOT(setBlankPage()));
- connect(m_ui->defaultPageButton, SIGNAL(clicked()), this, SLOT(setDefaultPage()));
+ connect(m_ui->currentPageButton, &QPushButton::clicked,
+ this, &GeneralSettingsPage::setCurrentPage);
+ connect(m_ui->blankPageButton, &QPushButton::clicked,
+ this, &GeneralSettingsPage::setBlankPage);
+ connect(m_ui->defaultPageButton, &QPushButton::clicked,
+ this, &GeneralSettingsPage::setDefaultPage);
HelpViewer *viewer = CentralWidget::instance()->currentViewer();
if (!viewer)
m_ui->currentPageButton->setEnabled(false);
m_ui->errorLabel->setVisible(false);
- connect(m_ui->importButton, SIGNAL(clicked()), this, SLOT(importBookmarks()));
- connect(m_ui->exportButton, SIGNAL(clicked()), this, SLOT(exportBookmarks()));
+ connect(m_ui->importButton, &QPushButton::clicked,
+ this, &GeneralSettingsPage::importBookmarks);
+ connect(m_ui->exportButton, &QPushButton::clicked,
+ this, &GeneralSettingsPage::exportBookmarks);
m_returnOnClose = HelpManager::customValue(QLatin1String("ReturnOnClose"),
false).toBool();
@@ -177,7 +182,7 @@ void GeneralSettingsPage::apply()
m_contextOption = helpOption;
HelpManager::setCustomValue(QLatin1String("ContextHelpOption"), helpOption);
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->beginGroup(QLatin1String(Help::Constants::ID_MODE_HELP));
settings->setValue(QLatin1String("ContextHelpOption"), helpOption);
settings->endGroup();
@@ -212,7 +217,7 @@ void GeneralSettingsPage::importBookmarks()
{
m_ui->errorLabel->setVisible(false);
- QString fileName = QFileDialog::getOpenFileName(Core::ICore::dialogParent(),
+ QString fileName = QFileDialog::getOpenFileName(ICore::dialogParent(),
tr("Import Bookmarks"), QDir::currentPath(), tr("Files (*.xbel)"));
if (fileName.isEmpty())
@@ -234,7 +239,7 @@ void GeneralSettingsPage::exportBookmarks()
{
m_ui->errorLabel->setVisible(false);
- QString fileName = QFileDialog::getSaveFileName(Core::ICore::dialogParent(),
+ QString fileName = QFileDialog::getSaveFileName(ICore::dialogParent(),
tr("Save File"), QLatin1String("untitled.xbel"), tr("Files (*.xbel)"));
QLatin1String suffix(".xbel");
diff --git a/src/plugins/help/help.pro b/src/plugins/help/help.pro
index c296fab572c..ca6e1adb911 100644
--- a/src/plugins/help/help.pro
+++ b/src/plugins/help/help.pro
@@ -1,4 +1,4 @@
-QT += help network printsupport
+QT += help network printsupport sql
!isEmpty(QT.webkitwidgets.name): QT += webkitwidgets webkit
else: DEFINES += QT_NO_WEBKIT
@@ -67,9 +67,13 @@ osx {
QT += macextras
HEADERS += macwebkithelpviewer.h
OBJECTIVE_SOURCES += macwebkithelpviewer.mm
-
LIBS += -framework WebKit -framework AppKit
+
+ !isEmpty(USE_QUICK_WIDGET) {
+ DEFINES += QTC_MAC_NATIVE_HELPVIEWER_DEFAULT
+ }
}
+
RESOURCES += help.qrc
include(../../shared/help/help.pri)
diff --git a/src/plugins/help/help.qbs b/src/plugins/help/help.qbs
index d4b4535b6d9..af3d320666f 100644
--- a/src/plugins/help/help.qbs
+++ b/src/plugins/help/help.qbs
@@ -3,7 +3,7 @@ import qbs 1.0
QtcPlugin {
name: "Help"
- Depends { name: "Qt"; submodules: ["help", "network"]; }
+ Depends { name: "Qt"; submodules: ["help", "network", "sql"]; }
Depends { name: "Qt.printsupport" }
Depends {
name: "Qt.webkit"
diff --git a/src/plugins/help/helpfindsupport.cpp b/src/plugins/help/helpfindsupport.cpp
index a3c42cbb675..aab70e6418e 100644
--- a/src/plugins/help/helpfindsupport.cpp
+++ b/src/plugins/help/helpfindsupport.cpp
@@ -41,7 +41,7 @@ HelpViewerFindSupport::HelpViewerFindSupport(HelpViewer *viewer)
{
}
-Core::FindFlags HelpViewerFindSupport::supportedFindFlags() const
+FindFlags HelpViewerFindSupport::supportedFindFlags() const
{
return FindBackward | FindCaseSensitively;
}
@@ -52,23 +52,23 @@ QString HelpViewerFindSupport::currentFindString() const
return m_viewer->selectedText();
}
-Core::IFindSupport::Result HelpViewerFindSupport::findIncremental(const QString &txt,
- Core::FindFlags findFlags)
+IFindSupport::Result HelpViewerFindSupport::findIncremental(const QString &txt,
+ FindFlags findFlags)
{
QTC_ASSERT(m_viewer, return NotFound);
findFlags &= ~FindBackward;
return find(txt, findFlags, true) ? Found : NotFound;
}
-Core::IFindSupport::Result HelpViewerFindSupport::findStep(const QString &txt,
- Core::FindFlags findFlags)
+IFindSupport::Result HelpViewerFindSupport::findStep(const QString &txt,
+ FindFlags findFlags)
{
QTC_ASSERT(m_viewer, return NotFound);
return find(txt, findFlags, false) ? Found : NotFound;
}
bool HelpViewerFindSupport::find(const QString &txt,
- Core::FindFlags findFlags, bool incremental)
+ FindFlags findFlags, bool incremental)
{
QTC_ASSERT(m_viewer, return false);
bool wrapped = false;
diff --git a/src/plugins/help/helpindexfilter.cpp b/src/plugins/help/helpindexfilter.cpp
index 52762f46f84..8fa6074983d 100644
--- a/src/plugins/help/helpindexfilter.cpp
+++ b/src/plugins/help/helpindexfilter.cpp
@@ -37,8 +37,14 @@
#include <extensionsystem/pluginmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/helpmanager.h>
+#include <utils/algorithm.h>
#include <QIcon>
+#include <QSqlDatabase>
+#include <QSqlDriver>
+#include <QSqlError>
+#include <QSqlQuery>
+
using namespace Core;
using namespace Help;
@@ -47,6 +53,7 @@ using namespace Help::Internal;
Q_DECLARE_METATYPE(ILocatorFilter*)
HelpIndexFilter::HelpIndexFilter()
+ : m_needsUpdate(true)
{
setId("HelpIndexFilter");
setDisplayName(tr("Help Index"));
@@ -54,6 +61,12 @@ HelpIndexFilter::HelpIndexFilter()
setShortcutString(QString(QLatin1Char('?')));
m_icon = QIcon(QLatin1String(":/help/images/bookmark.png"));
+ connect(HelpManager::instance(), &HelpManager::setupFinished,
+ this, &HelpIndexFilter::invalidateCache);
+ connect(HelpManager::instance(), &HelpManager::documentationChanged,
+ this, &HelpIndexFilter::invalidateCache);
+ connect(HelpManager::instance(), &HelpManager::collectionFileChanged,
+ this, &HelpIndexFilter::invalidateCache);
}
HelpIndexFilter::~HelpIndexFilter()
@@ -62,21 +75,63 @@ HelpIndexFilter::~HelpIndexFilter()
void HelpIndexFilter::prepareSearch(const QString &entry)
{
- if (entry.length() < 2)
- m_keywords = Core::HelpManager::findKeywords(entry, caseSensitivity(entry), 200);
- else
- m_keywords = Core::HelpManager::findKeywords(entry, caseSensitivity(entry));
+ Q_UNUSED(entry)
+ QStringList namespaces = HelpManager::registeredNamespaces();
+ m_helpDatabases = Utils::transform(namespaces, [](const QString &ns) {
+ return HelpManager::fileFromNamespace(ns);
+ });
}
QList<LocatorFilterEntry> HelpIndexFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &future, const QString &entry)
{
- Q_UNUSED(entry) // search is already done in the GUI thread in prepareSearch
+ m_mutex.lock(); // guard m_needsUpdate
+ bool forceUpdate = m_needsUpdate;
+ m_mutex.unlock();
+
+ if (forceUpdate || m_searchTermCache.size() < 2 || m_searchTermCache.isEmpty()
+ || !entry.contains(m_searchTermCache)) {
+ int limit = entry.size() < 2 ? 200 : INT_MAX;
+ QSet<QString> results;
+ foreach (const QString &filePath, m_helpDatabases) {
+ QSet<QString> result;
+ QMetaObject::invokeMethod(this, "searchMatches", Qt::BlockingQueuedConnection,
+ Q_RETURN_ARG(QSet<QString>, result),
+ Q_ARG(QString, filePath),
+ Q_ARG(QString, entry),
+ Q_ARG(int, limit));
+ results.unite(result);
+ }
+ m_mutex.lock(); // guard m_needsUpdate
+ m_needsUpdate = false;
+ m_mutex.unlock();
+ m_keywordCache = results;
+ m_searchTermCache = entry;
+ }
+
+ Qt::CaseSensitivity cs = caseSensitivity(entry);
QList<LocatorFilterEntry> entries;
- foreach (const QString &keyword, m_keywords) {
+ QStringList keywords;
+ QStringList unsortedKeywords;
+ keywords.reserve(m_keywordCache.size());
+ unsortedKeywords.reserve(m_keywordCache.size());
+ QSet<QString> allresults;
+ foreach (const QString &keyword, m_keywordCache) {
if (future.isCanceled())
break;
- entries.append(LocatorFilterEntry(this, keyword, QVariant(), m_icon));
+ if (keyword.startsWith(entry, cs)) {
+ keywords.append(keyword);
+ allresults.insert(keyword);
+ } else if (keyword.contains(entry, cs)) {
+ unsortedKeywords.append(keyword);
+ allresults.insert(keyword);
+ }
}
+ Utils::sort(keywords);
+ keywords << unsortedKeywords;
+ m_keywordCache = allresults;
+ m_searchTermCache = entry;
+ foreach (const QString &keyword, keywords)
+ entries.append(LocatorFilterEntry(this, keyword, QVariant(), m_icon));
return entries;
}
@@ -84,7 +139,7 @@ QList<LocatorFilterEntry> HelpIndexFilter::matchesFor(QFutureInterface<LocatorFi
void HelpIndexFilter::accept(LocatorFilterEntry selection) const
{
const QString &key = selection.displayName;
- const QMap<QString, QUrl> &links = Core::HelpManager::linksForKeyword(key);
+ const QMap<QString, QUrl> &links = HelpManager::linksForKeyword(key);
if (links.size() == 1)
emit linkActivated(links.begin().value());
@@ -95,5 +150,42 @@ void HelpIndexFilter::accept(LocatorFilterEntry selection) const
void HelpIndexFilter::refresh(QFutureInterface<void> &future)
{
Q_UNUSED(future)
- // Nothing to refresh
+ invalidateCache();
+}
+
+QSet<QString> HelpIndexFilter::searchMatches(const QString &databaseFilePath,
+ const QString &term, int limit)
+{
+ static const QLatin1String sqlite("QSQLITE");
+ static const QLatin1String name("HelpManager::findKeywords");
+
+ QSet<QString> keywords;
+
+ { // make sure db is destroyed before removeDatabase call
+ QSqlDatabase db = QSqlDatabase::addDatabase(sqlite, name);
+ if (db.driver() && db.driver()->lastError().type() == QSqlError::NoError) {
+ db.setDatabaseName(databaseFilePath);
+ if (db.open()) {
+ QSqlQuery query = QSqlQuery(db);
+ query.setForwardOnly(true);
+ query.exec(QString::fromLatin1("SELECT DISTINCT Name FROM IndexTable WHERE Name LIKE "
+ "'%%1%' LIMIT %2").arg(term, QString::number(limit)));
+ while (query.next()) {
+ const QString &keyValue = query.value(0).toString();
+ if (!keyValue.isEmpty())
+ keywords.insert(keyValue);
+ }
+ db.close();
+ }
+ }
+ }
+ QSqlDatabase::removeDatabase(name);
+ return keywords;
+}
+
+void HelpIndexFilter::invalidateCache()
+{
+ m_mutex.lock();
+ m_needsUpdate = true;
+ m_mutex.unlock();
}
diff --git a/src/plugins/help/helpindexfilter.h b/src/plugins/help/helpindexfilter.h
index 06526ec73e7..237a522443a 100644
--- a/src/plugins/help/helpindexfilter.h
+++ b/src/plugins/help/helpindexfilter.h
@@ -34,6 +34,7 @@
#include <coreplugin/locator/ilocatorfilter.h>
#include <QIcon>
+#include <QMutex>
namespace Help {
namespace Internal {
@@ -48,17 +49,26 @@ public:
// ILocatorFilter
void prepareSearch(const QString &entry);
- QList<Core::LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future, const QString &entry);
+ QList<Core::LocatorFilterEntry> matchesFor(QFutureInterface<Core::LocatorFilterEntry> &future,
+ const QString &entry);
void accept(Core::LocatorFilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
+ Q_INVOKABLE QSet<QString> searchMatches(const QString &databaseFilePath,
+ const QString &term, int limit);
signals:
void linkActivated(const QUrl &link) const;
void linksActivated(const QMap<QString, QUrl> &links, const QString &key) const;
private:
+ void invalidateCache();
+
+ QStringList m_helpDatabases;
+ QSet<QString> m_keywordCache;
+ QString m_searchTermCache;
+ bool m_needsUpdate;
+ QMutex m_mutex;
QIcon m_icon;
- QStringList m_keywords;
};
} // namespace Internal
diff --git a/src/plugins/help/helpplugin.cpp b/src/plugins/help/helpplugin.cpp
index 59787ffa6e1..12dcbb02eca 100644
--- a/src/plugins/help/helpplugin.cpp
+++ b/src/plugins/help/helpplugin.cpp
@@ -95,12 +95,12 @@
#include <QHelpEngine>
+#include <functional>
+
using namespace Help::Internal;
static const char kExternalWindowStateKey[] = "Help/ExternalWindowState";
-#define IMAGEPATH ":/help/images/"
-
using namespace Core;
using namespace Utils;
@@ -149,7 +149,7 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
addAutoReleasedObject(m_generalSettingsPage = new GeneralSettingsPage());
addAutoReleasedObject(m_searchTaskHandler = new SearchTaskHandler);
- m_centralWidget = new Help::Internal::CentralWidget(modecontext);
+ m_centralWidget = new CentralWidget(modecontext);
connect(m_centralWidget, SIGNAL(sourceChanged(QUrl)), this,
SLOT(updateSideBarSource(QUrl)));
connect(m_centralWidget, &CentralWidget::closeButtonClicked,
@@ -170,8 +170,6 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
SLOT(setupHelpEngineIfNeeded()));
connect(HelpManager::instance(), SIGNAL(collectionFileChanged()), this,
SLOT(setupHelpEngineIfNeeded()));
- connect(HelpManager::instance(), SIGNAL(setupFinished()), this,
- SLOT(unregisterOldQtCreatorDocumentation()));
Command *cmd;
QAction *action;
@@ -265,22 +263,6 @@ ExtensionSystem::IPlugin::ShutdownFlag HelpPlugin::aboutToShutdown()
return SynchronousShutdown;
}
-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);
-
- QStringList documentationToUnregister;
- foreach (const QString &ns, HelpManager::registeredNamespaces()) {
- if (ns.startsWith(QLatin1String("org.qt-project.qtcreator."))
- && ns != nsInternal) {
- documentationToUnregister << ns;
- }
- }
- if (!documentationToUnregister.isEmpty())
- HelpManager::unregisterDocumentation(documentationToUnregister);
-}
-
void HelpPlugin::resetFilter()
{
const QString &filterInternal = QString::fromLatin1("Qt Creator %1.%2.%3")
@@ -320,7 +302,7 @@ void HelpPlugin::saveExternalWindowSettings()
if (!m_externalWindow)
return;
m_externalWindowState = m_externalWindow->geometry();
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->setValue(QLatin1String(kExternalWindowStateKey),
qVariantFromValue(m_externalWindowState));
}
@@ -340,7 +322,7 @@ HelpWidget *HelpPlugin::createHelpWidget(const Context &context, HelpWidget::Wid
// force setup, as we might have never switched to full help mode
// thus the help engine might still run without collection file setup
- m_helpManager->setupGuiHelpEngine();
+ LocalHelpManager::setupGuiHelpEngine();
return widget;
}
@@ -349,7 +331,7 @@ void HelpPlugin::createRightPaneContextViewer()
{
if (m_rightPaneSideBarWidget)
return;
- m_rightPaneSideBarWidget = createHelpWidget(Core::Context(Constants::C_HELP_SIDEBAR),
+ m_rightPaneSideBarWidget = createHelpWidget(Context(Constants::C_HELP_SIDEBAR),
HelpWidget::SideBarWidget);
}
@@ -358,10 +340,10 @@ HelpViewer *HelpPlugin::externalHelpViewer()
if (m_externalWindow)
return m_externalWindow->currentViewer();
doSetupIfNeeded();
- m_externalWindow = createHelpWidget(Core::Context(Constants::C_HELP_EXTERNAL),
+ m_externalWindow = createHelpWidget(Context(Constants::C_HELP_EXTERNAL),
HelpWidget::ExternalWindow);
if (m_externalWindowState.isNull()) {
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
m_externalWindowState = settings->value(QLatin1String(kExternalWindowStateKey)).toRect();
}
if (m_externalWindowState.isNull())
@@ -375,30 +357,46 @@ HelpViewer *HelpPlugin::externalHelpViewer()
HelpViewer *HelpPlugin::createHelpViewer(qreal zoom)
{
- HelpViewer *viewer = 0;
- const QString backend = QLatin1String(qgetenv("QTC_HELPVIEWER_BACKEND"));
- if (backend.compare(QLatin1String("native"), Qt::CaseInsensitive) == 0) {
+ // check for backends
+ typedef std::function<HelpViewer *()> ViewerFactory;
+ QHash<QString, ViewerFactory> factories; // id -> factory
#ifdef QTC_MAC_NATIVE_HELPVIEWER
- viewer = new MacWebKitHelpViewer(zoom);
-#else
- qWarning() << "native help viewer is requested, but was not enabled during compilation";
- viewer = new TextBrowserHelpViewer(zoom);
+ factories.insert(QLatin1String("native"), []() { return new MacWebKitHelpViewer(); });
#endif
- } else if (backend.compare(QLatin1String("textbrowser"), Qt::CaseInsensitive) == 0) {
- viewer = new TextBrowserHelpViewer(zoom);
- } else {
#ifndef QT_NO_WEBKIT
- viewer = new QtWebKitHelpViewer(zoom);
-#else
- viewer = new TextBrowserHelpViewer(zoom);
+ factories.insert(QLatin1String("qtwebkit"), []() { return new QtWebKitHelpViewer(); });
#endif
+ factories.insert(QLatin1String("textbrowser"), []() { return new TextBrowserHelpViewer(); });
+
+ ViewerFactory factory;
+ // check requested backend
+ const QString backend = QLatin1String(qgetenv("QTC_HELPVIEWER_BACKEND"));
+ if (!backend.isEmpty()) {
+ factory = factories.value(backend);
+ if (!factory)
+ qWarning("Help viewer backend \"%s\" not found, using default.", qPrintable(backend));
}
+ // default setting
+#ifdef QTC_MAC_NATIVE_HELPVIEWER_DEFAULT
+ if (!factory)
+ factory = factories.value(QLatin1String("native"));
+#endif
+ if (!factory)
+ factory = factories.value(QLatin1String("qtwebkit"));
+ if (!factory)
+ factory = factories.value(QLatin1String("textbrowser"));
+
+ QTC_ASSERT(factory, return 0);
+ HelpViewer *viewer = factory();
// initialize font
QVariant fontSetting = LocalHelpManager::engineFontSettings();
if (fontSetting.isValid())
viewer->setViewerFont(fontSetting.value<QFont>());
+ // initialize zoom
+ viewer->setScale(zoom);
+
// add find support
Aggregation::Aggregate *agg = new Aggregation::Aggregate();
agg->add(viewer);
@@ -415,7 +413,7 @@ void HelpPlugin::activateHelpMode()
void HelpPlugin::showLinkInHelpMode(const QUrl &source)
{
activateHelpMode();
- Core::ICore::raiseWindow(m_mode->widget());
+ ICore::raiseWindow(m_mode->widget());
m_centralWidget->setSource(source);
m_centralWidget->setFocus();
}
@@ -423,7 +421,7 @@ void HelpPlugin::showLinkInHelpMode(const QUrl &source)
void HelpPlugin::showLinksInHelpMode(const QMap<QString, QUrl> &links, const QString &key)
{
activateHelpMode();
- Core::ICore::raiseWindow(m_mode->widget());
+ ICore::raiseWindow(m_mode->widget());
m_centralWidget->showTopicChooser(links, key);
}
@@ -477,10 +475,10 @@ void HelpPlugin::fontChanged()
void HelpPlugin::setupHelpEngineIfNeeded()
{
- m_helpManager->setEngineNeedsUpdate();
+ LocalHelpManager::setEngineNeedsUpdate();
if (ModeManager::currentMode() == m_mode
- || contextHelpOption() == Core::HelpManager::ExternalHelpAlways)
- m_helpManager->setupGuiHelpEngine();
+ || contextHelpOption() == HelpManager::ExternalHelpAlways)
+ LocalHelpManager::setupGuiHelpEngine();
}
bool HelpPlugin::canShowHelpSideBySide() const
@@ -502,24 +500,24 @@ bool HelpPlugin::canShowHelpSideBySide() const
return true;
}
-HelpViewer *HelpPlugin::viewerForHelpViewerLocation(Core::HelpManager::HelpViewerLocation location)
+HelpViewer *HelpPlugin::viewerForHelpViewerLocation(HelpManager::HelpViewerLocation location)
{
- Core::HelpManager::HelpViewerLocation actualLocation = location;
- if (location == Core::HelpManager::SideBySideIfPossible)
- actualLocation = canShowHelpSideBySide() ? Core::HelpManager::SideBySideAlways
- : Core::HelpManager::HelpModeAlways;
+ HelpManager::HelpViewerLocation actualLocation = location;
+ if (location == HelpManager::SideBySideIfPossible)
+ actualLocation = canShowHelpSideBySide() ? HelpManager::SideBySideAlways
+ : HelpManager::HelpModeAlways;
- if (actualLocation == Core::HelpManager::ExternalHelpAlways)
+ if (actualLocation == HelpManager::ExternalHelpAlways)
return externalHelpViewer();
- if (actualLocation == Core::HelpManager::SideBySideAlways) {
+ if (actualLocation == HelpManager::SideBySideAlways) {
createRightPaneContextViewer();
RightPaneWidget::instance()->setWidget(m_rightPaneSideBarWidget);
RightPaneWidget::instance()->setShown(true);
return m_rightPaneSideBarWidget->currentViewer();
}
- QTC_CHECK(actualLocation == Core::HelpManager::HelpModeAlways);
+ QTC_CHECK(actualLocation == HelpManager::HelpModeAlways);
activateHelpMode(); // should trigger an createPage...
HelpViewer *viewer = m_centralWidget->currentViewer();
@@ -569,7 +567,7 @@ void HelpPlugin::showContextHelp()
// Find out what to show
QMap<QString, QUrl> links;
QString idFromContext;
- if (IContext *context = Core::ICore::currentContextObject()) {
+ if (IContext *context = ICore::currentContextObject()) {
idFromContext = context->contextHelpId();
links = HelpManager::linksForIdentifier(idFromContext);
// Maybe the id is already an URL
@@ -599,7 +597,7 @@ void HelpPlugin::showContextHelp()
viewer->scrollToAnchor(source.fragment());
}
viewer->setFocus();
- Core::ICore::raiseWindow(viewer);
+ ICore::raiseWindow(viewer);
}
}
}
@@ -626,7 +624,7 @@ void HelpPlugin::highlightSearchTermsInContextHelp()
m_contextHelpHighlightId.clear();
}
-void HelpPlugin::handleHelpRequest(const QUrl &url, Core::HelpManager::HelpViewerLocation location)
+void HelpPlugin::handleHelpRequest(const QUrl &url, HelpManager::HelpViewerLocation location)
{
if (HelpViewer::launchWithExternalApp(url))
return;
@@ -650,7 +648,7 @@ void HelpPlugin::handleHelpRequest(const QUrl &url, Core::HelpManager::HelpViewe
HelpViewer *viewer = viewerForHelpViewerLocation(location);
QTC_ASSERT(viewer, return);
viewer->setSource(newUrl);
- Core::ICore::raiseWindow(viewer);
+ ICore::raiseWindow(viewer);
}
void HelpPlugin::slotOpenSupportPage()
@@ -665,7 +663,7 @@ void HelpPlugin::slotReportBug()
void HelpPlugin::doSetupIfNeeded()
{
- m_helpManager->setupGuiHelpEngine();
+ LocalHelpManager::setupGuiHelpEngine();
if (m_setupNeeded) {
qApp->processEvents();
resetFilter();
@@ -674,15 +672,15 @@ void HelpPlugin::doSetupIfNeeded()
}
}
-Core::HelpManager::HelpViewerLocation HelpPlugin::contextHelpOption() const
+HelpManager::HelpViewerLocation HelpPlugin::contextHelpOption() const
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
const QString key = QLatin1String(Help::Constants::ID_MODE_HELP) + QLatin1String("/ContextHelpOption");
if (settings->contains(key))
- return Core::HelpManager::HelpViewerLocation(
- settings->value(key, Core::HelpManager::SideBySideIfPossible).toInt());
+ return HelpManager::HelpViewerLocation(
+ settings->value(key, HelpManager::SideBySideIfPossible).toInt());
const QHelpEngineCore &engine = LocalHelpManager::helpEngine();
- return Core::HelpManager::HelpViewerLocation(engine.customValue(QLatin1String("ContextHelpOption"),
- Core::HelpManager::SideBySideIfPossible).toInt());
+ return HelpManager::HelpViewerLocation(engine.customValue(QLatin1String("ContextHelpOption"),
+ HelpManager::SideBySideIfPossible).toInt());
}
diff --git a/src/plugins/help/helpplugin.h b/src/plugins/help/helpplugin.h
index 1ced29cdffa..0540c5ad536 100644
--- a/src/plugins/help/helpplugin.h
+++ b/src/plugins/help/helpplugin.h
@@ -85,8 +85,6 @@ public:
static HelpViewer *createHelpViewer(qreal zoom);
private slots:
- void unregisterOldQtCreatorDocumentation();
-
void modeChanged(Core::IMode *mode, Core::IMode *old);
void showContextHelp();
diff --git a/src/plugins/help/helpviewer.h b/src/plugins/help/helpviewer.h
index 5d191f8affa..8454fb6ee11 100644
--- a/src/plugins/help/helpviewer.h
+++ b/src/plugins/help/helpviewer.h
@@ -55,6 +55,7 @@ public:
virtual void setViewerFont(const QFont &font) = 0;
virtual qreal scale() const = 0;
+ virtual void setScale(qreal scale) = 0;
virtual QString title() const = 0;
diff --git a/src/plugins/help/localhelpmanager.cpp b/src/plugins/help/localhelpmanager.cpp
index fb05e69c299..3603d6fbb8d 100644
--- a/src/plugins/help/localhelpmanager.cpp
+++ b/src/plugins/help/localhelpmanager.cpp
@@ -47,6 +47,9 @@ using namespace Help::Internal;
static LocalHelpManager *m_instance = 0;
+bool LocalHelpManager::m_guiNeedsSetup = true;
+bool LocalHelpManager::m_needsCollectionFile = true;
+
QMutex LocalHelpManager::m_guiMutex;
QHelpEngine* LocalHelpManager::m_guiEngine = 0;
@@ -61,8 +64,6 @@ static char kHelpHomePageKey[] = "Help/HomePage";
LocalHelpManager::LocalHelpManager(QObject *parent)
: QObject(parent)
- , m_guiNeedsSetup(true)
- , m_needsCollectionFile(true)
{
m_instance = this;
qRegisterMetaType<Help::Internal::LocalHelpManager::HelpData>("Help::Internal::LocalHelpManager::HelpData");
diff --git a/src/plugins/help/localhelpmanager.h b/src/plugins/help/localhelpmanager.h
index 1b4be734cdb..0fe6676057b 100644
--- a/src/plugins/help/localhelpmanager.h
+++ b/src/plugins/help/localhelpmanager.h
@@ -64,8 +64,8 @@ public:
static QString homePage();
static void setHomePage(const QString &page);
- void setupGuiHelpEngine();
- void setEngineNeedsUpdate();
+ static void setupGuiHelpEngine();
+ static void setEngineNeedsUpdate();
static QHelpEngine& helpEngine();
static BookmarkManager& bookmarkManager();
@@ -86,8 +86,8 @@ signals:
void filterIndexChanged(int index);
private:
- bool m_guiNeedsSetup;
- bool m_needsCollectionFile;
+ static bool m_guiNeedsSetup;
+ static bool m_needsCollectionFile;
static QStandardItemModel *m_filterModel;
static QString m_currentFilter;
diff --git a/src/plugins/help/macwebkithelpviewer.h b/src/plugins/help/macwebkithelpviewer.h
index 236c9ee4a1a..8b8df61085e 100644
--- a/src/plugins/help/macwebkithelpviewer.h
+++ b/src/plugins/help/macwebkithelpviewer.h
@@ -68,12 +68,15 @@ public:
void setOpenInNewPageActionVisible(bool visible);
WebView *webView() const;
+ void startToolTipTimer(const QPoint &pos, const QString &text);
+ void hideToolTip();
protected:
void hideEvent(QHideEvent *);
void showEvent(QShowEvent *);
private:
+ void showToolTip();
MacWebKitHelpWidgetPrivate *d;
};
@@ -82,13 +85,14 @@ class MacWebKitHelpViewer : public HelpViewer
Q_OBJECT
public:
- explicit MacWebKitHelpViewer(qreal zoom, QWidget *parent = 0);
+ explicit MacWebKitHelpViewer(QWidget *parent = 0);
~MacWebKitHelpViewer();
QFont viewerFont() const;
void setViewerFont(const QFont &font);
qreal scale() const;
+ void setScale(qreal scale);
QString title() const;
diff --git a/src/plugins/help/macwebkithelpviewer.mm b/src/plugins/help/macwebkithelpviewer.mm
index 9fb1c260410..096d0c34129 100644
--- a/src/plugins/help/macwebkithelpviewer.mm
+++ b/src/plugins/help/macwebkithelpviewer.mm
@@ -39,7 +39,10 @@
#include <QApplication>
#include <QClipboard>
#include <QHelpEngine>
+#include <QStyle>
+#include <QTimer>
#include <QtMac>
+#include <QToolTip>
#include <QUrl>
#include <QVBoxLayout>
@@ -86,6 +89,22 @@ AutoreleasePool::~AutoreleasePool()
[pool release];
}
+// #pragma mark -- mac helpers
+
+// copy from qcocoahelpers.mm
+static int mainScreenHeight()
+{
+ // The first screen in the screens array is documented
+ // to have the (0,0) origin.
+ NSRect screenFrame = [[[NSScreen screens] firstObject] frame];
+ return screenFrame.size.height;
+}
+
+static QPoint flipPoint(const NSPoint &p)
+{
+ return QPoint(p.x, mainScreenHeight() - p.y);
+}
+
// #pragma mark -- DOMNodeIterator (PrivateExtensions)
@interface DOMNodeIterator (PrivateExtensions)
@@ -212,6 +231,7 @@ static void ensureProtocolHandler()
- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame;
- (void)webView:(WebView *)sender didReceiveTitle:(NSString *)title forFrame:(WebFrame *)frame;
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame;
+- (void)webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame;
@end
@@ -249,28 +269,37 @@ static void ensureProtocolHandler()
viewer->slotLoadFinished();
}
+- (void)webView:(WebView *)sender didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
+{
+ Q_UNUSED(sender)
+ Q_UNUSED(error)
+ if (frame == mainFrame)
+ viewer->slotLoadFinished();
+}
+
@end
// #pragma mark -- UIDelegate
@interface UIDelegate : NSObject
{
- QWidget *widget;
+ Help::Internal::MacWebKitHelpWidget *widget;
}
@property (assign) BOOL openInNewPageActionVisible;
-- (id)initWithWidget:(QWidget *)theWidget;
+- (id)initWithWidget:(Help::Internal::MacWebKitHelpWidget *)theWidget;
- (void)webView:(WebView *)sender makeFirstResponder:(NSResponder *)responder;
- (NSArray *)webView:(WebView *)sender contextMenuItemsForElement:(NSDictionary *)element
defaultMenuItems:(NSArray *)defaultMenuItems;
- (WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request;
-
+- (void)webView:(WebView *)sender mouseDidMoveOverElement:(NSDictionary *)elementInformation
+ modifierFlags:(NSUInteger)modifierFlags;
@end
@implementation UIDelegate
-- (id)initWithWidget:(QWidget *)theWidget
+- (id)initWithWidget:(Help::Internal::MacWebKitHelpWidget *)theWidget
{
self = [super init];
if (self) {
@@ -334,6 +363,23 @@ static void ensureProtocolHandler()
return viewer->widget()->webView();
}
+- (void)webView:(WebView *)sender mouseDidMoveOverElement:(NSDictionary *)elementInformation
+ modifierFlags:(NSUInteger)modifierFlags
+{
+ Q_UNUSED(sender)
+ if (!elementInformation || (modifierFlags & NSDeviceIndependentModifierFlagsMask) != 0) {
+ widget->hideToolTip();
+ return;
+ }
+ NSURL *url = [elementInformation objectForKey:WebElementLinkURLKey];
+ if (!url) {
+ widget->hideToolTip();
+ return;
+ }
+ widget->startToolTipTimer(flipPoint(NSEvent.mouseLocation),
+ QString::fromNSString(url.absoluteString));
+}
+
@end
// #pragma mark -- MyWebView
@@ -396,6 +442,9 @@ public:
FrameLoadDelegate *m_frameLoadDelegate;
UIDelegate *m_uiDelegate;
NSResponder *m_savedResponder;
+ QTimer m_toolTipTimer;
+ QPoint m_toolTipPos;
+ QString m_toolTipText;
};
// #pragma mark -- MacWebKitHelpWidget
@@ -404,8 +453,13 @@ MacWebKitHelpWidget::MacWebKitHelpWidget(MacWebKitHelpViewer *parent)
: QMacCocoaViewContainer(0, parent),
d(new MacWebKitHelpWidgetPrivate)
{
+ d->m_toolTipTimer.setSingleShot(true);
+ connect(&d->m_toolTipTimer, &QTimer::timeout, this, &MacWebKitHelpWidget::showToolTip);
AutoreleasePool pool; Q_UNUSED(pool)
d->m_webView = [[MyWebView alloc] init];
+ // Turn layered rendering on.
+ // Otherwise the WebView will render empty after any QQuickWidget was shown.
+ d->m_webView.wantsLayer = YES;
d->m_frameLoadDelegate = [[FrameLoadDelegate alloc] initWithMainFrame:d->m_webView.mainFrame
viewer:parent];
[d->m_webView setFrameLoadDelegate:d->m_frameLoadDelegate];
@@ -430,6 +484,20 @@ WebView *MacWebKitHelpWidget::webView() const
return d->m_webView;
}
+void MacWebKitHelpWidget::startToolTipTimer(const QPoint &pos, const QString &text)
+{
+ int delay = style()->styleHint(QStyle::SH_ToolTip_WakeUpDelay, 0, this, 0);
+ d->m_toolTipPos = pos;
+ d->m_toolTipText = text;
+ d->m_toolTipTimer.start(delay);
+}
+
+void MacWebKitHelpWidget::hideToolTip()
+{
+ d->m_toolTipTimer.stop();
+ QToolTip::showText(QPoint(), QString());
+}
+
void MacWebKitHelpWidget::hideEvent(QHideEvent *)
{
[d->m_webView setHidden:YES];
@@ -440,9 +508,14 @@ void MacWebKitHelpWidget::showEvent(QShowEvent *)
[d->m_webView setHidden:NO];
}
+void MacWebKitHelpWidget::showToolTip()
+{
+ QToolTip::showText(d->m_toolTipPos, d->m_toolTipText, this);
+}
+
// #pragma mark -- MacWebKitHelpViewer
-MacWebKitHelpViewer::MacWebKitHelpViewer(qreal zoom, QWidget *parent)
+MacWebKitHelpViewer::MacWebKitHelpViewer(QWidget *parent)
: HelpViewer(parent),
m_widget(new MacWebKitHelpWidget(this))
{
@@ -457,7 +530,6 @@ MacWebKitHelpViewer::MacWebKitHelpViewer(qreal zoom, QWidget *parent)
setLayout(layout);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(m_widget, 10);
- m_widget->webView().textSizeMultiplier = (zoom == 0.0 ? 1.0 : zoom);
}
MacWebKitHelpViewer::~MacWebKitHelpViewer()
@@ -503,7 +575,12 @@ void MacWebKitHelpViewer::resetScale()
qreal MacWebKitHelpViewer::scale() const
{
AutoreleasePool pool; Q_UNUSED(pool)
- return m_widget->webView().textSizeMultiplier;
+ return m_widget->webView().textSizeMultiplier;
+}
+
+void MacWebKitHelpViewer::setScale(qreal scale)
+{
+ m_widget->webView().textSizeMultiplier = (scale <= 0.0 ? 1.0 : scale);
}
QString MacWebKitHelpViewer::title() const
diff --git a/src/plugins/help/openpagesmodel.cpp b/src/plugins/help/openpagesmodel.cpp
index 0e27b804aca..f87b4271548 100644
--- a/src/plugins/help/openpagesmodel.cpp
+++ b/src/plugins/help/openpagesmodel.cpp
@@ -75,7 +75,8 @@ void OpenPagesModel::addPage(const QUrl &url, qreal zoom)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
HelpViewer *page = HelpPlugin::createHelpViewer(zoom);
- connect(page, SIGNAL(titleChanged()), this, SLOT(handleTitleChanged()));
+ connect(page, &HelpViewer::titleChanged,
+ this, &OpenPagesModel::handleTitleChanged);
m_pages << page;
endInsertRows();
if (url.isValid())
diff --git a/src/plugins/help/openpagesswitcher.cpp b/src/plugins/help/openpagesswitcher.cpp
index c77a60cf1d1..12c929745df 100644
--- a/src/plugins/help/openpagesswitcher.cpp
+++ b/src/plugins/help/openpagesswitcher.cpp
@@ -67,10 +67,10 @@ OpenPagesSwitcher::OpenPagesSwitcher(OpenPagesModel *model)
layout->setMargin(0);
layout->addWidget(m_openPagesWidget);
- connect(m_openPagesWidget, SIGNAL(closePage(QModelIndex)), this,
- SIGNAL(closePage(QModelIndex)));
- connect(m_openPagesWidget, SIGNAL(setCurrentPage(QModelIndex)), this,
- SIGNAL(setCurrentPage(QModelIndex)));
+ connect(m_openPagesWidget, &OpenPagesWidget::closePage,
+ this, &OpenPagesSwitcher::closePage);
+ connect(m_openPagesWidget, &OpenPagesWidget::setCurrentPage,
+ this, &OpenPagesSwitcher::setCurrentPage);
}
OpenPagesSwitcher::~OpenPagesSwitcher()
diff --git a/src/plugins/help/qtwebkithelpviewer.cpp b/src/plugins/help/qtwebkithelpviewer.cpp
index a2c264b42e7..1821e1c0da7 100644
--- a/src/plugins/help/qtwebkithelpviewer.cpp
+++ b/src/plugins/help/qtwebkithelpviewer.cpp
@@ -38,6 +38,7 @@
#include <coreplugin/find/findplugin.h>
#include <utils/hostosinfo.h>
+#include <utils/networkaccessmanager.h>
#include <utils/qtcassert.h>
#include <QAction>
@@ -59,7 +60,6 @@
#include <QNetworkReply>
#include <QNetworkRequest>
-#include <utils/networkaccessmanager.h>
#include <cstring>
@@ -250,7 +250,7 @@ void HelpPage::onHandleUnsupportedContent(QNetworkReply *reply)
// -- HelpViewer
-QtWebKitHelpWidget::QtWebKitHelpWidget(qreal zoom, QtWebKitHelpViewer *parent)
+QtWebKitHelpWidget::QtWebKitHelpWidget(QtWebKitHelpViewer *parent)
: QWebView(parent),
m_parent(parent)
{
@@ -278,8 +278,6 @@ QtWebKitHelpWidget::QtWebKitHelpWidget(qreal zoom, QtWebKitHelpViewer *parent)
SLOT(actionChanged()));
connect(pageAction(QWebPage::Forward), SIGNAL(changed()), this,
SLOT(actionChanged()));
-
- setZoomFactor(zoom == 0.0 ? 1.0 : zoom);
}
QtWebKitHelpWidget::~QtWebKitHelpWidget()
@@ -387,15 +385,15 @@ bool QtWebKitHelpWidget::eventFilter(QObject *obj, QEvent *event)
if (event->type() == QEvent::KeyPress) {
if (QKeyEvent *keyEvent = static_cast<QKeyEvent*> (event)) {
if (keyEvent->key() == Qt::Key_Slash)
- Core::FindPlugin::instance()->openFindToolBar(Core::FindPlugin::FindForwardDirection);
+ FindPlugin::instance()->openFindToolBar(FindPlugin::FindForwardDirection);
}
}
return QWebView::eventFilter(obj, event);
}
-QtWebKitHelpViewer::QtWebKitHelpViewer(qreal zoom, QWidget *parent)
+QtWebKitHelpViewer::QtWebKitHelpViewer(QWidget *parent)
: HelpViewer(parent),
- m_webView(new QtWebKitHelpWidget(zoom, this))
+ m_webView(new QtWebKitHelpWidget(this))
{
QVBoxLayout *layout = new QVBoxLayout;
setLayout(layout);
@@ -413,6 +411,7 @@ QtWebKitHelpViewer::QtWebKitHelpViewer(qreal zoom, QWidget *parent)
connect(m_webView->page(), SIGNAL(printRequested(QWebFrame*)), this, SIGNAL(printRequested()));
connect(m_webView, SIGNAL(backwardAvailable(bool)), this, SIGNAL(backwardAvailable(bool)));
connect(m_webView, SIGNAL(forwardAvailable(bool)), this, SIGNAL(forwardAvailable(bool)));
+ connect(page(), &HelpPage::linkHovered, this, &QtWebKitHelpViewer::setToolTip);
}
QFont QtWebKitHelpViewer::viewerFont() const
@@ -449,6 +448,11 @@ qreal QtWebKitHelpViewer::scale() const
return m_webView->zoomFactor();
}
+void QtWebKitHelpViewer::setScale(qreal scale)
+{
+ m_webView->setZoomFactor(scale <= 0.0 ? 1.0 : scale);
+}
+
QString QtWebKitHelpViewer::title() const
{
return m_webView->title();
@@ -565,7 +569,7 @@ void QtWebKitHelpViewer::setOpenInNewPageActionVisible(bool visible)
m_webView->setOpenInNewPageActionVisible(visible);
}
-bool QtWebKitHelpViewer::findText(const QString &text, Core::FindFlags flags,
+bool QtWebKitHelpViewer::findText(const QString &text, FindFlags flags,
bool incremental, bool fromSearch, bool *wrapped)
{
Q_UNUSED(incremental);
@@ -573,9 +577,9 @@ bool QtWebKitHelpViewer::findText(const QString &text, Core::FindFlags flags,
if (wrapped)
*wrapped = false;
QWebPage::FindFlags options;
- if (flags & Core::FindBackward)
+ if (flags & FindBackward)
options |= QWebPage::FindBackward;
- if (flags & Core::FindCaseSensitively)
+ if (flags & FindCaseSensitively)
options |= QWebPage::FindCaseSensitively;
bool found = m_webView->findText(text, options);
diff --git a/src/plugins/help/qtwebkithelpviewer.h b/src/plugins/help/qtwebkithelpviewer.h
index 4f05c74dedc..669455fcb90 100644
--- a/src/plugins/help/qtwebkithelpviewer.h
+++ b/src/plugins/help/qtwebkithelpviewer.h
@@ -48,13 +48,14 @@ class QtWebKitHelpViewer : public HelpViewer
{
Q_OBJECT
public:
- explicit QtWebKitHelpViewer(qreal zoom, QWidget *parent = 0);
+ explicit QtWebKitHelpViewer(QWidget *parent = 0);
~QtWebKitHelpViewer() { }
QFont viewerFont() const;
void setViewerFont(const QFont &font);
qreal scale() const;
+ void setScale(qreal scale);
QString title() const;
@@ -103,7 +104,7 @@ class QtWebKitHelpWidget : public QWebView
Q_OBJECT
public:
- explicit QtWebKitHelpWidget(qreal zoom, QtWebKitHelpViewer *parent = 0);
+ explicit QtWebKitHelpWidget(QtWebKitHelpViewer *parent = 0);
~QtWebKitHelpWidget();
void scaleUp();
diff --git a/src/plugins/help/remotehelpfilter.cpp b/src/plugins/help/remotehelpfilter.cpp
index 4da4d2c847b..c6b64119a79 100644
--- a/src/plugins/help/remotehelpfilter.cpp
+++ b/src/plugins/help/remotehelpfilter.cpp
@@ -49,8 +49,10 @@ RemoteFilterOptions::RemoteFilterOptions(RemoteHelpFilter *filter, QWidget *pare
item->setFlags(item->flags() | Qt::ItemIsEditable);
}
- connect(m_ui.add, SIGNAL(clicked()), this, SLOT(addNewItem()));
- connect(m_ui.remove, SIGNAL(clicked()), this, SLOT(removeItem()));
+ connect(m_ui.add, &QPushButton::clicked,
+ this, &RemoteFilterOptions::addNewItem);
+ connect(m_ui.remove, &QPushButton::clicked,
+ this, &RemoteFilterOptions::removeItem);
connect(m_ui.listWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), SLOT(updateRemoveButton()));
updateRemoveButton();
}
diff --git a/src/plugins/help/textbrowserhelpviewer.cpp b/src/plugins/help/textbrowserhelpviewer.cpp
index fad3d1bff5e..6f2b9b9cd26 100644
--- a/src/plugins/help/textbrowserhelpviewer.cpp
+++ b/src/plugins/help/textbrowserhelpviewer.cpp
@@ -43,6 +43,7 @@
#include <QHelpEngine>
#include <QKeyEvent>
#include <QMenu>
+#include <QToolTip>
#include <QVBoxLayout>
using namespace Help;
@@ -50,9 +51,9 @@ using namespace Help::Internal;
// -- HelpViewer
-TextBrowserHelpViewer::TextBrowserHelpViewer(qreal zoom, QWidget *parent)
+TextBrowserHelpViewer::TextBrowserHelpViewer(QWidget *parent)
: HelpViewer(parent)
- , m_textBrowser(new TextBrowserHelpWidget(zoom, this))
+ , m_textBrowser(new TextBrowserHelpWidget(this))
{
QVBoxLayout *layout = new QVBoxLayout;
setLayout(layout);
@@ -112,6 +113,22 @@ qreal TextBrowserHelpViewer::scale() const
return m_textBrowser->zoomCount;
}
+void TextBrowserHelpViewer::setScale(qreal scale)
+{
+ m_textBrowser->forceFont = true;
+ if (scale > 10)
+ scale = 10;
+ else if (scale < -5)
+ scale = -5;
+ int diff = (int)scale - m_textBrowser->zoomCount;
+ if (diff > 0)
+ m_textBrowser->zoomIn(diff);
+ else if (diff < 0)
+ m_textBrowser->zoomOut(-diff);
+ m_textBrowser->zoomCount = (int)scale;
+ m_textBrowser->forceFont = false;
+}
+
QString TextBrowserHelpViewer::title() const
{
return m_textBrowser->documentTitle();
@@ -284,9 +301,9 @@ void TextBrowserHelpViewer::goToHistoryItem()
// -- private
-TextBrowserHelpWidget::TextBrowserHelpWidget(int zoom, TextBrowserHelpViewer *parent)
+TextBrowserHelpWidget::TextBrowserHelpWidget(TextBrowserHelpViewer *parent)
: QTextBrowser(parent)
- , zoomCount(zoom)
+ , zoomCount(0)
, forceFont(false)
, m_openInNewPageActionVisible(true)
, m_parent(parent)
@@ -389,6 +406,10 @@ bool TextBrowserHelpWidget::eventFilter(QObject *obj, QEvent *event)
Core::FindPlugin::instance()->openFindToolBar(Core::FindPlugin::FindForwardDirection);
return true;
}
+ } else if (event->type() == QEvent::ToolTip) {
+ QHelpEvent *e = static_cast<QHelpEvent *>(event);
+ QToolTip::showText(e->globalPos(), linkAt(e->pos()));
+ return true;
}
}
return QTextBrowser::eventFilter(obj, event);
diff --git a/src/plugins/help/textbrowserhelpviewer.h b/src/plugins/help/textbrowserhelpviewer.h
index 81dab92af68..d00bd169e9b 100644
--- a/src/plugins/help/textbrowserhelpviewer.h
+++ b/src/plugins/help/textbrowserhelpviewer.h
@@ -47,13 +47,14 @@ class TextBrowserHelpViewer : public HelpViewer
Q_OBJECT
public:
- explicit TextBrowserHelpViewer(qreal zoom, QWidget *parent = 0);
+ explicit TextBrowserHelpViewer(QWidget *parent = 0);
~TextBrowserHelpViewer();
QFont viewerFont() const;
void setViewerFont(const QFont &font);
qreal scale() const;
+ void setScale(qreal scale);
QString title() const;
@@ -97,7 +98,7 @@ class TextBrowserHelpWidget : public QTextBrowser
Q_OBJECT
public:
- TextBrowserHelpWidget(int zoom, TextBrowserHelpViewer *parent);
+ TextBrowserHelpWidget(TextBrowserHelpViewer *parent);
QVariant loadResource(int type, const QUrl &name);
diff --git a/src/plugins/imageviewer/imageviewer.cpp b/src/plugins/imageviewer/imageviewer.cpp
index 0aac32e6d0c..2520d59e11c 100644
--- a/src/plugins/imageviewer/imageviewer.cpp
+++ b/src/plugins/imageviewer/imageviewer.cpp
@@ -105,8 +105,8 @@ ImageViewer::ImageViewer(QWidget *parent)
d->imageView, SLOT(setViewBackground(bool)));
connect(d->ui_toolbar.toolButtonOutline, SIGNAL(toggled(bool)),
d->imageView, SLOT(setViewOutline(bool)));
- connect(d->ui_toolbar.toolButtonPlayPause, SIGNAL(clicked()),
- this, SLOT(playToggled()));
+ connect(d->ui_toolbar.toolButtonPlayPause, &Core::CommandButton::clicked,
+ this, &ImageViewer::playToggled);
connect(d->imageView, SIGNAL(imageSizeChanged(QSize)),
this, SLOT(imageSizeUpdated(QSize)));
connect(d->imageView, SIGNAL(scaleFactorChanged(qreal)),
@@ -126,7 +126,7 @@ bool ImageViewer::open(QString *errorString, const QString &fileName, const QStr
*errorString = tr("Cannot open image file %1.").arg(QDir::toNativeSeparators(realFileName));
return false;
}
- d->file->setFilePath(fileName);
+ d->file->setFilePath(Utils::FileName::fromString(fileName));
d->ui_toolbar.toolButtonPlayPause->setVisible(d->imageView->isAnimated());
setPaused(!d->imageView->isAnimated());
// d_ptr->file->setMimeType
diff --git a/src/plugins/imageviewer/imageviewerfile.cpp b/src/plugins/imageviewer/imageviewerfile.cpp
index 22eb0436c47..3216178bf9b 100644
--- a/src/plugins/imageviewer/imageviewerfile.cpp
+++ b/src/plugins/imageviewer/imageviewerfile.cpp
@@ -43,7 +43,7 @@ ImageViewerFile::ImageViewerFile(ImageViewer *parent)
{
setId(Constants::IMAGEVIEWER_ID);
m_editor = parent;
- connect(this, SIGNAL(mimeTypeChanged()), this, SIGNAL(changed()));
+ connect(this, &ImageViewerFile::mimeTypeChanged, this, &ImageViewerFile::changed);
}
Core::IDocument::ReloadBehavior ImageViewerFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
@@ -65,7 +65,7 @@ bool ImageViewerFile::reload(QString *errorString,
emit changed();
return true;
}
- return m_editor->open(errorString, filePath(), filePath());
+ return m_editor->open(errorString, filePath().toString(), filePath().toString());
}
bool ImageViewerFile::save(QString *errorString, const QString &fileName, bool autoSave)
diff --git a/src/plugins/ios/iosanalyzesupport.cpp b/src/plugins/ios/iosanalyzesupport.cpp
index 823068ba180..0ef6482a5a1 100644
--- a/src/plugins/ios/iosanalyzesupport.cpp
+++ b/src/plugins/ios/iosanalyzesupport.cpp
@@ -34,7 +34,6 @@
#include "iosmanager.h"
#include "iosdevice.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerkitinformation.h>
#include <debugger/debuggerruncontrol.h>
@@ -81,7 +80,7 @@ RunControl *IosAnalyzeSupport::createAnalyzeRunControl(IosRunConfiguration *runC
Target *target = runConfig->target();
if (!target)
return 0;
- ProjectExplorer::IDevice::ConstPtr device = DeviceKitInformation::device(target->kit());
+ IDevice::ConstPtr device = DeviceKitInformation::device(target->kit());
if (device.isNull())
return 0;
AnalyzerStartParameters params;
diff --git a/src/plugins/ios/iosbuildstep.cpp b/src/plugins/ios/iosbuildstep.cpp
index c9e47a7478c..897ad423c25 100644
--- a/src/plugins/ios/iosbuildstep.cpp
+++ b/src/plugins/ios/iosbuildstep.cpp
@@ -350,7 +350,7 @@ bool IosBuildStepFactory::canCreate(BuildStepList *parent, const Id id) const
&& parent->id() != ProjectExplorer::Constants::BUILDSTEPS_BUILD)
return false;
Kit *kit = parent->target()->kit();
- Core::Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
+ Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
return ((deviceType == Constants::IOS_DEVICE_TYPE
|| deviceType == Constants::IOS_SIMULATOR_TYPE)
&& id == IOS_BUILD_STEP_ID);
@@ -403,7 +403,7 @@ BuildStep *IosBuildStepFactory::restore(BuildStepList *parent, const QVariantMap
QList<Id> IosBuildStepFactory::availableCreationIds(BuildStepList *parent) const
{
Kit *kit = parent->target()->kit();
- Core::Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
+ Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
if (deviceType == Constants::IOS_DEVICE_TYPE
|| deviceType == Constants::IOS_SIMULATOR_TYPE)
return QList<Id>() << Id(IOS_BUILD_STEP_ID);
diff --git a/src/plugins/ios/iosconfigurations.cpp b/src/plugins/ios/iosconfigurations.cpp
index b7a0316008e..0bc72ed83d9 100644
--- a/src/plugins/ios/iosconfigurations.cpp
+++ b/src/plugins/ios/iosconfigurations.cpp
@@ -123,12 +123,16 @@ void IosConfigurations::updateAutomaticKitList()
if (p.compilerPath == toolchain->compilerCommand()
&& p.backendFlags == toolchain->platformCodeGenFlags()) {
found = true;
- if (p.architecture == QLatin1String("i386")
- && toolchain->targetAbi().wordWidth() != 32) {
+ if ((p.architecture == QLatin1String("i386")
+ && toolchain->targetAbi().wordWidth() != 32) ||
+ (p.architecture == QLatin1String("x86_64")
+ && toolchain->targetAbi().wordWidth() != 64)) {
qCDebug(kitSetupLog) << "resetting api of " << toolchain->displayName();
toolchain->setTargetAbi(Abi(Abi::X86Architecture,
Abi::MacOS, Abi::GenericMacFlavor,
- Abi::MachOFormat, 32));
+ Abi::MachOFormat,
+ p.architecture.endsWith(QLatin1String("64"))
+ ? 64 : 32));
}
platformToolchainMap[p.name] = toolchain;
qCDebug(kitSetupLog) << p.name << " -> " << toolchain->displayName();
@@ -172,10 +176,13 @@ void IosConfigurations::updateAutomaticKitList()
toolchain->setPlatformCodeGenFlags(p.backendFlags);
toolchain->setPlatformLinkerFlags(p.backendFlags);
toolchain->resetToolChain(p.compilerPath);
- if (p.architecture == QLatin1String("i386")) {
+ if (p.architecture == QLatin1String("i386")
+ || p.architecture == QLatin1String("x86_64")) {
qCDebug(kitSetupLog) << "setting toolchain Abi for " << toolchain->displayName();
toolchain->setTargetAbi(Abi(Abi::X86Architecture,Abi::MacOS, Abi::GenericMacFlavor,
- Abi::MachOFormat, 32));
+ Abi::MachOFormat,
+ p.architecture.endsWith(QLatin1String("64"))
+ ? 64 : 32));
}
qCDebug(kitSetupLog) << "adding toolchain " << p.name;
ToolChainManager::registerToolChain(toolchain);
@@ -226,7 +233,7 @@ void IosConfigurations::updateAutomaticKitList()
qtVersionsForArch[abi.architecture()].append(qtVersion);
}
- const DebuggerItem *possibleDebugger = DebuggerItemManager::findByEngineType(Debugger::LldbEngineType);
+ const DebuggerItem *possibleDebugger = DebuggerItemManager::findByEngineType(LldbEngineType);
QVariant debuggerId = (possibleDebugger ? possibleDebugger->id() : QVariant());
QList<Kit *> existingKits;
@@ -311,16 +318,16 @@ void IosConfigurations::updateAutomaticKitList()
}
kitAtt->setUnexpandedDisplayName(displayName);
}
- kitAtt->setIconPath(Utils::FileName::fromString(
+ kitAtt->setIconPath(FileName::fromString(
QLatin1String(Constants::IOS_SETTINGS_CATEGORY_ICON)));
DeviceTypeKitInformation::setDeviceTypeId(kitAtt, pDeviceType);
ToolChainKitInformation::setToolChain(kitAtt, pToolchain);
QtKitInformation::setQtVersion(kitAtt, qt);
- if ((!Debugger::DebuggerKitInformation::debugger(kitAtt)
- || !Debugger::DebuggerKitInformation::debugger(kitAtt)->isValid()
- || Debugger::DebuggerKitInformation::debugger(kitAtt)->engineType() != Debugger::LldbEngineType)
+ if ((!DebuggerKitInformation::debugger(kitAtt)
+ || !DebuggerKitInformation::debugger(kitAtt)->isValid()
+ || DebuggerKitInformation::debugger(kitAtt)->engineType() != LldbEngineType)
&& debuggerId.isValid())
- Debugger::DebuggerKitInformation::setDebugger(kitAtt,
+ DebuggerKitInformation::setDebugger(kitAtt,
debuggerId);
kitAtt->setMutable(DeviceKitInformation::id(), true);
@@ -328,7 +335,7 @@ void IosConfigurations::updateAutomaticKitList()
kitAtt->setSticky(ToolChainKitInformation::id(), true);
kitAtt->setSticky(DeviceTypeKitInformation::id(), true);
kitAtt->setSticky(SysRootKitInformation::id(), true);
- kitAtt->setSticky(Debugger::DebuggerKitInformation::id(), false);
+ kitAtt->setSticky(DebuggerKitInformation::id(), false);
SysRootKitInformation::setSysRoot(kitAtt, p.sdkPath);
// QmakeProjectManager::QmakeKitInformation::setMkspec(newKit,
diff --git a/src/plugins/ios/iosdebugsupport.cpp b/src/plugins/ios/iosdebugsupport.cpp
index 8b980352d3d..c5fbb148e65 100644
--- a/src/plugins/ios/iosdebugsupport.cpp
+++ b/src/plugins/ios/iosdebugsupport.cpp
@@ -34,7 +34,6 @@
#include "iosmanager.h"
#include "iosdevice.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerplugin.h>
#include <debugger/debuggerkitinformation.h>
#include <debugger/debuggerruncontrol.h>
@@ -75,7 +74,7 @@ RunControl *IosDebugSupport::createDebugRunControl(IosRunConfiguration *runConfi
Target *target = runConfig->target();
if (!target)
return 0;
- ProjectExplorer::IDevice::ConstPtr device = DeviceKitInformation::device(target->kit());
+ IDevice::ConstPtr device = DeviceKitInformation::device(target->kit());
if (device.isNull())
return 0;
QmakeProject *project = static_cast<QmakeProject *>(target->project());
@@ -119,9 +118,10 @@ RunControl *IosDebugSupport::createDebugRunControl(IosRunConfiguration *runConfi
params.remoteSetupNeeded = true;
if (!params.breakOnMain)
params.continueAfterAttach = true;
+ params.runConfiguration = runConfig;
- Debugger::DebuggerRunConfigurationAspect *aspect
- = runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
+ DebuggerRunConfigurationAspect *aspect
+ = runConfig->extraAspect<DebuggerRunConfigurationAspect>();
bool cppDebug = aspect->useCppDebugger();
bool qmlDebug = aspect->useQmlDebugger();
if (cppDebug) {
@@ -171,7 +171,7 @@ RunControl *IosDebugSupport::createDebugRunControl(IosRunConfiguration *runConfi
}
DebuggerRunControl * const debuggerRunControl
- = DebuggerRunControlFactory::doCreate(params, runConfig, errorMessage);
+ = DebuggerRunControlFactory::doCreate(params, errorMessage);
if (debuggerRunControl)
new IosDebugSupport(runConfig, debuggerRunControl, cppDebug, qmlDebug);
return debuggerRunControl;
@@ -182,7 +182,7 @@ IosDebugSupport::IosDebugSupport(IosRunConfiguration *runConfig,
: QObject(runControl), m_runControl(runControl),
m_runner(new IosRunner(this, runConfig, cppDebug, qmlDebug))
{
- connect(m_runControl->engine(), SIGNAL(requestRemoteSetup()),
+ connect(m_runControl, SIGNAL(requestRemoteSetup()),
m_runner, SLOT(start()));
connect(m_runControl, SIGNAL(finished()),
m_runner, SLOT(stop()));
@@ -212,7 +212,7 @@ void IosDebugSupport::handleServerPorts(int gdbServerPort, int qmlPort)
result.success = gdbServerPort > 0 || (m_runner && !m_runner->cppDebug() && qmlPort > 0);
if (!result.success)
result.reason = tr("Could not get debug server file descriptor.");
- m_runControl->engine()->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
void IosDebugSupport::handleGotInferiorPid(Q_PID pid, int qmlPort)
@@ -223,7 +223,7 @@ void IosDebugSupport::handleGotInferiorPid(Q_PID pid, int qmlPort)
result.success = pid > 0;
if (!result.success)
result.reason = tr("Got an invalid process id.");
- m_runControl->engine()->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
void IosDebugSupport::handleRemoteProcessFinished(bool cleanEnd)
@@ -233,28 +233,20 @@ void IosDebugSupport::handleRemoteProcessFinished(bool cleanEnd)
m_runControl->appendMessage(tr("Run ended with error."), Utils::DebugFormat);
else
m_runControl->appendMessage(tr("Run ended."), Utils::DebugFormat);
- m_runControl->engine()->abortDebugger();
+ m_runControl->abortDebugger();
}
}
void IosDebugSupport::handleRemoteOutput(const QString &output)
{
- if (m_runControl) {
- if (m_runControl->engine())
- m_runControl->engine()->showMessage(output, AppOutput);
- else
- m_runControl->appendMessage(output, Utils::StdOutFormatSameLine);
- }
+ if (m_runControl)
+ m_runControl->showMessage(output, AppOutput);
}
void IosDebugSupport::handleRemoteErrorOutput(const QString &output)
{
- if (m_runControl) {
- if (m_runControl->engine())
- m_runControl->engine()->showMessage(output, AppError);
- else
- m_runControl->appendMessage(output, Utils::StdErrFormatSameLine);
- }
+ if (m_runControl)
+ m_runControl->showMessage(output, AppError);
}
} // namespace Internal
diff --git a/src/plugins/ios/iosdeployconfiguration.cpp b/src/plugins/ios/iosdeployconfiguration.cpp
index 9b1ddaf45f0..437275bbfdc 100644
--- a/src/plugins/ios/iosdeployconfiguration.cpp
+++ b/src/plugins/ios/iosdeployconfiguration.cpp
@@ -128,10 +128,5 @@ QString IosDeployConfigurationFactory::displayNameForId(Core::Id id) const
return QString();
}
-bool IosDeployConfigurationFactory::canHandle(Target *parent) const
-{
- return IosManager::supportsIos(parent);
-}
-
} // namespace Internal
} // namespace Ios
diff --git a/src/plugins/ios/iosdeployconfiguration.h b/src/plugins/ios/iosdeployconfiguration.h
index d1380d5dc3a..48baad751bc 100644
--- a/src/plugins/ios/iosdeployconfiguration.h
+++ b/src/plugins/ios/iosdeployconfiguration.h
@@ -72,9 +72,6 @@ public:
QList<Core::Id> availableCreationIds(ProjectExplorer::Target *parent) const Q_DECL_OVERRIDE;
// used to translate the ids to names to display to the user
QString displayNameForId(Core::Id id) const Q_DECL_OVERRIDE;
-
-private:
- bool canHandle(ProjectExplorer::Target *parent) const Q_DECL_OVERRIDE;
};
} // namespace Internal
diff --git a/src/plugins/ios/iosdeploystep.cpp b/src/plugins/ios/iosdeploystep.cpp
index 4c52424f881..53e00794725 100644
--- a/src/plugins/ios/iosdeploystep.cpp
+++ b/src/plugins/ios/iosdeploystep.cpp
@@ -65,14 +65,14 @@ namespace Internal {
const Core::Id IosDeployStep::Id("Qt4ProjectManager.IosDeployStep");
-IosDeployStep::IosDeployStep(ProjectExplorer::BuildStepList *parent)
+IosDeployStep::IosDeployStep(BuildStepList *parent)
: BuildStep(parent, Id)
, m_expectFail(false)
{
ctor();
}
-IosDeployStep::IosDeployStep(ProjectExplorer::BuildStepList *parent,
+IosDeployStep::IosDeployStep(BuildStepList *parent,
IosDeployStep *other)
: BuildStep(parent, other)
, m_expectFail(false)
@@ -96,8 +96,8 @@ void IosDeployStep::ctor()
void IosDeployStep::updateDisplayNames()
{
- ProjectExplorer::IDevice::ConstPtr dev =
- ProjectExplorer::DeviceKitInformation::device(target()->kit());
+ IDevice::ConstPtr dev =
+ DeviceKitInformation::device(target()->kit());
const QString devName = dev.isNull() ? IosDevice::name() : dev->displayName();
setDefaultDisplayName(tr("Deploy to %1").arg(devName));
setDisplayName(tr("Deploy to %1").arg(devName));
@@ -106,7 +106,7 @@ void IosDeployStep::updateDisplayNames()
bool IosDeployStep::init()
{
QTC_ASSERT(m_transferStatus == NoTransfer, return false);
- m_device = ProjectExplorer::DeviceKitInformation::device(target()->kit());
+ m_device = DeviceKitInformation::device(target()->kit());
IosRunConfiguration * runConfig = qobject_cast<IosRunConfiguration *>(
this->target()->activeRunConfiguration());
QTC_ASSERT(runConfig, return false);
@@ -229,12 +229,12 @@ BuildStepConfigWidget *IosDeployStep::createConfigWidget()
bool IosDeployStep::fromMap(const QVariantMap &map)
{
- return ProjectExplorer::BuildStep::fromMap(map);
+ return BuildStep::fromMap(map);
}
QVariantMap IosDeployStep::toMap() const
{
- QVariantMap map = ProjectExplorer::BuildStep::toMap();
+ QVariantMap map = BuildStep::toMap();
return map;
}
diff --git a/src/plugins/ios/iosdevice.cpp b/src/plugins/ios/iosdevice.cpp
index 7fd6c89ce1b..fe584a28768 100644
--- a/src/plugins/ios/iosdevice.cpp
+++ b/src/plugins/ios/iosdevice.cpp
@@ -410,7 +410,7 @@ void deviceConnectedCallback(void *refCon, io_iterator_t iterator)
kr = IOObjectRelease(usbDevice);
}
}
- catch (std::exception &e) {
+ catch (const std::exception &e) {
qCWarning(detectLog) << "Exception " << e.what() << " in iosdevice.cpp deviceConnectedCallback";
}
catch (...) {
@@ -449,7 +449,7 @@ void deviceDisconnectedCallback(void *refCon, io_iterator_t iterator)
kr = IOObjectRelease(usbDevice);
}
}
- catch (std::exception &e) {
+ catch (const std::exception &e) {
qCWarning(detectLog) << "Exception " << e.what() << " in iosdevice.cpp deviceDisconnectedCallback";
}
catch (...) {
@@ -564,7 +564,7 @@ IosDevice::ConstPtr IosKitInformation::device(Kit *kit)
{
if (!kit)
return IosDevice::ConstPtr();
- ProjectExplorer::IDevice::ConstPtr dev = ProjectExplorer::DeviceKitInformation::device(kit);
+ IDevice::ConstPtr dev = DeviceKitInformation::device(kit);
IosDevice::ConstPtr res = dev.dynamicCast<const IosDevice>();
return res;
}
diff --git a/src/plugins/ios/iosdsymbuildstep.cpp b/src/plugins/ios/iosdsymbuildstep.cpp
index 92834cbdf9c..1eb5874ed04 100644
--- a/src/plugins/ios/iosdsymbuildstep.cpp
+++ b/src/plugins/ios/iosdsymbuildstep.cpp
@@ -400,7 +400,7 @@ QList<Id> IosDsymBuildStepFactory::availableCreationIds(BuildStepList *parent) c
&& parent->id() != ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
return QList<Id>();
Kit *kit = parent->target()->kit();
- Core::Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
+ Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
if (deviceType == Constants::IOS_DEVICE_TYPE
|| deviceType == Constants::IOS_SIMULATOR_TYPE)
return QList<Id>() << Id(Constants::IOS_DSYM_BUILD_STEP_ID);
@@ -414,7 +414,7 @@ bool IosDsymBuildStepFactory::canCreate(BuildStepList *parent, const Id id) cons
&& parent->id() != ProjectExplorer::Constants::BUILDSTEPS_DEPLOY)
return false;
Kit *kit = parent->target()->kit();
- Core::Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
+ Id deviceType = DeviceTypeKitInformation::deviceTypeId(kit);
return ((deviceType == Constants::IOS_DEVICE_TYPE
|| deviceType == Constants::IOS_SIMULATOR_TYPE)
&& id == Constants::IOS_DSYM_BUILD_STEP_ID);
diff --git a/src/plugins/ios/iosmanager.cpp b/src/plugins/ios/iosmanager.cpp
index 7c172ae5731..aecefef7466 100644
--- a/src/plugins/ios/iosmanager.cpp
+++ b/src/plugins/ios/iosmanager.cpp
@@ -57,9 +57,9 @@ using namespace ProjectExplorer;
namespace Ios {
namespace Internal {
-bool IosManager::supportsIos(ProjectExplorer::Target *target)
+bool IosManager::supportsIos(Target *target)
{
- if (!qobject_cast<QmakeProjectManager::QmakeProject *>(target->project()))
+ if (!qobject_cast<QmakeProject *>(target->project()))
return false;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
return version && version->type() == QLatin1String(Ios::Constants::IOSQT);
diff --git a/src/plugins/ios/iosqtversion.cpp b/src/plugins/ios/iosqtversion.cpp
index 3c51142253c..b73ef881107 100644
--- a/src/plugins/ios/iosqtversion.cpp
+++ b/src/plugins/ios/iosqtversion.cpp
@@ -89,20 +89,20 @@ QString IosQtVersion::invalidReason() const
return tmp;
}
-QList<ProjectExplorer::Abi> IosQtVersion::detectQtAbis() const
+QList<Abi> IosQtVersion::detectQtAbis() const
{
- QList<ProjectExplorer::Abi> abis = qtAbisFromLibrary(qtCorePaths(versionInfo(), qtVersionString()));
+ QList<Abi> abis = qtAbisFromLibrary(qtCorePaths(versionInfo(), qtVersionString()));
for (int i = 0; i < abis.count(); ++i) {
abis[i] = Abi(abis.at(i).architecture(),
abis.at(i).os(),
- ProjectExplorer::Abi::GenericMacFlavor,
+ Abi::GenericMacFlavor,
abis.at(i).binaryFormat(),
abis.at(i).wordWidth());
}
return abis;
}
-void IosQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const
+void IosQtVersion::addToEnvironment(const Kit *k, Utils::Environment &env) const
{
Q_UNUSED(k);
Q_UNUSED(env);
diff --git a/src/plugins/ios/iosrunconfiguration.cpp b/src/plugins/ios/iosrunconfiguration.cpp
index c96169711a9..05f30251fc2 100644
--- a/src/plugins/ios/iosrunconfiguration.cpp
+++ b/src/plugins/ios/iosrunconfiguration.cpp
@@ -46,6 +46,8 @@
#include <qtsupport/qtoutputformatter.h>
#include <qtsupport/qtkitinformation.h>
+#include <utils/fileutils.h>
+
#include <QList>
#include <QStandardItemModel>
@@ -130,7 +132,7 @@ void IosRunConfiguration::deviceChanges() {
enabledCheck();
}
-void IosRunConfiguration::proFileUpdated(QmakeProjectManager::QmakeProFileNode *pro, bool success,
+void IosRunConfiguration::proFileUpdated(QmakeProFileNode *pro, bool success,
bool parseInProgress)
{
if (m_profilePath != pro->path())
@@ -149,7 +151,7 @@ QWidget *IosRunConfiguration::createConfigurationWidget()
return new IosRunConfigurationWidget(this);
}
-Utils::OutputFormatter *IosRunConfiguration::createOutputFormatter() const
+OutputFormatter *IosRunConfiguration::createOutputFormatter() const
{
return new QtSupport::QtOutputFormatter(target()->project());
}
@@ -209,9 +211,9 @@ QString IosRunConfiguration::applicationName() const
return QString();
}
-Utils::FileName IosRunConfiguration::bundleDirectory() const
+FileName IosRunConfiguration::bundleDirectory() const
{
- Utils::FileName res;
+ FileName res;
Core::Id devType = DeviceTypeKitInformation::deviceTypeId(target()->kit());
bool isDevice = (devType == Constants::IOS_DEVICE_TYPE);
if (!isDevice && devType != Constants::IOS_SIMULATOR_TYPE) {
@@ -257,7 +259,7 @@ Utils::FileName IosRunConfiguration::bundleDirectory() const
return res;
}
-Utils::FileName IosRunConfiguration::localExecutable() const
+FileName IosRunConfiguration::localExecutable() const
{
return bundleDirectory().appendPath(applicationName());
}
@@ -301,7 +303,7 @@ QString IosRunConfiguration::disabledReason() const
{
if (m_parseInProgress)
return tr("The .pro file \"%1\" is currently being parsed.")
- .arg(QFileInfo(m_profilePath).fileName());
+ .arg(FileName::fromString(m_profilePath).fileName());
if (!m_parseSuccess)
return static_cast<QmakeProject *>(target()->project())
->disabledReasonForRunConfiguration(m_profilePath);
@@ -403,7 +405,7 @@ IosRunConfigurationWidget::~IosRunConfigurationWidget()
QString IosRunConfigurationWidget::argListToString(const QStringList &args) const
{
- return Utils::QtcProcess::joinArgs(args);
+ return QtcProcess::joinArgs(args);
}
QStringList IosRunConfigurationWidget::stringToArgList(const QString &args) const
diff --git a/src/plugins/ios/iosrunfactories.cpp b/src/plugins/ios/iosrunfactories.cpp
index d23b5e421c7..20ecea6f7af 100644
--- a/src/plugins/ios/iosrunfactories.cpp
+++ b/src/plugins/ios/iosrunfactories.cpp
@@ -132,8 +132,8 @@ bool IosRunConfigurationFactory::canHandle(Target *t) const
QList<RunConfiguration *> IosRunConfigurationFactory::runConfigurationsForNode(Target *t, const Node *n)
{
- QList<ProjectExplorer::RunConfiguration *> result;
- foreach (ProjectExplorer::RunConfiguration *rc, t->runConfigurations())
+ QList<RunConfiguration *> result;
+ foreach (RunConfiguration *rc, t->runConfigurations())
if (IosRunConfiguration *qt4c = qobject_cast<IosRunConfiguration *>(rc))
if (qt4c->profilePath() == n->path())
result << rc;
@@ -157,7 +157,7 @@ IosRunControlFactory::IosRunControlFactory(QObject *parent)
}
bool IosRunControlFactory::canRun(RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const
+ RunMode mode) const
{
if (mode != NormalRunMode && mode != DebugRunMode && mode != QmlProfilerRunMode
&& mode != DebugRunModeWithBreakOnMain)
@@ -166,16 +166,16 @@ bool IosRunControlFactory::canRun(RunConfiguration *runConfiguration,
}
RunControl *IosRunControlFactory::create(RunConfiguration *runConfig,
- ProjectExplorer::RunMode mode, QString *errorMessage)
+ RunMode mode, QString *errorMessage)
{
Q_ASSERT(canRun(runConfig, mode));
IosRunConfiguration *rc = qobject_cast<IosRunConfiguration *>(runConfig);
Q_ASSERT(rc);
RunControl *res = 0;
- Core::Id devId = ProjectExplorer::DeviceKitInformation::deviceId(rc->target()->kit());
+ Core::Id devId = DeviceKitInformation::deviceId(rc->target()->kit());
// The device can only run an application at a time, if an app is running stop it.
if (m_activeRunControls.contains(devId)) {
- if (QPointer<ProjectExplorer::RunControl> activeRunControl = m_activeRunControls[devId])
+ if (QPointer<RunControl> activeRunControl = m_activeRunControls[devId])
activeRunControl->stop();
m_activeRunControls.remove(devId);
}
diff --git a/src/plugins/ios/iosrunner.cpp b/src/plugins/ios/iosrunner.cpp
index c9cf1932a9d..83262715cc1 100644
--- a/src/plugins/ios/iosrunner.cpp
+++ b/src/plugins/ios/iosrunner.cpp
@@ -59,7 +59,7 @@ namespace Internal {
IosRunner::IosRunner(QObject *parent, IosRunConfiguration *runConfig, bool cppDebug, bool qmlDebug)
: QObject(parent), m_toolHandler(0), m_bundleDir(runConfig->bundleDirectory().toString()),
m_arguments(runConfig->commandLineArguments()),
- m_device(ProjectExplorer::DeviceKitInformation::device(runConfig->target()->kit())),
+ m_device(DeviceKitInformation::device(runConfig->target()->kit())),
m_cppDebug(cppDebug), m_qmlDebug(qmlDebug), m_cleanExit(false),
m_qmlPort(0), m_pid(0)
{
diff --git a/src/plugins/ios/iossimulator.cpp b/src/plugins/ios/iossimulator.cpp
index 5f63ed01f4e..2fb5afee5bf 100644
--- a/src/plugins/ios/iossimulator.cpp
+++ b/src/plugins/ios/iossimulator.cpp
@@ -209,7 +209,7 @@ IosSimulator::ConstPtr IosKitInformation::simulator(Kit *kit)
{
if (!kit)
return IosSimulator::ConstPtr();
- ProjectExplorer::IDevice::ConstPtr dev = ProjectExplorer::DeviceKitInformation::device(kit);
+ IDevice::ConstPtr dev = DeviceKitInformation::device(kit);
IosSimulator::ConstPtr res = dev.dynamicCast<const IosSimulator>();
return res;
}
diff --git a/src/plugins/macros/findmacrohandler.cpp b/src/plugins/macros/findmacrohandler.cpp
index 0c75e65bb31..3c572dc73ec 100644
--- a/src/plugins/macros/findmacrohandler.cpp
+++ b/src/plugins/macros/findmacrohandler.cpp
@@ -205,18 +205,18 @@ void FindMacroHandler::changeEditor(Core::IEditor *editor)
aggregate->add(macroFind);
// Connect all signals
- connect(macroFind, SIGNAL(allReplaced(QString,QString,Core::FindFlags)),
- this, SLOT(replaceAll(QString,QString,Core::FindFlags)));
- connect(macroFind, SIGNAL(incrementalFound(QString,Core::FindFlags)),
- this, SLOT(findIncremental(QString,Core::FindFlags)));
- connect(macroFind, SIGNAL(incrementalSearchReseted()),
- this, SLOT(resetIncrementalSearch()));
- connect(macroFind, SIGNAL(replaced(QString,QString,Core::FindFlags)),
- this, SLOT(replace(QString,QString,Core::FindFlags)));
- connect(macroFind, SIGNAL(stepFound(QString,Core::FindFlags)),
- this, SLOT(findStep(QString,Core::FindFlags)));
- connect(macroFind, SIGNAL(stepReplaced(QString,QString,Core::FindFlags)),
- this, SLOT(replaceStep(QString,QString,Core::FindFlags)));
+ connect(macroFind, &MacroTextFind::allReplaced,
+ this, &FindMacroHandler::replaceAll);
+ connect(macroFind, &MacroTextFind::incrementalFound,
+ this, &FindMacroHandler::findIncremental);
+ connect(macroFind, &MacroTextFind::incrementalSearchReseted,
+ this, &FindMacroHandler::resetIncrementalSearch);
+ connect(macroFind, &MacroTextFind::replaced,
+ this, &FindMacroHandler::replace);
+ connect(macroFind, &MacroTextFind::stepFound,
+ this, &FindMacroHandler::findStep);
+ connect(macroFind, &MacroTextFind::stepReplaced,
+ this, &FindMacroHandler::replaceStep);
}
}
}
diff --git a/src/plugins/macros/macrooptionswidget.cpp b/src/plugins/macros/macrooptionswidget.cpp
index 9ec6b716a33..465a2ac02dd 100644
--- a/src/plugins/macros/macrooptionswidget.cpp
+++ b/src/plugins/macros/macrooptionswidget.cpp
@@ -61,12 +61,12 @@ MacroOptionsWidget::MacroOptionsWidget(QWidget *parent) :
{
m_ui->setupUi(this);
- connect(m_ui->treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
- this, SLOT(changeCurrentItem(QTreeWidgetItem*)));
- connect(m_ui->removeButton, SIGNAL(clicked()),
- this, SLOT(remove()));
- connect(m_ui->description, SIGNAL(textChanged(QString)),
- this, SLOT(changeDescription(QString)));
+ connect(m_ui->treeWidget, &QTreeWidget::currentItemChanged,
+ this, &MacroOptionsWidget::changeCurrentItem);
+ connect(m_ui->removeButton, &QPushButton::clicked,
+ this, &MacroOptionsWidget::remove);
+ connect(m_ui->description, &QLineEdit::textChanged,
+ this, &MacroOptionsWidget::changeDescription);
m_ui->treeWidget->header()->setSortIndicator(0, Qt::AscendingOrder);
diff --git a/src/plugins/macros/macrosplugin.cpp b/src/plugins/macros/macrosplugin.cpp
index 0b2f8f88fd3..46ee1e5bd66 100644
--- a/src/plugins/macros/macrosplugin.cpp
+++ b/src/plugins/macros/macrosplugin.cpp
@@ -86,26 +86,26 @@ bool MacrosPlugin::initialize(const QStringList &arguments, QString *errorMessag
Core::Command *command = Core::ActionManager::registerAction(startMacro, Constants::START_MACRO, textContext);
command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Ctrl+(") : tr("Alt+(")));
mmacrotools->addAction(command);
- connect(startMacro, SIGNAL(triggered()), m_macroManager, SLOT(startMacro()));
+ connect(startMacro, &QAction::triggered, m_macroManager, &MacroManager::startMacro);
QAction *endMacro = new QAction(tr("Stop Recording Macro"), this);
endMacro->setEnabled(false);
command = Core::ActionManager::registerAction(endMacro, Constants::END_MACRO, globalcontext);
command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Ctrl+)") : tr("Alt+)")));
mmacrotools->addAction(command);
- connect(endMacro, SIGNAL(triggered()), m_macroManager, SLOT(endMacro()));
+ connect(endMacro, &QAction::triggered, m_macroManager, &MacroManager::endMacro);
QAction *executeLastMacro = new QAction(tr("Play Last Macro"), this);
command = Core::ActionManager::registerAction(executeLastMacro, Constants::EXECUTE_LAST_MACRO, textContext);
command->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+R") : tr("Alt+R")));
mmacrotools->addAction(command);
- connect(executeLastMacro, SIGNAL(triggered()), m_macroManager, SLOT(executeLastMacro()));
+ connect(executeLastMacro, &QAction::triggered, m_macroManager, &MacroManager::executeLastMacro);
QAction *saveLastMacro = new QAction(tr("Save Last Macro"), this);
saveLastMacro->setEnabled(false);
command = Core::ActionManager::registerAction(saveLastMacro, Constants::SAVE_LAST_MACRO, textContext);
mmacrotools->addAction(command);
- connect(saveLastMacro, SIGNAL(triggered()), m_macroManager, SLOT(saveLastMacro()));
+ connect(saveLastMacro, &QAction::triggered, m_macroManager, &MacroManager::saveLastMacro);
return true;
}
diff --git a/src/plugins/mercurial/clonewizard.cpp b/src/plugins/mercurial/clonewizard.cpp
index 5aa46671f33..bd4e4328190 100644
--- a/src/plugins/mercurial/clonewizard.cpp
+++ b/src/plugins/mercurial/clonewizard.cpp
@@ -36,7 +36,7 @@
#include <coreplugin/iversioncontrol.h>
#include <vcsbase/vcscommand.h>
#include <vcsbase/vcsbaseconstants.h>
-#include <vcsbase/vcsconfigurationpage.h>
+#include <vcsbase/wizard/vcsconfigurationpage.h>
using namespace VcsBase;
@@ -53,9 +53,12 @@ CloneWizard::CloneWizard(const Utils::FileName &path, QWidget *parent) :
setStartedStatus(tr("Cloning started..."));
const Core::IVersionControl *vc = MercurialPlugin::instance()->versionControl();
- if (!vc->isConfigured())
- addPage(new VcsConfigurationPage(vc));
- CloneWizardPage *page = new CloneWizardPage;
+ if (!vc->isConfigured()) {
+ auto configPage = new VcsConfigurationPage;
+ configPage->setVersionControl(vc);
+ addPage(configPage);
+ }
+ auto page = new CloneWizardPage;
page->setPath(path.toString());
addPage(page);
}
@@ -79,8 +82,8 @@ VcsCommand *CloneWizard::createCommand(Utils::FileName *checkoutDir)
QStringList args;
args << QLatin1String("clone") << cwp->repository() << directory;
*checkoutDir = Utils::FileName::fromString(path + QLatin1Char('/') + directory);
- VcsCommand *command = new VcsCommand(settings.binaryPath(), path,
- QProcessEnvironment::systemEnvironment());
+ auto command = new VcsCommand(settings.binaryPath(), path,
+ QProcessEnvironment::systemEnvironment());
command->addJob(args, -1);
return command;
}
diff --git a/src/plugins/mercurial/commiteditor.cpp b/src/plugins/mercurial/commiteditor.cpp
index 81d2d7f34f7..73b9b7ab845 100644
--- a/src/plugins/mercurial/commiteditor.cpp
+++ b/src/plugins/mercurial/commiteditor.cpp
@@ -71,7 +71,7 @@ void CommitEditor::setFields(const QFileInfo &repositoryRoot, const QString &bra
if (item.flags == QLatin1String("Untracked"))
shouldTrack.append(item.file);
else
- fileModel->addFile(item.file, item.flags, VcsBase::Unchecked);
+ fileModel->addFile(item.file, item.flags, Unchecked);
}
VcsBaseSubmitEditor::filterUntrackedFilesOfProject(repositoryRoot.absoluteFilePath(),
@@ -80,7 +80,7 @@ void CommitEditor::setFields(const QFileInfo &repositoryRoot, const QString &bra
foreach (const QString &track, shouldTrack) {
foreach (const VcsBaseClient::StatusItem &item, repoStatus) {
if (item.file == track)
- fileModel->addFile(item.file, item.flags, VcsBase::Unchecked);
+ fileModel->addFile(item.file, item.flags, Unchecked);
}
}
diff --git a/src/plugins/mercurial/mercurialclient.cpp b/src/plugins/mercurial/mercurialclient.cpp
index e348e4bc906..ac3eed0eb62 100644
--- a/src/plugins/mercurial/mercurialclient.cpp
+++ b/src/plugins/mercurial/mercurialclient.cpp
@@ -53,9 +53,25 @@ using namespace VcsBase;
namespace Mercurial {
namespace Internal {
+// Parameter widget controlling whitespace diff mode, associated with a parameter
+class MercurialDiffParameterWidget : public VcsBaseEditorParameterWidget
+{
+ Q_OBJECT
+public:
+ MercurialDiffParameterWidget(MercurialSettings *settings, QWidget *parent = 0) :
+ VcsBaseEditorParameterWidget(parent)
+ {
+ mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace")),
+ settings->boolPointer(MercurialSettings::diffIgnoreWhiteSpaceKey));
+ mapSetting(addToggleButton(QLatin1String("-B"), tr("Ignore Blank Lines")),
+ settings->boolPointer(MercurialSettings::diffIgnoreBlankLinesKey));
+ }
+};
+
MercurialClient::MercurialClient(MercurialSettings *settings) :
VcsBaseClient(settings)
{
+ setDiffParameterWidgetCreator([=] { return new MercurialDiffParameterWidget(settings); });
}
MercurialSettings *MercurialClient::settings() const
@@ -236,7 +252,7 @@ QString MercurialClient::shortDescriptionSync(const QString &workingDirectory,
QByteArray outputData;
if (!vcsFullySynchronousExec(workingDirectory, args, &outputData))
return revision;
- description = Utils::SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(outputData));
+ description = SynchronousProcess::normalizeNewlines(QString::fromLocal8Bit(outputData));
if (description.endsWith(QLatin1Char('\n')))
description.truncate(description.size() - 1);
return description;
@@ -251,18 +267,6 @@ QString MercurialClient::shortDescriptionSync(const QString &workingDirectory,
return shortDescriptionSync(workingDirectory, revision, QLatin1String(defaultFormatC));
}
-QString MercurialClient::vcsGetRepositoryURL(const QString &directory)
-{
- QByteArray output;
-
- QStringList arguments(QLatin1String("showconfig"));
- arguments << QLatin1String("paths.default");
-
- if (vcsFullySynchronousExec(directory, arguments, &output))
- return QString::fromLocal8Bit(output);
- return QString();
-}
-
bool MercurialClient::managesFile(const QString &workingDirectory, const QString &fileName) const
{
QStringList args;
@@ -280,10 +284,8 @@ void MercurialClient::incoming(const QString &repositoryRoot, const QString &rep
args.append(repository);
QString id = repositoryRoot;
- if (!repository.isEmpty()) {
- id += QDir::separator();
- id += repository;
- }
+ if (!repository.isEmpty())
+ id += QLatin1Char('/') + repository;
const QString title = tr("Hg incoming %1").arg(id);
@@ -426,50 +428,6 @@ void MercurialClient::parsePullOutput(const QString &output)
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
-{
- QString workingDir;
- QStringList files;
- QStringList extraOptions;
-};
-
-// Parameter widget controlling whitespace diff mode, associated with a parameter
-class MercurialDiffParameterWidget : public VcsBaseEditorParameterWidget
-{
- Q_OBJECT
-public:
- MercurialDiffParameterWidget(MercurialClient *client,
- const MercurialDiffParameters &p, QWidget *parent = 0) :
- VcsBaseEditorParameterWidget(parent), m_client(client), m_params(p)
- {
- mapSetting(addToggleButton(QLatin1String("-w"), tr("Ignore Whitespace")),
- client->settings()->boolPointer(MercurialSettings::diffIgnoreWhiteSpaceKey));
- mapSetting(addToggleButton(QLatin1String("-B"), tr("Ignore Blank Lines")),
- client->settings()->boolPointer(MercurialSettings::diffIgnoreBlankLinesKey));
- }
-
- void executeCommand()
- {
- m_client->diff(m_params.workingDir, m_params.files, m_params.extraOptions);
- }
-
-private:
- MercurialClient *m_client;
- const MercurialDiffParameters m_params;
-};
-
-VcsBaseEditorParameterWidget *MercurialClient::createDiffEditor(
- const QString &workingDir, const QStringList &files, const QStringList &extraOptions)
-{
- MercurialDiffParameters parameters;
- parameters.workingDir = workingDir;
- parameters.files = files;
- parameters.extraOptions = extraOptions;
- return new MercurialDiffParameterWidget(this, parameters);
-}
-
} // namespace Internal
} // namespace Mercurial
diff --git a/src/plugins/mercurial/mercurialclient.h b/src/plugins/mercurial/mercurialclient.h
index baf3ef11a9a..cae751fce8b 100644
--- a/src/plugins/mercurial/mercurialclient.h
+++ b/src/plugins/mercurial/mercurialclient.h
@@ -63,7 +63,6 @@ public:
QString shortDescriptionSync(const QString &workingDirectory, const QString &revision);
void incoming(const QString &repositoryRoot, const QString &repository = QString());
void outgoing(const QString &repositoryRoot);
- QString vcsGetRepositoryURL(const QString &directory);
bool managesFile(const QString &workingDirectory, const QString &fileName) const;
void annotate(const QString &workingDir, const QString &file,
@@ -87,9 +86,6 @@ public:
protected:
Core::Id vcsEditorKind(VcsCommandTag cmd) const;
QStringList revisionSpec(const QString &revision) const;
- VcsBase::VcsBaseEditorParameterWidget *createDiffEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions);
StatusItem parseStatusLine(const QString &line) const;
signals:
diff --git a/src/plugins/mercurial/mercurialcontrol.cpp b/src/plugins/mercurial/mercurialcontrol.cpp
index c6f38b7eb57..fbbfe202461 100644
--- a/src/plugins/mercurial/mercurialcontrol.cpp
+++ b/src/plugins/mercurial/mercurialcontrol.cpp
@@ -112,8 +112,6 @@ bool MercurialControl::supportsOperation(Operation operation) const
case Core::IVersionControl::MoveOperation:
case Core::IVersionControl::CreateRepositoryOperation:
case Core::IVersionControl::AnnotateOperation:
- case Core::IVersionControl::CheckoutOperation:
- case Core::IVersionControl::GetRepositoryRootOperation:
break;
case Core::IVersionControl::SnapshotOperations:
supported = false;
@@ -172,16 +170,6 @@ bool MercurialControl::sccManaged(const QString &filename)
return mercurialClient->manifestSync(topLevel, topLevelDir.relativeFilePath(filename));
}
-bool MercurialControl::vcsCheckout(const QString &directory, const QByteArray &url)
-{
- return mercurialClient->synchronousClone(QString(), directory, QLatin1String(url));
-}
-
-QString MercurialControl::vcsGetRepositoryURL(const QString &directory)
-{
- return mercurialClient->vcsGetRepositoryURL(directory);
-}
-
void MercurialControl::changed(const QVariant &v)
{
switch (v.type()) {
diff --git a/src/plugins/mercurial/mercurialcontrol.h b/src/plugins/mercurial/mercurialcontrol.h
index 6bf15e2f3b0..e3db1a08938 100644
--- a/src/plugins/mercurial/mercurialcontrol.h
+++ b/src/plugins/mercurial/mercurialcontrol.h
@@ -62,8 +62,6 @@ public:
bool vcsDelete(const QString &filename);
bool vcsMove(const QString &from, const QString &to);
bool vcsCreateRepository(const QString &directory);
- bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
bool sccManaged(const QString &filename);
bool vcsAnnotate(const QString &file, int line);
diff --git a/src/plugins/mercurial/mercurialplugin.cpp b/src/plugins/mercurial/mercurialplugin.cpp
index a552d022594..137a9de51cf 100644
--- a/src/plugins/mercurial/mercurialplugin.cpp
+++ b/src/plugins/mercurial/mercurialplugin.cpp
@@ -320,12 +320,9 @@ void MercurialPlugin::statusCurrentFile()
void MercurialPlugin::createDirectoryActions(const Core::Context &context)
{
- QAction *action;
- Core::Command *command;
-
- action = new QAction(tr("Diff"), this);
+ auto action = new QAction(tr("Diff"), this);
m_repositoryActionList.append(action);
- command = Core::ActionManager::registerAction(action, Core::Id(Constants::DIFFMULTI), context);
+ Core::Command *command = Core::ActionManager::registerAction(action, Core::Id(Constants::DIFFMULTI), context);
connect(action, SIGNAL(triggered()), this, SLOT(diffRepository()));
m_mercurialContainer->addAction(command);
m_commandLocator->appendCommand(command);
@@ -387,7 +384,7 @@ void MercurialPlugin::statusMulti()
void MercurialPlugin::createRepositoryActions(const Core::Context &context)
{
- QAction *action = new QAction(tr("Pull..."), this);
+ auto action = new QAction(tr("Pull..."), this);
m_repositoryActionList.append(action);
Core::Command *command = Core::ActionManager::registerAction(action, Core::Id(Constants::PULL), context);
connect(action, SIGNAL(triggered()), this, SLOT(pull()));
@@ -517,10 +514,9 @@ void MercurialPlugin::outgoing()
void MercurialPlugin::createSubmitEditorActions()
{
Core::Context context(Constants::COMMIT_ID);
- Core::Command *command;
editorCommit = new QAction(VcsBaseSubmitEditor::submitIcon(), tr("Commit"), this);
- command = Core::ActionManager::registerAction(editorCommit, Core::Id(Constants::COMMIT), context);
+ Core::Command *command = Core::ActionManager::registerAction(editorCommit, Core::Id(Constants::COMMIT), context);
command->setAttribute(Core::Command::CA_UpdateText);
connect(editorCommit, SIGNAL(triggered()), this, SLOT(commitFromEditor()));
@@ -559,7 +555,7 @@ void MercurialPlugin::showCommitWidget(const QList<VcsBaseClient::StatusItem> &s
}
// Start new temp file
- Utils::TempFileSaver saver;
+ TempFileSaver saver;
// Keep the file alive, else it removes self and forgets its name
saver.setAutoRemove(false);
if (!saver.finalize()) {
@@ -638,7 +634,7 @@ bool MercurialPlugin::submitEditorAboutToClose()
QStringList extraOptions;
if (!commitEditor->committerInfo().isEmpty())
extraOptions << QLatin1String("-u") << commitEditor->committerInfo();
- m_client->commit(m_submitRepository, files, editorFile->filePath(),
+ m_client->commit(m_submitRepository, files, editorFile->filePath().toString(),
extraOptions);
}
return true;
@@ -649,7 +645,7 @@ void MercurialPlugin::createRepositoryManagementActions(const Core::Context &con
//TODO create menu for these options
Q_UNUSED(context);
return;
- // QAction *action = new QAction(tr("Branch"), this);
+ // auto action = new QAction(tr("Branch"), this);
// actionList.append(action);
// Core::Command *command = Core::ActionManager::registerAction(action, Constants::BRANCH, context);
// // connect(action, SIGNAL(triggered()), this, SLOT(branch()));
diff --git a/src/plugins/perforce/perforcechecker.cpp b/src/plugins/perforce/perforcechecker.cpp
index 223f4621232..1e6518c9493 100644
--- a/src/plugins/perforce/perforcechecker.cpp
+++ b/src/plugins/perforce/perforcechecker.cpp
@@ -51,10 +51,10 @@ PerforceChecker::PerforceChecker(QObject *parent) :
m_useOverideCursor(false),
m_isOverrideCursor(false)
{
- connect(&m_process, SIGNAL(error(QProcess::ProcessError)),
- this, SLOT(slotError(QProcess::ProcessError)));
- connect(&m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
- this, SLOT(slotFinished(int,QProcess::ExitStatus)));
+ connect(&m_process, static_cast<void (QProcess::*)(QProcess::ProcessError)>(&QProcess::error),
+ this, &PerforceChecker::slotError);
+ connect(&m_process, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
+ this, &PerforceChecker::slotFinished);
}
PerforceChecker::~PerforceChecker()
diff --git a/src/plugins/perforce/perforceplugin.cpp b/src/plugins/perforce/perforceplugin.cpp
index bf248d2df35..a5e00a22992 100644
--- a/src/plugins/perforce/perforceplugin.cpp
+++ b/src/plugins/perforce/perforceplugin.cpp
@@ -98,15 +98,15 @@ const char PERFORCE_ANNOTATION_EDITOR_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("VCS",
const VcsBaseEditorParameters editorParameters[] = {
{
- VcsBase::LogOutput,
+ LogOutput,
PERFORCE_LOG_EDITOR_ID,
PERFORCE_LOG_EDITOR_DISPLAY_NAME,
"text/vnd.qtcreator.p4.log"},
-{ VcsBase::AnnotateOutput,
+{ AnnotateOutput,
PERFORCE_ANNOTATION_EDITOR_ID,
PERFORCE_ANNOTATION_EDITOR_DISPLAY_NAME,
"text/vnd.qtcreator.p4.annotation"},
-{ VcsBase::DiffOutput,
+{ DiffOutput,
PERFORCE_DIFF_EDITOR_ID,
PERFORCE_DIFF_EDITOR_DISPLAY_NAME,
"text/x-patch"}
@@ -249,18 +249,18 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
ActionContainer *mtools = ActionManager::actionContainer(Core::Constants::M_TOOLS);
- Core::ActionContainer *perforceContainer = ActionManager::createMenu(CMD_ID_PERFORCE_MENU);
+ ActionContainer *perforceContainer = ActionManager::createMenu(CMD_ID_PERFORCE_MENU);
perforceContainer->menu()->setTitle(tr("&Perforce"));
mtools->addMenu(perforceContainer);
m_menuAction = perforceContainer->menu()->menuAction();
Context perforcesubmitcontext(PERFORCE_SUBMIT_EDITOR_ID);
- Core::Command *command;
+ Command *command;
m_diffFileAction = new ParameterAction(tr("Diff Current File"), tr("Diff \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_diffFileAction, CMD_ID_DIFF_CURRENT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDescription(tr("Diff Current File"));
connect(m_diffFileAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
perforceContainer->addAction(command);
@@ -268,7 +268,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_annotateCurrentAction = new ParameterAction(tr("Annotate Current File"), tr("Annotate \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_annotateCurrentAction, CMD_ID_ANNOTATE_CURRENT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDescription(tr("Annotate Current File"));
connect(m_annotateCurrentAction, SIGNAL(triggered()), this, SLOT(annotateCurrentFile()));
perforceContainer->addAction(command);
@@ -276,7 +276,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_filelogCurrentAction = new ParameterAction(tr("Filelog Current File"), tr("Filelog \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_filelogCurrentAction, CMD_ID_FILELOG_CURRENT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+P,Meta+F") : tr("Alt+P,Alt+F")));
command->setDescription(tr("Filelog Current File"));
connect(m_filelogCurrentAction, SIGNAL(triggered()), this, SLOT(filelogCurrentFile()));
@@ -287,7 +287,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_editAction = new ParameterAction(tr("Edit"), tr("Edit \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_editAction, CMD_ID_EDIT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+P,Meta+E") : tr("Alt+P,Alt+E")));
command->setDescription(tr("Edit File"));
connect(m_editAction, SIGNAL(triggered()), this, SLOT(openCurrentFile()));
@@ -296,7 +296,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_addAction = new ParameterAction(tr("Add"), tr("Add \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_addAction, CMD_ID_ADD, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+P,Meta+A") : tr("Alt+P,Alt+A")));
command->setDescription(tr("Add File"));
connect(m_addAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
@@ -305,7 +305,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_deleteAction = new ParameterAction(tr("Delete..."), tr("Delete \"%1\"..."), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_deleteAction, CMD_ID_DELETE_FILE, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDescription(tr("Delete File"));
connect(m_deleteAction, SIGNAL(triggered()), this, SLOT(promptToDeleteCurrentFile()));
perforceContainer->addAction(command);
@@ -313,7 +313,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_revertFileAction = new ParameterAction(tr("Revert"), tr("Revert \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_revertFileAction, CMD_ID_REVERT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+P,Meta+R") : tr("Alt+P,Alt+R")));
command->setDescription(tr("Revert File"));
connect(m_revertFileAction, SIGNAL(triggered()), this, SLOT(revertCurrentFile()));
@@ -325,7 +325,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
const QString diffProjectDefaultText = tr("Diff Current Project/Session");
m_diffProjectAction = new ParameterAction(diffProjectDefaultText, tr("Diff Project \"%1\""), ParameterAction::AlwaysEnabled, this);
command = ActionManager::registerAction(m_diffProjectAction, CMD_ID_DIFF_PROJECT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+P,Meta+D") : tr("Alt+P,Alt+D")));
command->setDescription(diffProjectDefaultText);
connect(m_diffProjectAction, SIGNAL(triggered()), this, SLOT(diffCurrentProject()));
@@ -334,14 +334,14 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_logProjectAction = new ParameterAction(tr("Log Project"), tr("Log Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_logProjectAction, CMD_ID_PROJECTLOG, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_logProjectAction, SIGNAL(triggered()), this, SLOT(logProject()));
perforceContainer->addAction(command);
m_commandLocator->appendCommand(command);
m_submitProjectAction = new ParameterAction(tr("Submit Project"), tr("Submit Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_submitProjectAction, CMD_ID_SUBMIT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+P,Meta+S") : tr("Alt+P,Alt+S")));
connect(m_submitProjectAction, SIGNAL(triggered()), this, SLOT(startSubmitProject()));
perforceContainer->addAction(command);
@@ -351,21 +351,21 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_updateProjectAction = new ParameterAction(updateProjectDefaultText, tr("Update Project \"%1\""), ParameterAction::AlwaysEnabled, this);
command = ActionManager::registerAction(m_updateProjectAction, CMD_ID_UPDATE_PROJECT, context);
command->setDescription(updateProjectDefaultText);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_updateProjectAction, SIGNAL(triggered()), this, SLOT(updateCurrentProject()));
perforceContainer->addAction(command);
m_commandLocator->appendCommand(command);
m_revertUnchangedAction = new ParameterAction(tr("Revert Unchanged"), tr("Revert Unchanged Files of Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_revertUnchangedAction, CMD_ID_REVERT_UNCHANGED_PROJECT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_revertUnchangedAction, SIGNAL(triggered()), this, SLOT(revertUnchangedCurrentProject()));
perforceContainer->addAction(command);
m_commandLocator->appendCommand(command);
m_revertProjectAction = new ParameterAction(tr("Revert Project"), tr("Revert Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_revertProjectAction, CMD_ID_REVERT_PROJECT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_revertProjectAction, SIGNAL(triggered()), this, SLOT(revertCurrentProject()));
perforceContainer->addAction(command);
m_commandLocator->appendCommand(command);
@@ -422,7 +422,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
m_submitCurrentLogAction = new QAction(VcsBaseSubmitEditor::submitIcon(), tr("Submit"), this);
command = ActionManager::registerAction(m_submitCurrentLogAction, SUBMIT_CURRENT, perforcesubmitcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_submitCurrentLogAction, SIGNAL(triggered()), this, SLOT(submitCurrentLog()));
m_diffSelectedFiles = new QAction(VcsBaseSubmitEditor::diffIcon(), tr("Diff &Selected Files"), this);
@@ -734,7 +734,7 @@ void PerforcePlugin::annotate(const QString &workingDir,
if (lineNumber < 1)
lineNumber = VcsBaseEditor::lineNumberOfCurrentEditor();
IEditor *ed = showOutputInEditor(tr("p4 annotate %1").arg(id),
- result.stdOut, VcsBase::AnnotateOutput,
+ result.stdOut, AnnotateOutput,
source, codec);
VcsBaseEditor::gotoLineOfEditor(ed, lineNumber);
}
@@ -760,14 +760,14 @@ void PerforcePlugin::logProject()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasProject(), return);
- filelog(state.currentProjectTopLevel(), perforceRelativeFileArguments(state.relativeCurrentProject()));
+ changelists(state.currentProjectTopLevel(), perforceRelativeFileArguments(state.relativeCurrentProject()));
}
void PerforcePlugin::logRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- filelog(state.topLevel(), perforceRelativeFileArguments(QString()));
+ changelists(state.topLevel(), perforceRelativeFileArguments(QString()));
}
void PerforcePlugin::filelog(const QString &workingDir, const QString &fileName,
@@ -787,12 +787,33 @@ void PerforcePlugin::filelog(const QString &workingDir, const QString &fileName,
if (!result.error) {
const QString source = VcsBaseEditor::getSource(workingDir, fileName);
IEditor *editor = showOutputInEditor(tr("p4 filelog %1").arg(id), result.stdOut,
- VcsBase::LogOutput, source, codec);
+ LogOutput, source, codec);
if (enableAnnotationContextMenu)
VcsBaseEditor::getVcsBaseEditor(editor)->setFileLogAnnotateEnabled(true);
}
}
+void PerforcePlugin::changelists(const QString &workingDir, const QString &fileName)
+{
+ const QString id = VcsBaseEditor::getTitleId(workingDir, QStringList(fileName));
+ QTextCodec *codec = VcsBaseEditor::getCodec(workingDir, QStringList(fileName));
+ QStringList args;
+ args << QLatin1String("changelists") << QLatin1String("-lit");
+ if (m_settings.logCount() > 0)
+ args << QLatin1String("-m") << QString::number(m_settings.logCount());
+ if (!fileName.isEmpty())
+ args.append(fileName);
+ const PerforceResponse result = runP4Cmd(workingDir, args,
+ CommandToWindow|StdErrToWindow|ErrorToWindow,
+ QStringList(), QByteArray(), codec);
+ if (!result.error) {
+ const QString source = VcsBaseEditor::getSource(workingDir, fileName);
+ IEditor *editor = showOutputInEditor(tr("p4 changelists %1").arg(id), result.stdOut,
+ LogOutput, source, codec);
+ VcsBaseEditor::gotoLineOfEditor(editor, 1);
+ }
+}
+
void PerforcePlugin::updateActions(VcsBasePlugin::ActionState as)
{
const bool menuActionEnabled = enableMenuAction(as, m_menuAction);
@@ -941,8 +962,9 @@ PerforcePlugin::createTemporaryArgumentFile(const QStringList &extraArgs,
QString pattern = m_instance->m_tempFilePattern;
if (pattern.isEmpty()) {
pattern = QDir::tempPath();
- if (!pattern.endsWith(QDir::separator()))
- pattern += QDir::separator();
+ const QChar slash = QLatin1Char('/');
+ if (!pattern.endsWith(slash))
+ pattern += slash;
pattern += QLatin1String("qtc_p4_XXXXXX.args");
m_instance->m_tempFilePattern = pattern;
}
@@ -1188,7 +1210,7 @@ IEditor *PerforcePlugin::showOutputInEditor(const QString &title,
const int maxSize = EditorManager::maxTextFileSize() / 2 - 1000; // ~25 MB, 600000 lines
if (content.size() >= maxSize) {
content = content.left(maxSize);
- content += QLatin1Char('\n') + tr("[Only %1 MB of output shown]").arg(maxSize / 1024 / 1024);
+ content += QLatin1Char('\n') + tr("[Only %n MB of output shown]", 0, maxSize / 1024 / 1024);
}
IEditor *editor = EditorManager::openEditorWithContents(id, &s, content.toUtf8());
QTC_ASSERT(editor, return 0);
@@ -1264,7 +1286,7 @@ void PerforcePlugin::p4Diff(const PerforceDiffParameters &p)
QTextCodec *codec = VcsBaseEditor::getCodec(p.workingDir, p.files);
const QString id = VcsBaseEditor::getTitleId(p.workingDir, p.files);
// Reuse existing editors for that id
- const QString tag = VcsBaseEditor::editorTag(VcsBase::DiffOutput, p.workingDir, p.files);
+ const QString tag = VcsBaseEditor::editorTag(DiffOutput, p.workingDir, p.files);
IEditor *existingEditor = VcsBaseEditor::locateEditorByTag(tag);
// Split arguments according to size
QStringList args;
@@ -1295,7 +1317,7 @@ void PerforcePlugin::p4Diff(const PerforceDiffParameters &p)
VcsBaseEditorWidget *diffEditorWidget = qobject_cast<VcsBaseEditorWidget *>(editor->widget());
// Wire up the parameter widget to trigger a re-run on
// parameter change and 'revert' from inside the diff editor.
- PerforceDiffParameterWidget *pw = new PerforceDiffParameterWidget(p);
+ auto pw = new PerforceDiffParameterWidget(p);
connect(pw, SIGNAL(reRunDiff(Perforce::Internal::PerforceDiffParameters)),
this, SLOT(p4Diff(Perforce::Internal::PerforceDiffParameters)));
connect(diffEditorWidget, SIGNAL(diffChunkReverted(VcsBase::DiffChunk)),
@@ -1526,11 +1548,11 @@ void PerforcePlugin::getTopLevel()
// Run a new checker
if (m_instance->m_settings.p4BinaryPath().isEmpty())
return;
- 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)), m_instance, SLOT(slotTopLevelFound(QString)));
- connect(checker, SIGNAL(succeeded(QString)),checker, SLOT(deleteLater()));
+ auto checker = new PerforceChecker(m_instance);
+ connect(checker, &PerforceChecker::failed, m_instance, &PerforcePlugin::slotTopLevelFailed);
+ connect(checker, &PerforceChecker::failed, checker, &QObject::deleteLater);
+ connect(checker, &PerforceChecker::succeeded, m_instance, &PerforcePlugin::slotTopLevelFound);
+ connect(checker, &PerforceChecker::succeeded,checker, &QObject::deleteLater);
checker->start(settings().p4BinaryPath(), settings().commonP4Arguments(QString()), 30000);
}
diff --git a/src/plugins/perforce/perforceplugin.h b/src/plugins/perforce/perforceplugin.h
index dea5dfa9fca..f6ce849533d 100644
--- a/src/plugins/perforce/perforceplugin.h
+++ b/src/plugins/perforce/perforceplugin.h
@@ -192,6 +192,7 @@ private:
const QString &changeList = QString(), int lineNumber = -1);
void filelog(const QString &workingDir, const QString &fileName = QString(),
bool enableAnnotationContextMenu = false);
+ void changelists(const QString &workingDir, const QString &fileName = QString());
void cleanCommitMessageFile();
bool isCommitEditorOpen() const;
static QSharedPointer<Utils::TempFileSaver> createTemporaryArgumentFile(const QStringList &extraArgs,
diff --git a/src/plugins/perforce/perforceversioncontrol.cpp b/src/plugins/perforce/perforceversioncontrol.cpp
index b51e4844e89..8ae4b02c069 100644
--- a/src/plugins/perforce/perforceversioncontrol.cpp
+++ b/src/plugins/perforce/perforceversioncontrol.cpp
@@ -76,8 +76,6 @@ bool PerforceVersionControl::supportsOperation(Operation operation) const
return supported;
case CreateRepositoryOperation:
case SnapshotOperations:
- case CheckoutOperation:
- case GetRepositoryRootOperation:
break;
}
return false;
@@ -134,16 +132,6 @@ bool PerforceVersionControl::vcsAnnotate(const QString &file, int line)
return true;
}
-bool PerforceVersionControl::vcsCheckout(const QString &,const QByteArray &)
-{
- return false;
-}
-
-QString PerforceVersionControl::vcsGetRepositoryURL(const QString &)
-{
- return QString();
-}
-
QString PerforceVersionControl::vcsOpenText() const
{
return tr("&Edit");
diff --git a/src/plugins/perforce/perforceversioncontrol.h b/src/plugins/perforce/perforceversioncontrol.h
index cd6cfcdc6dd..70f9439fda1 100644
--- a/src/plugins/perforce/perforceversioncontrol.h
+++ b/src/plugins/perforce/perforceversioncontrol.h
@@ -59,8 +59,6 @@ public:
bool vcsDelete(const QString &filename);
bool vcsMove(const QString &from, const QString &to);
bool vcsCreateRepository(const QString &directory);
- bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
bool vcsAnnotate(const QString &file, int line);
QString vcsOpenText() const;
QString vcsMakeWritableText() const;
diff --git a/src/plugins/perforce/settingspage.cpp b/src/plugins/perforce/settingspage.cpp
index eaa5b1e3dd7..db0851a7a09 100644
--- a/src/plugins/perforce/settingspage.cpp
+++ b/src/plugins/perforce/settingspage.cpp
@@ -51,7 +51,7 @@ SettingsPageWidget::SettingsPageWidget(QWidget *parent) :
m_ui.pathChooser->setPromptDialogTitle(tr("Perforce Command"));
m_ui.pathChooser->setHistoryCompleter(QLatin1String("Perforce.Command.History"));
m_ui.pathChooser->setExpectedKind(PathChooser::Command);
- connect(m_ui.testPushButton, SIGNAL(clicked()), this, SLOT(slotTest()));
+ connect(m_ui.testPushButton, &QPushButton::clicked, this, &SettingsPageWidget::slotTest);
}
void SettingsPageWidget::slotTest()
diff --git a/src/plugins/projectexplorer/abi.cpp b/src/plugins/projectexplorer/abi.cpp
index bcf2f0c94f4..a84c198840f 100644
--- a/src/plugins/projectexplorer/abi.cpp
+++ b/src/plugins/projectexplorer/abi.cpp
@@ -101,6 +101,8 @@ static Abi macAbiForCpu(quint32 type) {
return Abi(Abi::PowerPCArchitecture, Abi::MacOS, Abi::GenericMacFlavor, Abi::MachOFormat, 32);
case 12: // CPU_TYPE_ARM
return Abi(Abi::ArmArchitecture, Abi::MacOS, Abi::GenericMacFlavor, Abi::MachOFormat, 32);
+ case 0x01000000 + 12: // CPU_TYPE_ARM64
+ return Abi(Abi::ArmArchitecture, Abi::MacOS, Abi::GenericMacFlavor, Abi::MachOFormat, 64);
default:
return Abi();
}
@@ -331,6 +333,9 @@ Abi::Abi(const Architecture &a, const OS &o,
if (m_osFlavor < WindowsMsvc2005Flavor || m_osFlavor > WindowsCEFlavor)
m_osFlavor = UnknownFlavor;
break;
+ case Abi::VxWorks:
+ if (m_osFlavor != VxWorksFlavor)
+ m_osFlavor = VxWorksFlavor;
}
}
@@ -371,8 +376,9 @@ Abi::Abi(const QString &abiString) :
m_os = UnixOS;
else if (abiParts.at(1) == QLatin1String("windows"))
m_os = WindowsOS;
+ else if (abiParts.at(1) == QLatin1String("vxworks"))
+ m_os = VxWorks;
else
-
return;
}
@@ -409,6 +415,8 @@ Abi::Abi(const QString &abiString) :
m_osFlavor = WindowsMSysFlavor;
else if (abiParts.at(2) == QLatin1String("ce") && m_os == WindowsOS)
m_osFlavor = WindowsCEFlavor;
+ else if (abiParts.at(2) == QLatin1String("vxworks") && m_os == VxWorks)
+ m_osFlavor = VxWorksFlavor;
else
return;
}
@@ -469,7 +477,7 @@ Abi Abi::abiFromTargetTriplet(const QString &triple)
arch = Abi::X86Architecture;
} else if (p.startsWith(QLatin1String("arm"))) {
arch = Abi::ArmArchitecture;
- width = 32;
+ width = p.contains(QLatin1String("64")) ? 64 : 32;
} else if (p.startsWith(QLatin1String("mips"))) {
arch = Abi::MipsArchitecture;
width = p.contains(QLatin1String("64")) ? 64 : 32;
@@ -511,6 +519,12 @@ Abi Abi::abiFromTargetTriplet(const QString &triple)
width = 32;
} else if (p == QLatin1String("gnueabi")) {
format = Abi::ElfFormat;
+ } else if (p == QLatin1String("wrs")) {
+ continue;
+ } else if (p == QLatin1String("vxworks")) {
+ os = Abi::VxWorks;
+ flavor = Abi::VxWorksFlavor;
+ format = Abi::ElfFormat;
} else {
++unknownCount;
}
@@ -620,6 +634,8 @@ QString Abi::toString(const OS &o)
return QLatin1String("unix");
case WindowsOS:
return QLatin1String("windows");
+ case VxWorks:
+ return QLatin1String("vxworks");
case UnknownOS: // fall through!
default:
return QLatin1String("unknown");
@@ -659,6 +675,8 @@ QString Abi::toString(const OSFlavor &of)
return QLatin1String("msys");
case Abi::WindowsCEFlavor:
return QLatin1String("ce");
+ case Abi::VxWorksFlavor:
+ return QLatin1String("vxworks");
case Abi::UnknownFlavor: // fall through!
default:
return QLatin1String("unknown");
@@ -705,6 +723,8 @@ QList<Abi::OSFlavor> Abi::flavorsForOs(const Abi::OS &o)
return result << WindowsMsvc2005Flavor << WindowsMsvc2008Flavor << WindowsMsvc2010Flavor
<< WindowsMsvc2012Flavor << WindowsMsvc2013Flavor << WindowsMSysFlavor
<< WindowsCEFlavor << UnknownFlavor;
+ case VxWorks:
+ return result << VxWorksFlavor << UnknownFlavor;
case UnknownOS:
return result << UnknownFlavor;
default:
@@ -1080,6 +1100,10 @@ void ProjectExplorer::ProjectExplorerPlugin::testAbiFromTargetTriplet_data()
QTest::newRow("mips64el-linux-gnuabi") << int(Abi::MipsArchitecture)
<< int(Abi::LinuxOS) << int(Abi::GenericLinuxFlavor)
<< int(Abi::ElfFormat) << 64;
+
+ QTest::newRow("arm-wrs-vxworks") << int(Abi::ArmArchitecture)
+ << int(Abi::VxWorks) << int(Abi::VxWorksFlavor)
+ << int(Abi::ElfFormat) << 32;
}
void ProjectExplorer::ProjectExplorerPlugin::testAbiFromTargetTriplet()
diff --git a/src/plugins/projectexplorer/abi.h b/src/plugins/projectexplorer/abi.h
index a6a5bfa735a..b09016a0442 100644
--- a/src/plugins/projectexplorer/abi.h
+++ b/src/plugins/projectexplorer/abi.h
@@ -62,6 +62,7 @@ public:
MacOS,
UnixOS,
WindowsOS,
+ VxWorks,
UnknownOS
};
@@ -91,6 +92,8 @@ public:
WindowsMSysFlavor,
WindowsCEFlavor,
+ VxWorksFlavor,
+
UnknownFlavor
};
diff --git a/src/plugins/projectexplorer/abstractprocessstep.cpp b/src/plugins/projectexplorer/abstractprocessstep.cpp
index 909d8360af3..a3620fdadbd 100644
--- a/src/plugins/projectexplorer/abstractprocessstep.cpp
+++ b/src/plugins/projectexplorer/abstractprocessstep.cpp
@@ -415,7 +415,7 @@ void AbstractProcessStep::taskAdded(const Task &task)
// 3. give up.
QList<QFileInfo> possibleFiles;
- QString fileName = QFileInfo(filePath).fileName();
+ QString fileName = Utils::FileName::fromString(filePath).fileName();
foreach (const QString &file, project()->files(Project::AllFiles)) {
QFileInfo candidate(file);
if (candidate.fileName() == fileName)
diff --git a/src/plugins/projectexplorer/addnewmodel.cpp b/src/plugins/projectexplorer/addnewmodel.cpp
deleted file mode 100644
index da5a722e6a7..00000000000
--- a/src/plugins/projectexplorer/addnewmodel.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "addnewmodel.h"
-
-#include "projectexplorer.h"
-
-using namespace ProjectExplorer;
-using namespace ProjectExplorer::Internal;
-
-AddNewTree::AddNewTree(const QString &displayName)
- : m_parent(0),
- m_children(QList<AddNewTree *>()),
- m_displayName(displayName),
- m_node(0),
- m_canAdd(true),
- m_priority(-1)
-{
-
-}
-
-AddNewTree::AddNewTree(FolderNode *node, QList<AddNewTree *> children, const QString &displayName)
- : m_parent(0),
- m_children(children),
- m_displayName(displayName),
- m_node(0),
- m_canAdd(false),
- m_priority(-1)
-{
- if (node)
- m_toolTip = ProjectExplorerPlugin::directoryFor(node);
- foreach (AddNewTree *child, m_children)
- child->m_parent = this;
-}
-
-AddNewTree::AddNewTree(FolderNode *node, QList<AddNewTree *> children, const FolderNode::AddNewInformation &info)
- : m_parent(0),
- m_children(children),
- m_displayName(info.displayName),
- m_node(node),
- m_canAdd(true),
- m_priority(info.priority)
-{
- if (node)
- m_toolTip = ProjectExplorerPlugin::directoryFor(node);
- foreach (AddNewTree *child, m_children)
- child->m_parent = this;
-}
-
-AddNewTree::~AddNewTree()
-{
- qDeleteAll(m_children);
-}
-
-AddNewTree *AddNewTree::parent() const
-{
- return m_parent;
-}
-
-QList<AddNewTree *> AddNewTree::children() const
-{
- return m_children;
-}
-
-bool AddNewTree::canAdd() const
-{
- return m_canAdd;
-}
-
-QString AddNewTree::displayName() const
-{
- return m_displayName;
-}
-
-QString AddNewTree::toolTip() const
-{
- return m_toolTip;
-}
-
-FolderNode *AddNewTree::node() const
-{
- return m_node;
-}
-
-int AddNewTree::priority() const
-{
- return m_priority;
-}
-
-AddNewModel::AddNewModel(AddNewTree *root)
- : m_root(root)
-{
-
-}
-
-AddNewModel::~AddNewModel()
-{
- delete m_root;
-}
-
-int AddNewModel::rowCount(const QModelIndex &parent) const
-{
- if (!parent.isValid())
- return m_root->children().size();
- AddNewTree *tree = static_cast<AddNewTree *>(parent.internalPointer());
- return tree->children().size();
-}
-
-int AddNewModel::columnCount(const QModelIndex &parent) const
-{
- Q_UNUSED(parent)
- return 1;
-}
-
-QModelIndex AddNewModel::index(int row, int column, const QModelIndex &parent) const
-{
- if (column != 0)
- return QModelIndex();
- if (!parent.isValid()) {
- if (row >= 0 && row < m_root->children().size())
- return createIndex(row, column, m_root->children().at(row));
- return QModelIndex();
- }
- AddNewTree *tree = static_cast<AddNewTree *>(parent.internalPointer());
- if (row >= 0 && row < tree->children().size())
- return createIndex(row, column, tree->children().at(row));
- return QModelIndex();
-}
-
-QModelIndex AddNewModel::parent(const QModelIndex &child) const
-{
- if (!child.isValid())
- return QModelIndex();
- AddNewTree *childTree = static_cast<AddNewTree *>(child.internalPointer());
- if (childTree == m_root)
- return QModelIndex();
- AddNewTree *parent = childTree->parent();
- if (parent == m_root)
- return QModelIndex();
- AddNewTree *grandparent = parent->parent();
- for (int i = 0; i < grandparent->children().size(); ++i) {
- if (grandparent->children().at(i) == parent)
- return createIndex(i, 0, parent);
- }
- return QModelIndex();
-}
-
-QVariant AddNewModel::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid())
- return QVariant();
- AddNewTree *tree = static_cast<AddNewTree *>(index.internalPointer());
- if (role == Qt::DisplayRole)
- return tree->displayName();
- else if (role == Qt::ToolTipRole)
- return tree->toolTip();
- return QVariant();
-}
-
-Qt::ItemFlags AddNewModel::flags(const QModelIndex &index) const
-{
- AddNewTree *tree = static_cast<AddNewTree *>(index.internalPointer());
- if (tree && tree->canAdd())
- return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
- return Qt::NoItemFlags;
-}
-
-FolderNode *AddNewModel::nodeForIndex(const QModelIndex &index) const
-{
- if (!index.isValid())
- return m_root->node();
- AddNewTree *tree = static_cast<AddNewTree *>(index.internalPointer());
- return tree->node();
-}
-
-QModelIndex AddNewModel::indexForTree(AddNewTree *tree) const
-{
- if (!tree)
- return index(0, 0, QModelIndex());
- AddNewTree *parent = tree->parent();
- if (!parent)
- return QModelIndex();
- for (int i = 0; i < parent->children().size(); ++i)
- if (parent->children().at(i) == tree)
- return createIndex(i, 0, tree);
- return QModelIndex();
-}
diff --git a/src/plugins/projectexplorer/addnewmodel.h b/src/plugins/projectexplorer/addnewmodel.h
deleted file mode 100644
index ee7b42d9380..00000000000
--- a/src/plugins/projectexplorer/addnewmodel.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef ADDNEWMODEL_H
-#define ADDNEWMODEL_H
-
-#include "projectnodes.h"
-
-#include <QAbstractItemModel>
-
-namespace ProjectExplorer {
-class FolderNode;
-
-namespace Internal {
-
-class AddNewTree
-{
-public:
- AddNewTree(const QString &displayName);
- AddNewTree(FolderNode *node, QList<AddNewTree *> children, const QString &displayName);
- AddNewTree(FolderNode *node, QList<AddNewTree *> children, const FolderNode::AddNewInformation &info);
- ~AddNewTree();
-
- AddNewTree *parent() const;
- QList<AddNewTree *> children() const;
-
- bool canAdd() const;
- QString displayName() const;
- QString toolTip() const;
- FolderNode *node() const;
- int priority() const;
-private:
- AddNewTree *m_parent;
- QList<AddNewTree *> m_children;
- QString m_displayName;
- QString m_toolTip;
- FolderNode *m_node;
- bool m_canAdd;
- int m_priority;
-};
-
-class AddNewModel : public QAbstractItemModel
-{
-public:
- AddNewModel(AddNewTree *root);
- ~AddNewModel();
- int rowCount(const QModelIndex &parent) const;
- int columnCount(const QModelIndex &parent) const;
- QModelIndex index(int row, int column, const QModelIndex &parent) const;
- QModelIndex parent(const QModelIndex &child) const;
- QVariant data(const QModelIndex &index, int role) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
-
- FolderNode *nodeForIndex(const QModelIndex &index) const;
- QModelIndex indexForTree(AddNewTree *tree) const;
-private:
- AddNewTree *m_root;
-};
-}
-}
-
-#endif // ADDNEWMODEL_H
diff --git a/src/plugins/projectexplorer/allprojectsfilter.cpp b/src/plugins/projectexplorer/allprojectsfilter.cpp
index 08b0bf6aa6f..a5d6c2c3d8d 100644
--- a/src/plugins/projectexplorer/allprojectsfilter.cpp
+++ b/src/plugins/projectexplorer/allprojectsfilter.cpp
@@ -36,17 +36,17 @@
#include <utils/algorithm.h>
#include <QMutexLocker>
+#include <QTimer>
using namespace Core;
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
-AllProjectsFilter::AllProjectsFilter() : m_filesUpToDate(false)
+AllProjectsFilter::AllProjectsFilter()
{
setId("Files in any project");
setDisplayName(tr("Files in Any Project"));
setShortcutString(QString(QLatin1Char('a')));
- setPriority(Low);
setIncludedByDefault(true);
connect(ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()),
@@ -55,26 +55,24 @@ AllProjectsFilter::AllProjectsFilter() : m_filesUpToDate(false)
void AllProjectsFilter::markFilesAsOutOfDate()
{
- QMutexLocker lock(&m_mutex); Q_UNUSED(lock)
- m_filesUpToDate = false;
+ setFileIterator(0);
}
void AllProjectsFilter::prepareSearch(const QString &entry)
{
Q_UNUSED(entry)
- QMutexLocker lock(&m_mutex); Q_UNUSED(lock)
- if (m_filesUpToDate)
- return;
- files().clear();
- foreach (Project *project, SessionManager::projects())
- files().append(project->files(Project::AllFiles));
- Utils::sort(files());
- generateFileNames();
- m_filesUpToDate = true;
+ if (!fileIterator()) {
+ QStringList paths;
+ foreach (Project *project, SessionManager::projects())
+ paths.append(project->files(Project::AllFiles));
+ Utils::sort(paths);
+ setFileIterator(new BaseFileFilter::ListIterator(paths));
+ }
+ BaseFileFilter::prepareSearch(entry);
}
void AllProjectsFilter::refresh(QFutureInterface<void> &future)
{
Q_UNUSED(future)
- markFilesAsOutOfDate();
+ QTimer::singleShot(0, this, SLOT(markFilesAsOutOfDate()));
}
diff --git a/src/plugins/projectexplorer/allprojectsfilter.h b/src/plugins/projectexplorer/allprojectsfilter.h
index 92799ba937b..6abf051a30a 100644
--- a/src/plugins/projectexplorer/allprojectsfilter.h
+++ b/src/plugins/projectexplorer/allprojectsfilter.h
@@ -33,7 +33,6 @@
#include <coreplugin/locator/basefilefilter.h>
-#include <QMutex>
#include <QFutureInterface>
namespace ProjectExplorer {
@@ -50,10 +49,6 @@ public:
private slots:
void markFilesAsOutOfDate();
-
-private:
- bool m_filesUpToDate;
- QMutex m_mutex;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/allprojectsfind.cpp b/src/plugins/projectexplorer/allprojectsfind.cpp
index 3c4a4c18764..7401b76cf0a 100644
--- a/src/plugins/projectexplorer/allprojectsfind.cpp
+++ b/src/plugins/projectexplorer/allprojectsfind.cpp
@@ -93,7 +93,7 @@ Utils::FileIterator *AllProjectsFind::filesForProjects(const QStringList &nameFi
foreach (const QString &file, projectFiles) {
if (Utils::anyOf(filterRegs,
[&file](QRegExp reg) {
- return (reg.exactMatch(file) || reg.exactMatch(QFileInfo(file).fileName()));
+ return (reg.exactMatch(file) || reg.exactMatch(Utils::FileName::fromString(file).fileName()));
})) {
filteredFiles.append(file);
}
diff --git a/src/plugins/projectexplorer/applicationlauncher.cpp b/src/plugins/projectexplorer/applicationlauncher.cpp
index d083c733e60..64577eb28d9 100644
--- a/src/plugins/projectexplorer/applicationlauncher.cpp
+++ b/src/plugins/projectexplorer/applicationlauncher.cpp
@@ -32,6 +32,9 @@
#ifdef Q_OS_WIN
#include "windebuginterface.h"
#endif
+#ifdef WITH_JOURNALD
+#include "journaldwatcher.h"
+#endif
#include <coreplugin/icore.h>
@@ -125,6 +128,10 @@ ApplicationLauncher::ApplicationLauncher(QObject *parent)
connect(WinDebugInterface::instance(), SIGNAL(debugOutput(qint64,QString)),
this, SLOT(checkDebugOutput(qint64,QString)));
#endif
+#ifdef WITH_JOURNALD
+ connect(JournaldWatcher::instance(), &JournaldWatcher::journaldOutput,
+ this, &ApplicationLauncher::checkDebugOutput);
+#endif
}
ApplicationLauncher::~ApplicationLauncher()
@@ -216,7 +223,7 @@ QString ApplicationLauncher::errorString() const
return d->m_consoleProcess.errorString();
}
-QProcess::ProcessError ApplicationLauncher::error() const
+QProcess::ProcessError ApplicationLauncher::processError() const
{
if (d->m_currentMode == Gui)
return d->m_guiProcess.error();
@@ -277,13 +284,13 @@ void ApplicationLauncher::cannotRetrieveDebugOutput()
disconnect(WinDebugInterface::instance(), 0, this, 0);
emit appendMessage(msgWinCannotRetrieveDebuggingOutput(), Utils::ErrorMessageFormat);
}
+#endif
void ApplicationLauncher::checkDebugOutput(qint64 pid, const QString &message)
{
if (applicationPID() == pid)
emit appendMessage(message, Utils::DebugFormat);
}
-#endif
void ApplicationLauncher::processDone(int exitCode, QProcess::ExitStatus status)
{
diff --git a/src/plugins/projectexplorer/applicationlauncher.h b/src/plugins/projectexplorer/applicationlauncher.h
index 3a5a153265e..f6d1d2f8d56 100644
--- a/src/plugins/projectexplorer/applicationlauncher.h
+++ b/src/plugins/projectexplorer/applicationlauncher.h
@@ -69,7 +69,7 @@ public:
qint64 applicationPID() const;
QString errorString() const;
- QProcess::ProcessError error() const;
+ QProcess::ProcessError processError() const;
static QString msgWinCannotRetrieveDebuggingOutput();
@@ -87,8 +87,8 @@ private slots:
void readStandardError();
#ifdef Q_OS_WIN
void cannotRetrieveDebugOutput();
- void checkDebugOutput(qint64 pid, const QString &message);
#endif
+ void checkDebugOutput(qint64 pid, const QString &message);
void processDone(int, QProcess::ExitStatus);
void bringToForeground();
diff --git a/src/plugins/projectexplorer/appoutputpane.cpp b/src/plugins/projectexplorer/appoutputpane.cpp
index 449d6e010d6..147cc1f4b5c 100644
--- a/src/plugins/projectexplorer/appoutputpane.cpp
+++ b/src/plugins/projectexplorer/appoutputpane.cpp
@@ -33,6 +33,7 @@
#include "projectexplorersettings.h"
#include "runconfiguration.h"
#include "session.h"
+#include "windebuginterface.h"
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/coreconstants.h>
@@ -203,6 +204,11 @@ AppOutputPane::AppOutputPane() :
this, SLOT(aboutToUnloadSession()));
connect(ProjectExplorerPlugin::instance(), SIGNAL(settingsChanged()),
this, SLOT(updateFromSettings()));
+
+#ifdef Q_OS_WIN
+ connect(this, &AppOutputPane::allRunControlsFinished,
+ WinDebugInterface::instance(), &WinDebugInterface::stop);
+#endif
}
AppOutputPane::~AppOutputPane()
diff --git a/src/plugins/projectexplorer/buildmanager.cpp b/src/plugins/projectexplorer/buildmanager.cpp
index 2eb623d1d10..9cff3972d93 100644
--- a/src/plugins/projectexplorer/buildmanager.cpp
+++ b/src/plugins/projectexplorer/buildmanager.cpp
@@ -155,7 +155,7 @@ BuildManager::BuildManager(QObject *parent, QAction *cancelBuildAction)
this, SLOT(finish()));
}
-QObject *BuildManager::instance()
+BuildManager *BuildManager::instance()
{
return m_instance;
}
@@ -278,7 +278,7 @@ void BuildManager::clearBuildQueue()
void BuildManager::toggleOutputWindow()
{
- d->m_outputWindow->toggle(IOutputPane::ModeSwitch);
+ d->m_outputWindow->toggle(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
}
void BuildManager::showTaskWindow()
@@ -288,7 +288,7 @@ void BuildManager::showTaskWindow()
void BuildManager::toggleTaskWindow()
{
- d->m_taskWindow->toggle(IOutputPane::ModeSwitch);
+ d->m_taskWindow->toggle(IOutputPane::ModeSwitch | IOutputPane::WithFocus);
}
bool BuildManager::tasksAvailable()
diff --git a/src/plugins/projectexplorer/buildmanager.h b/src/plugins/projectexplorer/buildmanager.h
index 2ef33e43492..0752fa0f5e0 100644
--- a/src/plugins/projectexplorer/buildmanager.h
+++ b/src/plugins/projectexplorer/buildmanager.h
@@ -49,7 +49,7 @@ class PROJECTEXPLORER_EXPORT BuildManager : public QObject
public:
explicit BuildManager(QObject *parent, QAction *cancelBuildAction);
~BuildManager();
- static QObject *instance();
+ static BuildManager *instance();
static void extensionsInitialized();
diff --git a/src/plugins/projectexplorer/buildprogress.cpp b/src/plugins/projectexplorer/buildprogress.cpp
index 2bead293c36..f96d85b76f4 100644
--- a/src/plugins/projectexplorer/buildprogress.cpp
+++ b/src/plugins/projectexplorer/buildprogress.cpp
@@ -87,8 +87,10 @@ BuildProgress::BuildProgress(TaskWindow *taskWindow, Qt::Orientation orientation
m_errorIcon->setAlignment(Qt::AlignRight);
m_warningIcon->setAlignment(Qt::AlignRight);
- m_errorIcon->setPixmap(QPixmap(QLatin1String(Core::Constants::ICON_ERROR)));
- m_warningIcon->setPixmap(QPixmap(QLatin1String(Core::Constants::ICON_WARNING)));
+ m_errorIcon->setPixmap(QPixmap(Utils::StyleHelper::dpiSpecificImageFile(
+ QLatin1String(Core::Constants::ICON_ERROR))));
+ m_warningIcon->setPixmap(QPixmap(Utils::StyleHelper::dpiSpecificImageFile(
+ QLatin1String(Core::Constants::ICON_WARNING))));
m_contentWidget->hide();
diff --git a/src/plugins/projectexplorer/buildstepspage.cpp b/src/plugins/projectexplorer/buildstepspage.cpp
index cf6750e7621..98b3536a149 100644
--- a/src/plugins/projectexplorer/buildstepspage.cpp
+++ b/src/plugins/projectexplorer/buildstepspage.cpp
@@ -56,13 +56,13 @@ using namespace ProjectExplorer::Internal;
using namespace Utils;
ToolWidget::ToolWidget(QWidget *parent)
- : Utils::FadingPanel(parent), m_buildStepEnabled(true), m_targetOpacity(1.0f)
+ : FadingPanel(parent), m_buildStepEnabled(true), m_targetOpacity(1.0f)
{
QHBoxLayout *layout = new QHBoxLayout;
layout->setMargin(4);
layout->setSpacing(4);
setLayout(layout);
- m_firstWidget = new Utils::FadingWidget(this);
+ m_firstWidget = new FadingWidget(this);
m_firstWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setContentsMargins(0, 0, 0, 0);
@@ -79,7 +79,7 @@ ToolWidget::ToolWidget(QWidget *parent)
hbox->addWidget(m_disableButton);
layout->addWidget(m_firstWidget);
- m_secondWidget = new Utils::FadingWidget(this);
+ m_secondWidget = new FadingWidget(this);
m_secondWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
hbox = new QHBoxLayout();
hbox->setMargin(0);
@@ -179,7 +179,7 @@ BuildStepsWidgetData::BuildStepsWidgetData(BuildStep *s) :
widget = s->createConfigWidget();
Q_ASSERT(widget);
- detailsWidget = new Utils::DetailsWidget;
+ detailsWidget = new DetailsWidget;
detailsWidget->setWidget(widget);
toolWidget = new ToolWidget(detailsWidget);
@@ -278,7 +278,7 @@ void BuildStepListWidget::init(BuildStepList *bsl)
addBuildStep(i);
// addBuilStep expands the config widget by default, which we don't want here
if (m_buildStepsData.at(i)->widget->showWidget())
- m_buildStepsData.at(i)->detailsWidget->setState(Utils::DetailsWidget::Collapsed);
+ m_buildStepsData.at(i)->detailsWidget->setState(DetailsWidget::Collapsed);
}
m_noStepsLabel->setVisible(bsl->isEmpty());
@@ -354,9 +354,9 @@ void BuildStepListWidget::addBuildStep(int pos)
BuildStepsWidgetData *s = m_buildStepsData.at(pos);
// Expand new build steps by default
if (s->widget->showWidget())
- s->detailsWidget->setState(Utils::DetailsWidget::Expanded);
+ s->detailsWidget->setState(DetailsWidget::Expanded);
else
- s->detailsWidget->setState(Utils::DetailsWidget::OnlySummary);
+ s->detailsWidget->setState(DetailsWidget::OnlySummary);
m_noStepsLabel->setVisible(false);
updateBuildStepButtonsState();
diff --git a/src/plugins/projectexplorer/clangparser.cpp b/src/plugins/projectexplorer/clangparser.cpp
index 9746a534c90..f5d359ab101 100644
--- a/src/plugins/projectexplorer/clangparser.cpp
+++ b/src/plugins/projectexplorer/clangparser.cpp
@@ -141,7 +141,7 @@ void ProjectExplorerPlugin::testClangOutputParser_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");
const Core::Id categoryCompile = Constants::TASK_CATEGORY_COMPILE;
@@ -149,19 +149,19 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
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("clang++ warning")
<< QString::fromLatin1("clang++: warning: argument unused during compilation: '-mthreads'")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Warning,
QLatin1String("argument unused during compilation: '-mthreads'"),
Utils::FileName(), -1,
@@ -171,7 +171,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
<< QString::fromLatin1("clang++: error: no input files [err_drv_no_input_files]")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error,
QLatin1String("no input files [err_drv_no_input_files]"),
Utils::FileName(), -1,
@@ -184,7 +184,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
" ^")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Unknown,
QLatin1String("In file included from ..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qnamespace.h:45:"),
Utils::FileName::fromUserInput(QLatin1String("..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qnamespace.h")), 45,
@@ -202,7 +202,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
" ^")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Unknown,
QLatin1String("instantiated from:\n"
"# define Q_CORE_EXPORT Q_DECL_IMPORT\n"
@@ -216,7 +216,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
" ^")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error,
QLatin1String("'bits/c++config.h' file not found\n"
"#include <bits/c++config.h>\n"
@@ -231,7 +231,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Warning,
QLatin1String("?: has lower precedence than +; + will be evaluated first [-Wparentheses]\n"
" int x = option->rect.x() + horizontal ? 2 : 6;\n"
@@ -245,7 +245,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
"CodeSign error: code signing is required for product type 'Application' in SDK 'iOS 7.0'")
<< OutputParserTester::STDERR
<< QString() << QString::fromLatin1("Check dependencies\n")
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error,
QLatin1String("No matching provisioning profiles found: No provisioning profiles with a valid signing identity (i.e. certificate and private key pair) were found."),
Utils::FileName(), -1,
diff --git a/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp b/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
index 63ea5419322..87563cc049e 100644
--- a/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
@@ -46,7 +46,7 @@ CodeStyleSettingsWidget::CodeStyleSettingsWidget(Project *project) : QWidget(),
const EditorConfiguration *config = m_project->editorConfiguration();
QMap<Core::Id, ICodeStylePreferencesFactory *> factories
- = TextEditor::TextEditorSettings::codeStyleFactories();
+ = TextEditorSettings::codeStyleFactories();
QMapIterator<Core::Id, ICodeStylePreferencesFactory *> it(factories);
while (it.hasNext()) {
it.next();
diff --git a/src/plugins/projectexplorer/currentprojectfilter.cpp b/src/plugins/projectexplorer/currentprojectfilter.cpp
index cb0ddef74ba..d2a06cc6d1a 100644
--- a/src/plugins/projectexplorer/currentprojectfilter.cpp
+++ b/src/plugins/projectexplorer/currentprojectfilter.cpp
@@ -29,52 +29,53 @@
****************************************************************************/
#include "currentprojectfilter.h"
-#include "projectexplorer.h"
+#include "projecttree.h"
#include "project.h"
+#include "session.h"
#include <utils/algorithm.h>
#include <QMutexLocker>
+#include <QTimer>
using namespace Core;
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
CurrentProjectFilter::CurrentProjectFilter()
- : BaseFileFilter(), m_project(0), m_filesUpToDate(false)
+ : BaseFileFilter(), m_project(0)
{
setId("Files in current project");
setDisplayName(tr("Files in Current Project"));
- setPriority(Low);
setShortcutString(QString(QLatin1Char('p')));
setIncludedByDefault(false);
- connect(ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
- this, SLOT(currentProjectChanged(ProjectExplorer::Project*)));
+ connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
+ this, &CurrentProjectFilter::currentProjectChanged);
+ connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
+ this, &CurrentProjectFilter::currentProjectChanged);
}
void CurrentProjectFilter::markFilesAsOutOfDate()
{
- QMutexLocker lock(&m_filesUpToDateMutex); Q_UNUSED(lock)
- m_filesUpToDate = false;
+ setFileIterator(0);
}
void CurrentProjectFilter::prepareSearch(const QString &entry)
{
Q_UNUSED(entry)
- QMutexLocker lock(&m_filesUpToDateMutex); Q_UNUSED(lock)
- if (m_filesUpToDate)
- return;
- files().clear();
- m_filesUpToDate = true;
- if (!m_project)
- return;
- files() = m_project->files(Project::AllFiles);
- Utils::sort(files());
- generateFileNames();
+ if (!fileIterator()) {
+ QStringList paths;
+ if (m_project) {
+ paths = m_project->files(Project::AllFiles);
+ Utils::sort(paths);
+ }
+ setFileIterator(new BaseFileFilter::ListIterator(paths));
+ }
+ BaseFileFilter::prepareSearch(entry);
}
-void CurrentProjectFilter::currentProjectChanged(ProjectExplorer::Project *project)
+void CurrentProjectFilter::currentProjectChanged(Project *project)
{
if (project == m_project)
return;
@@ -91,5 +92,5 @@ void CurrentProjectFilter::currentProjectChanged(ProjectExplorer::Project *proje
void CurrentProjectFilter::refresh(QFutureInterface<void> &future)
{
Q_UNUSED(future)
- markFilesAsOutOfDate();
+ QTimer::singleShot(0, this, SLOT(markFilesAsOutOfDate()));
}
diff --git a/src/plugins/projectexplorer/currentprojectfilter.h b/src/plugins/projectexplorer/currentprojectfilter.h
index dde8e874ef6..c903e48b948 100644
--- a/src/plugins/projectexplorer/currentprojectfilter.h
+++ b/src/plugins/projectexplorer/currentprojectfilter.h
@@ -33,8 +33,8 @@
#include <coreplugin/locator/basefilefilter.h>
-#include <QMutex>
#include <QFutureInterface>
+#include <QMutex>
namespace ProjectExplorer {
@@ -57,8 +57,6 @@ private slots:
private:
Project *m_project;
- bool m_filesUpToDate;
- QMutex m_filesUpToDateMutex;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/currentprojectfind.cpp b/src/plugins/projectexplorer/currentprojectfind.cpp
index 8da9a345be2..a40b7965852 100644
--- a/src/plugins/projectexplorer/currentprojectfind.cpp
+++ b/src/plugins/projectexplorer/currentprojectfind.cpp
@@ -30,8 +30,8 @@
#include "currentprojectfind.h"
-#include "projectexplorer.h"
#include "project.h"
+#include "projecttree.h"
#include "session.h"
#include <utils/qtcassert.h>
@@ -46,8 +46,10 @@ using namespace TextEditor;
CurrentProjectFind::CurrentProjectFind()
{
- connect(ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
- this, SLOT(handleProjectChanged()));
+ connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
+ this, &CurrentProjectFind::handleProjectChanged);
+ connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
+ this, &CurrentProjectFind::handleProjectChanged);
connect(SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
this, SLOT(handleProjectChanged()));
connect(SessionManager::instance(), SIGNAL(projectAdded(ProjectExplorer::Project*)),
@@ -66,12 +68,12 @@ QString CurrentProjectFind::displayName() const
bool CurrentProjectFind::isEnabled() const
{
- return ProjectExplorerPlugin::currentProject() != 0 && BaseFileFind::isEnabled();
+ return ProjectTree::currentProject() != 0 && BaseFileFind::isEnabled();
}
QVariant CurrentProjectFind::additionalParameters() const
{
- Project *project = ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
if (project && project->document())
return qVariantFromValue(project->projectFilePath().toString());
return QVariant();
@@ -92,8 +94,8 @@ Utils::FileIterator *CurrentProjectFind::files(const QStringList &nameFilters,
QString CurrentProjectFind::label() const
{
- QTC_ASSERT(ProjectExplorerPlugin::currentProject(), return QString());
- return tr("Project \"%1\":").arg(ProjectExplorerPlugin::currentProject()->displayName());
+ QTC_ASSERT(ProjectTree::currentProject(), return QString());
+ return tr("Project \"%1\":").arg(ProjectTree::currentProject()->displayName());
}
void CurrentProjectFind::handleProjectChanged()
diff --git a/src/plugins/projectexplorer/customparser.cpp b/src/plugins/projectexplorer/customparser.cpp
index 75d167a4171..9eee9ff2ca4 100644
--- a/src/plugins/projectexplorer/customparser.cpp
+++ b/src/plugins/projectexplorer/customparser.cpp
@@ -36,6 +36,7 @@
#include <QString>
+using namespace Utils;
using namespace ProjectExplorer;
CustomParserSettings::CustomParserSettings() :
@@ -138,8 +139,7 @@ bool CustomParser::parseLine(const QString &rawLine)
if (m_errorRegExp.indexIn(rawLine.trimmed()) == -1)
return false;
- const Utils::FileName fileName =
- Utils::FileName::fromUserInput(m_errorRegExp.cap(m_fileNameCap));
+ const FileName fileName = FileName::fromUserInput(m_errorRegExp.cap(m_fileNameCap));
const int lineNumber = m_errorRegExp.cap(m_lineNumberCap).toInt();
const QString message = m_errorRegExp.cap(m_messageCap);
@@ -156,8 +156,6 @@ bool CustomParser::parseLine(const QString &rawLine)
# include "metatypedeclarations.h"
# include "outputparser_test.h"
-using namespace Utils;
-
void ProjectExplorerPlugin::testCustomOutputParsers_data()
{
QTest::addColumn<QString>("input");
@@ -168,12 +166,12 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
QTest::addColumn<int>("messageCap");
QTest::addColumn<QString>("childStdOutLines");
QTest::addColumn<QString>("childStdErrLines");
- QTest::addColumn<QList<ProjectExplorer::Task> >("tasks");
+ QTest::addColumn<QList<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"));
+ const FileName fileName = FileName::fromUserInput(QLatin1String("main.c"));
QTest::newRow("empty pattern")
<< QString::fromLatin1("Sometext")
@@ -181,7 +179,7 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
<< QString::fromLatin1("")
<< 1 << 2 << 3
<< QString::fromLatin1("Sometext\n") << QString()
- << QList<ProjectExplorer::Task>()
+ << QList<Task>()
<< QString();
QTest::newRow("pass-through stdout")
@@ -190,7 +188,7 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
<< simplePattern
<< 1 << 2 << 3
<< QString::fromLatin1("Sometext\n") << QString()
- << QList<ProjectExplorer::Task>()
+ << QList<Task>()
<< QString();
QTest::newRow("pass-through stderr")
@@ -199,7 +197,7 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
<< simplePattern
<< 1 << 2 << 3
<< QString() << QString::fromLatin1("Sometext\n")
- << QList<ProjectExplorer::Task>()
+ << QList<Task>()
<< QString();
const QString simpleError = QLatin1String("main.c:9: error: `sfasdf' undeclared (first use this function)");
@@ -211,7 +209,7 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
<< simplePattern
<< 1 << 2 << 3
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error, message, fileName, 9, categoryCompile)
)
<< QString();
@@ -226,7 +224,7 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
<< simplePattern2
<< 1 << 2 << 3
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error, message, fileName, lineNumber2, categoryCompile)
)
<< QString();
@@ -237,7 +235,7 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
<< simplePattern2
<< 1 << 2 << 3
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error, message, fileName, lineNumber2, categoryCompile)
)
<< QString();
@@ -254,7 +252,7 @@ void ProjectExplorerPlugin::testCustomOutputParsers_data()
<< unitTestPattern
<< 1 << 2 << 3
<< QString() << QString()
- << (QList<ProjectExplorer::Task>()
+ << (QList<Task>()
<< Task(Task::Error, unitTestMessage, unitTestFileName, unitTestLineNumber, categoryCompile)
)
<< QString();
diff --git a/src/plugins/projectexplorer/customtoolchain.cpp b/src/plugins/projectexplorer/customtoolchain.cpp
index 3f4f7a183f6..aa4579672e6 100644
--- a/src/plugins/projectexplorer/customtoolchain.cpp
+++ b/src/plugins/projectexplorer/customtoolchain.cpp
@@ -177,7 +177,7 @@ void CustomToolChain::setPredefinedMacros(const QStringList &list)
m_predefinedMacros = list;
}
-QList<HeaderPath> CustomToolChain::systemHeaderPaths(const QStringList &cxxFlags, const Utils::FileName &) const
+QList<HeaderPath> CustomToolChain::systemHeaderPaths(const QStringList &cxxFlags, const FileName &) const
{
QList<HeaderPath> flagHeaderPaths;
foreach (const QString &cxxFlag, cxxFlags) {
@@ -251,7 +251,7 @@ void CustomToolChain::setMakeCommand(const FileName &path)
toolChainUpdated();
}
-QString CustomToolChain::makeCommand(const Utils::Environment &) const
+QString CustomToolChain::makeCommand(const Environment &) const
{
return m_makeCommand.toString();
}
@@ -272,7 +272,7 @@ const QStringList &CustomToolChain::cxx11Flags() const
void CustomToolChain::setMkspecs(const QString &specs)
{
m_mkspecs = Utils::transform(specs.split(QLatin1Char(',')),
- [](QString fn) { return Utils::FileName::fromString(fn); });
+ [](QString fn) { return FileName::fromString(fn); });
}
QString CustomToolChain::mkspecs() const
@@ -585,7 +585,7 @@ void CustomToolChainConfigWidget::setFromToolchain()
bool blocked = blockSignals(true);
CustomToolChain *tc = static_cast<CustomToolChain *>(toolChain());
m_compilerCommand->setFileName(tc->compilerCommand());
- m_makeCommand->setFileName(FileName::fromString(tc->makeCommand(Utils::Environment())));
+ m_makeCommand->setFileName(FileName::fromString(tc->makeCommand(Environment())));
m_abiWidget->setAbis(QList<Abi>(), tc->targetAbi());
m_predefinedMacros->setPlainText(tc->rawPredefinedMacros().join(QLatin1Char('\n')));
m_headerPaths->setPlainText(tc->headerPathsList().join(QLatin1Char('\n')));
@@ -601,7 +601,7 @@ bool CustomToolChainConfigWidget::isDirtyImpl() const
CustomToolChain *tc = static_cast<CustomToolChain *>(toolChain());
Q_ASSERT(tc);
return m_compilerCommand->fileName() != tc->compilerCommand()
- || m_makeCommand->path() != tc->makeCommand(Utils::Environment())
+ || m_makeCommand->path() != tc->makeCommand(Environment())
|| m_abiWidget->currentAbi() != tc->targetAbi()
|| m_predefinedDetails->entries() != tc->rawPredefinedMacros()
|| m_headerDetails->entries() != tc->headerPathsList()
diff --git a/src/plugins/projectexplorer/deployablefile.cpp b/src/plugins/projectexplorer/deployablefile.cpp
index bbf75c82818..8eede6aed5c 100644
--- a/src/plugins/projectexplorer/deployablefile.cpp
+++ b/src/plugins/projectexplorer/deployablefile.cpp
@@ -30,7 +30,8 @@
#include "deployablefile.h"
-#include <QFileInfo>
+#include <utils/fileutils.h>
+
#include <QHash>
using namespace Utils;
@@ -55,7 +56,7 @@ DeployableFile::DeployableFile(const FileName &localFilePath, const QString &rem
QString DeployableFile::remoteFilePath() const
{
return m_remoteDir.isEmpty()
- ? QString() : m_remoteDir + QLatin1Char('/') + m_localFilePath.toFileInfo().fileName();
+ ? QString() : m_remoteDir + QLatin1Char('/') + m_localFilePath.fileName();
}
bool DeployableFile::isValid() const
diff --git a/src/plugins/projectexplorer/deployconfiguration.cpp b/src/plugins/projectexplorer/deployconfiguration.cpp
index 854f719b9e0..c5c8c115c6c 100644
--- a/src/plugins/projectexplorer/deployconfiguration.cpp
+++ b/src/plugins/projectexplorer/deployconfiguration.cpp
@@ -182,14 +182,42 @@ DeployConfigurationFactory::DeployConfigurationFactory(QObject *parent) :
DeployConfigurationFactory::~DeployConfigurationFactory()
{ }
-QList<Core::Id> DeployConfigurationFactory::availableCreationIds(Target *parent) const
+DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, const QVariantMap &map)
+{
+ return ExtensionSystem::PluginManager::getObject<DeployConfigurationFactory>(
+ [&parent, &map](DeployConfigurationFactory *factory) {
+ return factory->canRestore(parent, map);
+ });
+}
+
+QList<DeployConfigurationFactory *> DeployConfigurationFactory::find(Target *parent)
+{
+ return ExtensionSystem::PluginManager::getObjects<DeployConfigurationFactory>(
+ [&parent](DeployConfigurationFactory *factory) {
+ return !factory->availableCreationIds(parent).isEmpty();
+ });
+}
+
+DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, DeployConfiguration *dc)
+{
+ return ExtensionSystem::PluginManager::getObject<DeployConfigurationFactory>(
+ [&parent, &dc](DeployConfigurationFactory *factory) {
+ return factory->canClone(parent, dc);
+ });
+}
+
+///
+// DefaultDeployConfigurationFactory
+///
+
+QList<Core::Id> DefaultDeployConfigurationFactory::availableCreationIds(Target *parent) const
{
if (!canHandle(parent))
return QList<Core::Id>();
return QList<Core::Id>() << Core::Id(Constants::DEFAULT_DEPLOYCONFIGURATION_ID);
}
-QString DeployConfigurationFactory::displayNameForId(Core::Id id) const
+QString DefaultDeployConfigurationFactory::displayNameForId(Core::Id id) const
{
if (id == Constants::DEFAULT_DEPLOYCONFIGURATION_ID)
//: Display name of the default deploy configuration
@@ -197,26 +225,26 @@ QString DeployConfigurationFactory::displayNameForId(Core::Id id) const
return QString();
}
-bool DeployConfigurationFactory::canCreate(Target *parent, Core::Id id) const
+bool DefaultDeployConfigurationFactory::canCreate(Target *parent, Core::Id id) const
{
if (!canHandle(parent))
return false;
return id == Constants::DEFAULT_DEPLOYCONFIGURATION_ID;
}
-DeployConfiguration *DeployConfigurationFactory::create(Target *parent, Core::Id id)
+DeployConfiguration *DefaultDeployConfigurationFactory::create(Target *parent, Core::Id id)
{
if (!canCreate(parent, id))
return 0;
return new DefaultDeployConfiguration(parent, id);
}
-bool DeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
+bool DefaultDeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
{
return canCreate(parent, idFromMap(map));
}
-DeployConfiguration *DeployConfigurationFactory::restore(Target *parent, const QVariantMap &map)
+DeployConfiguration *DefaultDeployConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
if (!canRestore(parent, map))
return 0;
@@ -228,43 +256,19 @@ DeployConfiguration *DeployConfigurationFactory::restore(Target *parent, const Q
return dc;
}
-bool DeployConfigurationFactory::canClone(Target *parent, DeployConfiguration *product) const
+bool DefaultDeployConfigurationFactory::canClone(Target *parent, DeployConfiguration *product) const
{
return canCreate(parent, product->id());
}
-DeployConfiguration *DeployConfigurationFactory::clone(Target *parent, DeployConfiguration *product)
+DeployConfiguration *DefaultDeployConfigurationFactory::clone(Target *parent, DeployConfiguration *product)
{
if (!canClone(parent, product))
return 0;
return new DefaultDeployConfiguration(parent, product);
}
-DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, const QVariantMap &map)
-{
- return ExtensionSystem::PluginManager::getObject<DeployConfigurationFactory>(
- [&parent, &map](DeployConfigurationFactory *factory) {
- return factory->canRestore(parent, map);
- });
-}
-
-QList<DeployConfigurationFactory *> DeployConfigurationFactory::find(Target *parent)
-{
- return ExtensionSystem::PluginManager::getObjects<DeployConfigurationFactory>(
- [&parent](DeployConfigurationFactory *factory) {
- return !factory->availableCreationIds(parent).isEmpty();
- });
-}
-
-DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, DeployConfiguration *dc)
-{
- return ExtensionSystem::PluginManager::getObject<DeployConfigurationFactory>(
- [&parent, &dc](DeployConfigurationFactory *factory) {
- return factory->canClone(parent, dc);
- });
-}
-
-bool DeployConfigurationFactory::canHandle(Target *parent) const
+bool DefaultDeployConfigurationFactory::canHandle(Target *parent) const
{
if (!parent->project()->supportsKit(parent->kit()) || parent->project()->needsSpecialDeployment())
return false;
diff --git a/src/plugins/projectexplorer/deployconfiguration.h b/src/plugins/projectexplorer/deployconfiguration.h
index de232d1ec78..bf997d06520 100644
--- a/src/plugins/projectexplorer/deployconfiguration.h
+++ b/src/plugins/projectexplorer/deployconfiguration.h
@@ -84,7 +84,7 @@ private:
class PROJECTEXPLORER_EXPORT DefaultDeployConfiguration : public DeployConfiguration
{
Q_OBJECT
- friend class DeployConfigurationFactory; // for the ctors
+ friend class DefaultDeployConfigurationFactory; // for the ctors
protected:
DefaultDeployConfiguration(Target *target, Core::Id id);
DefaultDeployConfiguration(Target *target, DeployConfiguration *source);
@@ -100,17 +100,17 @@ public:
virtual ~DeployConfigurationFactory();
// used to show the list of possible additons to a target, returns a list of types
- virtual QList<Core::Id> availableCreationIds(Target *parent) const;
+ virtual QList<Core::Id> availableCreationIds(Target *parent) const = 0;
// used to translate the types to names to display to the user
- virtual QString displayNameForId(Core::Id id) const;
+ virtual QString displayNameForId(Core::Id id) const = 0;
- virtual bool canCreate(Target *parent, Core::Id id) const;
- virtual DeployConfiguration *create(Target *parent, Core::Id id);
+ virtual bool canCreate(Target *parent, Core::Id id) const = 0;
+ virtual DeployConfiguration *create(Target *parent, Core::Id id) = 0;
// used to recreate the runConfigurations when restoring settings
- virtual bool canRestore(Target *parent, const QVariantMap &map) const;
- virtual DeployConfiguration *restore(Target *parent, const QVariantMap &map);
- virtual bool canClone(Target *parent, DeployConfiguration *product) const;
- virtual DeployConfiguration *clone(Target *parent, DeployConfiguration *product);
+ virtual bool canRestore(Target *parent, const QVariantMap &map) const = 0;
+ virtual DeployConfiguration *restore(Target *parent, const QVariantMap &map) = 0;
+ virtual bool canClone(Target *parent, DeployConfiguration *product) const = 0;
+ virtual DeployConfiguration *clone(Target *parent, DeployConfiguration *product) = 0;
static DeployConfigurationFactory *find(Target *parent, const QVariantMap &map);
static QList<DeployConfigurationFactory *> find(Target *parent);
@@ -118,11 +118,22 @@ public:
signals:
void availableCreationIdsChanged();
+};
-protected:
- virtual bool canHandle(Target *parent) const;
-
+class DefaultDeployConfigurationFactory : public DeployConfigurationFactory
+{
+public:
+ QList<Core::Id> availableCreationIds(Target *parent) const;
+ // used to translate the types to names to display to the user
+ QString displayNameForId(Core::Id id) const;
+ bool canCreate(Target *parent, Core::Id id) const;
+ DeployConfiguration *create(Target *parent, Core::Id id);
+ bool canRestore(Target *parent, const QVariantMap &map) const;
+ DeployConfiguration *restore(Target *parent, const QVariantMap &map);
+ bool canClone(Target *parent, DeployConfiguration *product) const;
+ DeployConfiguration *clone(Target *parent, DeployConfiguration *product);
private:
+ bool canHandle(Target *parent) const;
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/deploymentdata.h b/src/plugins/projectexplorer/deploymentdata.h
index c658e634ddd..deb377393db 100644
--- a/src/plugins/projectexplorer/deploymentdata.h
+++ b/src/plugins/projectexplorer/deploymentdata.h
@@ -47,8 +47,13 @@ public:
void addFile(const DeployableFile &file)
{
- if (!m_files.contains(file))
- m_files << file;
+ for (int i = 0; i < m_files.size(); ++i) {
+ if (m_files.at(i).localFilePath() == file.localFilePath()) {
+ m_files[i] = file;
+ return;
+ }
+ }
+ m_files << file;
}
void addFile(const QString &localFilePath, const QString &remoteDirectory,
diff --git a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
index 375bdb6eeaf..14b300f3f1c 100644
--- a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
@@ -32,9 +32,11 @@
#include "idevicefactory.h"
#include <coreplugin/icore.h>
+#include <coreplugin/messagemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <ssh/sshhostkeydatabase.h>
#include <utils/qtcassert.h>
#include <utils/fileutils.h>
#include <utils/persistentsettings.h>
@@ -75,6 +77,7 @@ public:
static DeviceManager *clonedInstance;
QList<IDevice::Ptr> devices;
QHash<Core::Id, Core::Id> defaultDevices;
+ QSsh::SshHostKeyDatabasePtr hostKeyDatabase;
Utils::PersistentSettingsWriter *writer;
};
@@ -136,6 +139,7 @@ void DeviceManager::save()
QVariantMap data;
data.insert(QLatin1String(DeviceManagerKey), toMap());
d->writer->save(data, Core::ICore::mainWindow());
+ d->hostKeyDatabase->store(hostKeysFilePath());
}
void DeviceManager::load()
@@ -308,6 +312,11 @@ bool DeviceManager::isLoaded() const
return d->writer;
}
+QSsh::SshHostKeyDatabasePtr DeviceManager::hostKeyDatabase() const
+{
+ return d->hostKeyDatabase;
+}
+
void DeviceManager::setDefaultDevice(Core::Id id)
{
QTC_ASSERT(this != instance(), return);
@@ -343,6 +352,13 @@ DeviceManager::DeviceManager(bool isInstance) : d(new DeviceManagerPrivate)
if (isInstance) {
QTC_ASSERT(!m_instance, return);
m_instance = this;
+ d->hostKeyDatabase = QSsh::SshHostKeyDatabasePtr::create();
+ const QString keyFilePath = hostKeysFilePath();
+ if (QFileInfo(keyFilePath).exists()) {
+ QString error;
+ if (!d->hostKeyDatabase->load(keyFilePath, &error))
+ Core::MessageManager::write(error);
+ }
connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), SLOT(save()));
}
}
@@ -415,6 +431,11 @@ IDevice::ConstPtr DeviceManager::fromRawPointer(const IDevice *device) const
return fromRawPointer(const_cast<IDevice *>(device));
}
+QString DeviceManager::hostKeysFilePath()
+{
+ return settingsFilePath(QLatin1String("/ssh-hostkeys")).toString();
+}
+
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/devicesupport/devicemanager.h b/src/plugins/projectexplorer/devicesupport/devicemanager.h
index aa85bdae36f..21c7293ccbb 100644
--- a/src/plugins/projectexplorer/devicesupport/devicemanager.h
+++ b/src/plugins/projectexplorer/devicesupport/devicemanager.h
@@ -36,6 +36,7 @@
#include <QObject>
+namespace QSsh { class SshHostKeyDatabase; }
namespace Utils { class FileName; }
namespace ProjectExplorer {
@@ -105,6 +106,8 @@ private:
IDevice::Ptr fromRawPointer(IDevice *device) const;
IDevice::ConstPtr fromRawPointer(const IDevice *device) const;
+ static QString hostKeysFilePath();
+ QSharedPointer<QSsh::SshHostKeyDatabase> hostKeyDatabase() const;
static Utils::FileName settingsFilePath(const QString &extension);
static Utils::FileName systemSettingsFilePath(const QString &deviceFileRelativePath);
static void copy(const DeviceManager *source, DeviceManager *target, bool deep);
diff --git a/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp b/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp
index 14d281a13ef..fbb01fb4c13 100644
--- a/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp
+++ b/src/plugins/projectexplorer/devicesupport/deviceprocessesdialog.cpp
@@ -114,7 +114,7 @@ public:
QLabel *kitLabel;
KitChooser *kitChooser;
- Utils::TreeView *procView;
+ TreeView *procView;
QTextBrowser *errorText;
FancyLineEdit *processFilterLineEdit;
QPushButton *updateListButton;
@@ -144,7 +144,7 @@ DeviceProcessesDialogPrivate::DeviceProcessesDialogPrivate(KitChooser *chooser,
kitChooser->populate();
- procView = new Utils::TreeView(q);
+ procView = new TreeView(q);
procView->setModel(&proxyModel);
procView->setSelectionBehavior(QAbstractItemView::SelectRows);
procView->setSelectionMode(QAbstractItemView::SingleSelection);
@@ -155,7 +155,7 @@ DeviceProcessesDialogPrivate::DeviceProcessesDialogPrivate(KitChooser *chooser,
procView->header()->setDefaultSectionSize(100);
procView->header()->setStretchLastSection(true);
procView->sortByColumn(1, Qt::AscendingOrder);
- procView->setActivationMode(Utils::DoubleClickActivation);
+ procView->setActivationMode(DoubleClickActivation);
errorText = new QTextBrowser(q);
diff --git a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp
index 4ae3011c4c2..3e125ecacb6 100644
--- a/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicesettingswidget.cpp
@@ -124,7 +124,7 @@ void DeviceSettingsWidget::initGui()
m_ui->addConfigButton->setEnabled(hasDeviceFactories);
- int lastIndex = Core::ICore::settings()
+ int lastIndex = ICore::settings()
->value(QLatin1String(LastDeviceIndexKey), 0).toInt();
if (lastIndex == -1)
lastIndex = 0;
@@ -143,7 +143,7 @@ void DeviceSettingsWidget::addDevice()
if (d.exec() != QDialog::Accepted)
return;
- Core::Id toCreate = d.selectedId();
+ Id toCreate = d.selectedId();
if (!toCreate.isValid())
return;
IDeviceFactory *factory = IDeviceFactory::find(toCreate);
@@ -221,7 +221,7 @@ void DeviceSettingsWidget::updateDeviceFromUi()
void DeviceSettingsWidget::saveSettings()
{
- Core::ICore::settings()->setValue(QLatin1String(LastDeviceIndexKey), currentIndex());
+ ICore::settings()->setValue(QLatin1String(LastDeviceIndexKey), currentIndex());
DeviceManager::replaceInstance();
}
@@ -299,7 +299,7 @@ void DeviceSettingsWidget::currentDeviceChanged(int index)
m_ui->buttonsLayout->insertWidget(m_ui->buttonsLayout->count() - 1, button);
}
- foreach (Core::Id actionId, device->actionIds()) {
+ foreach (Id actionId, device->actionIds()) {
QPushButton * const button = new QPushButton(device->displayNameForActionId(actionId));
m_additionalActionButtons << button;
connect(button, SIGNAL(clicked()), m_additionalActionsMapper, SLOT(map()));
@@ -327,7 +327,7 @@ void DeviceSettingsWidget::handleAdditionalActionRequest(int actionId)
const IDevice::Ptr device = m_deviceManager->mutableDevice(currentDevice()->id());
QTC_ASSERT(device, return);
updateDeviceFromUi();
- device->executeAction(Core::Id::fromUniqueIdentifier(actionId), this);
+ device->executeAction(Id::fromUniqueIdentifier(actionId), this);
// Widget must be set up from scratch, because the action could have changed random attributes.
currentDeviceChanged(currentIndex());
diff --git a/src/plugins/projectexplorer/devicesupport/idevice.cpp b/src/plugins/projectexplorer/devicesupport/idevice.cpp
index b2bbbe81a2e..83eb457f1d7 100644
--- a/src/plugins/projectexplorer/devicesupport/idevice.cpp
+++ b/src/plugins/projectexplorer/devicesupport/idevice.cpp
@@ -123,6 +123,7 @@ const char AuthKey[] = "Authentication";
const char KeyFileKey[] = "KeyFile";
const char PasswordKey[] = "Password";
const char TimeoutKey[] = "Timeout";
+const char HostKeyCheckingKey[] = "HostKeyChecking";
const char DebugServerKey[] = "DebugServerKey";
@@ -161,7 +162,9 @@ PortsGatheringMethod::~PortsGatheringMethod() { }
DeviceTester::DeviceTester(QObject *parent) : QObject(parent) { }
IDevice::IDevice() : d(new Internal::IDevicePrivate)
-{ }
+{
+ d->sshParameters.hostKeyDatabase = DeviceManager::instance()->hostKeyDatabase();
+}
IDevice::IDevice(Core::Id type, Origin origin, MachineType machineType, Core::Id id)
: d(new Internal::IDevicePrivate)
@@ -171,6 +174,7 @@ IDevice::IDevice(Core::Id type, Origin origin, MachineType machineType, Core::Id
d->machineType = machineType;
QTC_CHECK(origin == ManuallyAdded || id.isValid());
d->id = id.isValid() ? id : newId();
+ d->sshParameters.hostKeyDatabase = DeviceManager::instance()->hostKeyDatabase();
}
IDevice::IDevice(const IDevice &other) : d(new Internal::IDevicePrivate)
@@ -322,6 +326,8 @@ void IDevice::fromMap(const QVariantMap &map)
d->sshParameters.password = map.value(QLatin1String(PasswordKey)).toString();
d->sshParameters.privateKeyFile = map.value(QLatin1String(KeyFileKey), defaultPrivateKeyFilePath()).toString();
d->sshParameters.timeout = map.value(QLatin1String(TimeoutKey), DefaultTimeout).toInt();
+ d->sshParameters.hostKeyCheckingMode = static_cast<QSsh::SshHostKeyCheckingMode>
+ (map.value(QLatin1String(HostKeyCheckingKey), QSsh::SshHostKeyCheckingNone).toInt());
d->freePorts = Utils::PortList::fromString(map.value(QLatin1String(PortsSpecKey),
QLatin1String("10000-10100")).toString());
@@ -353,6 +359,7 @@ QVariantMap IDevice::toMap() const
map.insert(QLatin1String(PasswordKey), d->sshParameters.password);
map.insert(QLatin1String(KeyFileKey), d->sshParameters.privateKeyFile);
map.insert(QLatin1String(TimeoutKey), d->sshParameters.timeout);
+ map.insert(QLatin1String(HostKeyCheckingKey), d->sshParameters.hostKeyCheckingMode);
map.insert(QLatin1String(PortsSpecKey), d->freePorts.toString());
map.insert(QLatin1String(VersionKey), d->version);
@@ -392,6 +399,7 @@ QSsh::SshConnectionParameters IDevice::sshParameters() const
void IDevice::setSshParameters(const QSsh::SshConnectionParameters &sshParameters)
{
d->sshParameters = sshParameters;
+ d->sshParameters.hostKeyDatabase = DeviceManager::instance()->hostKeyDatabase();
}
QString IDevice::qmlProfilerHost() const
diff --git a/src/plugins/projectexplorer/doubletabwidget.cpp b/src/plugins/projectexplorer/doubletabwidget.cpp
index 7ee2ede2aad..55817378855 100644
--- a/src/plugins/projectexplorer/doubletabwidget.cpp
+++ b/src/plugins/projectexplorer/doubletabwidget.cpp
@@ -51,7 +51,7 @@ static const int MARGIN = 12;
static const int OTHER_HEIGHT = 38;
static const int SELECTION_IMAGE_WIDTH = 10;
static const int SELECTION_IMAGE_HEIGHT = 20;
-static const int OVERFLOW_DROPDOWN_WIDTH = Utils::StyleHelper::navigationWidgetHeight();
+static const int OVERFLOW_DROPDOWN_WIDTH = StyleHelper::navigationWidgetHeight();
static void drawFirstLevelSeparator(QPainter *painter, QPoint top, QPoint bottom)
{
@@ -170,7 +170,7 @@ void DoubleTabWidget::setTitle(const QString &title)
QSize DoubleTabWidget::minimumSizeHint() const
{
- return QSize(0, Utils::StyleHelper::navigationWidgetHeight() + OTHER_HEIGHT + 1);
+ return QSize(0, StyleHelper::navigationWidgetHeight() + OTHER_HEIGHT + 1);
}
void DoubleTabWidget::updateNameIsUniqueAdd(Tab *tab)
@@ -258,7 +258,7 @@ int DoubleTabWidget::tabCount() const
/// is the tab or subtab number
QPair<DoubleTabWidget::HitArea, int> DoubleTabWidget::convertPosToTab(QPoint pos)
{
- if (pos.y() < Utils::StyleHelper::navigationWidgetHeight()) {
+ if (pos.y() < StyleHelper::navigationWidgetHeight()) {
// on the top level part of the bar
int eventX = pos.x();
QFontMetrics fm(font());
@@ -282,10 +282,10 @@ QPair<DoubleTabWidget::HitArea, int> DoubleTabWidget::convertPosToTab(QPoint pos
if (eventX > x && eventX < x + OVERFLOW_DROPDOWN_WIDTH)
return qMakePair(HITOVERFLOW, -1);
}
- } else if (pos.y() < Utils::StyleHelper::navigationWidgetHeight() + OTHER_HEIGHT) {
+ } else if (pos.y() < StyleHelper::navigationWidgetHeight() + OTHER_HEIGHT) {
int diff = (OTHER_HEIGHT - SELECTION_IMAGE_HEIGHT) / 2;
- if (pos.y() < Utils::StyleHelper::navigationWidgetHeight() + diff
- || pos.y() > Utils::StyleHelper::navigationWidgetHeight() + OTHER_HEIGHT - diff)
+ if (pos.y() < StyleHelper::navigationWidgetHeight() + diff
+ || pos.y() > StyleHelper::navigationWidgetHeight() + OTHER_HEIGHT - diff)
return qMakePair(HITNOTHING, -1);
// on the lower level part of the bar
if (m_currentIndex == -1)
@@ -363,13 +363,13 @@ void DoubleTabWidget::paintEvent(QPaintEvent *event)
QRect r = rect();
// draw top level tab bar
- r.setHeight(Utils::StyleHelper::navigationWidgetHeight());
+ r.setHeight(StyleHelper::navigationWidgetHeight());
if (creatorTheme()->widgetStyle () == Theme::StyleDefault) {
QPoint offset = window()->mapToGlobal(QPoint(0, 0)) - mapToGlobal(r.topLeft());
QRect gradientSpan = QRect(offset, window()->size());
- Utils::StyleHelper::horizontalGradient(&painter, gradientSpan, r);
- painter.setPen(Utils::StyleHelper::borderColor());
+ StyleHelper::horizontalGradient(&painter, gradientSpan, r);
+ painter.setPen(StyleHelper::borderColor());
QColor lighter(255, 255, 255, 40);
painter.drawLine(r.bottomLeft(), r.bottomRight());
painter.setPen(lighter);
@@ -383,7 +383,7 @@ void DoubleTabWidget::paintEvent(QPaintEvent *event)
// top level title
if (!m_title.isEmpty()) {
- painter.setPen(Utils::StyleHelper::panelTextColor());
+ painter.setPen(StyleHelper::panelTextColor());
painter.drawText(MARGIN, baseline, m_title);
}
@@ -478,7 +478,7 @@ void DoubleTabWidget::paintEvent(QPaintEvent *event)
int actualIndex = m_currentTabIndices.at(i);
Tab tab = m_tabs.at(actualIndex);
if (actualIndex == m_currentIndex) {
- painter.setPen(Utils::StyleHelper::borderColor());
+ painter.setPen(StyleHelper::borderColor());
painter.drawLine(x - 1, 0, x - 1, r.height() - 1);
painter.fillRect(QRect(x, 0,
2 * MARGIN + fm.width(tab.displayName()),
@@ -495,7 +495,7 @@ void DoubleTabWidget::paintEvent(QPaintEvent *event)
x += nameWidth.at(actualIndex);
x += MARGIN;
if (creatorTheme()->widgetStyle() == Theme::StyleDefault) {
- painter.setPen(Utils::StyleHelper::borderColor());
+ painter.setPen(StyleHelper::borderColor());
painter.drawLine(x, 0, x, r.height() - 1);
painter.setPen(QColor(0, 0, 0, 20));
painter.drawLine(x + 1, 0, x + 1, r.height() - 1);
diff --git a/src/plugins/projectexplorer/editorconfiguration.cpp b/src/plugins/projectexplorer/editorconfiguration.cpp
index dc73902aaa9..dded5d867a9 100644
--- a/src/plugins/projectexplorer/editorconfiguration.cpp
+++ b/src/plugins/projectexplorer/editorconfiguration.cpp
@@ -281,7 +281,7 @@ void EditorConfiguration::setUseGlobalSettings(bool use)
d->m_defaultCodeStyle->setCurrentDelegate(use ? TextEditorSettings::codeStyle() : 0);
foreach (Core::IEditor *editor, Core::DocumentModel::editorsForOpenedDocuments()) {
if (TextEditorWidget *widget = qobject_cast<TextEditorWidget *>(editor->widget())) {
- Project *project = SessionManager::projectForFile(editor->document()->filePath());
+ Project *project = SessionManager::projectForFile(editor->document()->filePath().toString());
if (project && project->editorConfiguration() == this)
switchSettings(widget);
}
@@ -333,25 +333,25 @@ void EditorConfiguration::switchSettings(TextEditorWidget *widget) const
}
}
-void EditorConfiguration::setTypingSettings(const TextEditor::TypingSettings &settings)
+void EditorConfiguration::setTypingSettings(const TypingSettings &settings)
{
d->m_typingSettings = settings;
emit typingSettingsChanged(d->m_typingSettings);
}
-void EditorConfiguration::setStorageSettings(const TextEditor::StorageSettings &settings)
+void EditorConfiguration::setStorageSettings(const StorageSettings &settings)
{
d->m_storageSettings = settings;
emit storageSettingsChanged(d->m_storageSettings);
}
-void EditorConfiguration::setBehaviorSettings(const TextEditor::BehaviorSettings &settings)
+void EditorConfiguration::setBehaviorSettings(const BehaviorSettings &settings)
{
d->m_behaviorSettings = settings;
emit behaviorSettingsChanged(d->m_behaviorSettings);
}
-void EditorConfiguration::setExtraEncodingSettings(const TextEditor::ExtraEncodingSettings &settings)
+void EditorConfiguration::setExtraEncodingSettings(const ExtraEncodingSettings &settings)
{
d->m_extraEncodingSettings = settings;
emit extraEncodingSettingsChanged(d->m_extraEncodingSettings);
@@ -391,7 +391,7 @@ void EditorConfiguration::slotAboutToRemoveProject(Project *project)
if (project->editorConfiguration() != this)
return;
- foreach (TextEditor::BaseTextEditor *editor, d->m_editors)
+ foreach (BaseTextEditor *editor, d->m_editors)
deconfigureEditor(editor);
}
diff --git a/src/plugins/projectexplorer/foldernavigationwidget.cpp b/src/plugins/projectexplorer/foldernavigationwidget.cpp
index 4558b04dcb9..d6f3a39ad6b 100644
--- a/src/plugins/projectexplorer/foldernavigationwidget.cpp
+++ b/src/plugins/projectexplorer/foldernavigationwidget.cpp
@@ -38,6 +38,7 @@
#include <coreplugin/fileiconprovider.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/fileutils.h>
#include <coreplugin/find/findplugin.h>
@@ -199,17 +200,21 @@ void FolderNavigationWidget::setAutoSynchronization(bool sync)
m_autoSync = sync;
if (m_autoSync) {
- connect(Core::DocumentManager::instance(), SIGNAL(currentFileChanged(QString)),
- this, SLOT(setCurrentFile(QString)));
- setCurrentFile(Core::DocumentManager::currentFile());
+ connect(Core::EditorManager::instance(), &Core::EditorManager::currentEditorChanged,
+ this, &FolderNavigationWidget::setCurrentFile);
+ setCurrentFile(Core::EditorManager::currentEditor());
} else {
- disconnect(Core::DocumentManager::instance(), SIGNAL(currentFileChanged(QString)),
- this, SLOT(setCurrentFile(QString)));
+ disconnect(Core::EditorManager::instance(), &Core::EditorManager::currentEditorChanged,
+ this, &FolderNavigationWidget::setCurrentFile);
}
}
-void FolderNavigationWidget::setCurrentFile(const QString &filePath)
+void FolderNavigationWidget::setCurrentFile(Core::IEditor *editor)
{
+ if (!editor)
+ return;
+
+ const QString filePath = editor->document()->filePath().toString();
// Try to find directory of current file
bool pathOpened = false;
if (!filePath.isEmpty()) {
diff --git a/src/plugins/projectexplorer/foldernavigationwidget.h b/src/plugins/projectexplorer/foldernavigationwidget.h
index c6c5ca68d14..feded0c86b8 100644
--- a/src/plugins/projectexplorer/foldernavigationwidget.h
+++ b/src/plugins/projectexplorer/foldernavigationwidget.h
@@ -36,22 +36,17 @@
#include <QWidget>
namespace Utils { class ListView; }
+namespace Core { class IEditor; }
QT_BEGIN_NAMESPACE
class QLabel;
class QSortFilterProxyModel;
class QModelIndex;
class QFileSystemModel;
-class QDir;
class QAction;
QT_END_NAMESPACE
namespace ProjectExplorer {
-
-class ProjectExplorerPlugin;
-class Project;
-class Node;
-
namespace Internal {
class FolderNavigationWidget : public QWidget
@@ -69,7 +64,7 @@ public slots:
void toggleAutoSynchronization();
private slots:
- void setCurrentFile(const QString &filePath);
+ void setCurrentFile(Core::IEditor *editor);
void slotOpenItem(const QModelIndex &viewIndex);
void setHiddenFilesFilter(bool filter);
void ensureCurrentIndex();
diff --git a/src/plugins/projectexplorer/gccparser.cpp b/src/plugins/projectexplorer/gccparser.cpp
index bf1bd16c676..c5eb12025c6 100644
--- a/src/plugins/projectexplorer/gccparser.cpp
+++ b/src/plugins/projectexplorer/gccparser.cpp
@@ -197,7 +197,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_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");
const Core::Id categoryCompile = Constants::TASK_CATEGORY_COMPILE;
diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp
index 78483c40745..320bf869767 100644
--- a/src/plugins/projectexplorer/gcctoolchain.cpp
+++ b/src/plugins/projectexplorer/gcctoolchain.cpp
@@ -128,7 +128,7 @@ static QByteArray gccPredefinedMacros(const FileName &gcc, const QStringList &ar
QByteArray predefinedMacros = runGcc(gcc, arguments, env);
// Sanity check in case we get an error message instead of real output:
QTC_CHECK(predefinedMacros.isNull() || predefinedMacros.startsWith("#define "));
- if (Utils::HostOsInfo::isMacHost()) {
+ if (HostOsInfo::isMacHost()) {
// Turn off flag indicating Apple's blocks support
const QByteArray blocksDefine("#define __BLOCKS__ 1");
const QByteArray blocksUndefine("#undef __BLOCKS__");
@@ -539,7 +539,7 @@ GccToolChain::WarningFlags GccToolChain::warningFlags(const QStringList &cflags)
return flags;
}
-QList<HeaderPath> GccToolChain::systemHeaderPaths(const QStringList &cxxflags, const Utils::FileName &sysRoot) const
+QList<HeaderPath> GccToolChain::systemHeaderPaths(const QStringList &cxxflags, const FileName &sysRoot) const
{
if (m_headerPaths.isEmpty()) {
// Using a clean environment breaks ccache/distcc/etc.
@@ -617,7 +617,7 @@ QList<FileName> GccToolChain::suggestedMkspecList() const
return QList<FileName>();
}
-QString GccToolChain::makeCommand(const Utils::Environment &environment) const
+QString GccToolChain::makeCommand(const Environment &environment) const
{
QString make = QLatin1String("make");
FileName tmp = environment.searchInPath(make);
@@ -791,7 +791,7 @@ ToolChain *GccToolChainFactory::create()
QList<ToolChain *> GccToolChainFactory::autoDetect()
{
QList<ToolChain *> tcs;
- if (Utils::HostOsInfo::isMacHost()) {
+ if (HostOsInfo::isMacHost()) {
// Old mac compilers needed to support macx-gccXY mkspecs:
tcs.append(autoDetectToolchains(QLatin1String("g++-4.0"), Abi::hostAbi()));
tcs.append(autoDetectToolchains(QLatin1String("g++-4.2"), Abi::hostAbi()));
@@ -1036,10 +1036,10 @@ QString ClangToolChain::typeDisplayName() const
return ClangToolChainFactory::tr("Clang");
}
-QString ClangToolChain::makeCommand(const Utils::Environment &environment) const
+QString ClangToolChain::makeCommand(const Environment &environment) const
{
QStringList makes;
- if (Utils::HostOsInfo::isWindowsHost()) {
+ if (HostOsInfo::isWindowsHost()) {
makes << QLatin1String("mingw32-make.exe");
makes << QLatin1String("make.exe");
} else {
@@ -1186,9 +1186,9 @@ QString MingwToolChain::typeDisplayName() const
QList<FileName> MingwToolChain::suggestedMkspecList() const
{
- if (Utils::HostOsInfo::isWindowsHost())
+ if (HostOsInfo::isWindowsHost())
return QList<FileName>() << FileName::fromLatin1("win32-g++");
- if (Utils::HostOsInfo::isLinuxHost()) {
+ if (HostOsInfo::isLinuxHost()) {
if (version().startsWith(QLatin1String("4.6.")))
return QList<FileName>()
<< FileName::fromLatin1("win32-g++-4.6-cross")
@@ -1201,10 +1201,10 @@ QList<FileName> MingwToolChain::suggestedMkspecList() const
return QList<FileName>();
}
-QString MingwToolChain::makeCommand(const Utils::Environment &environment) const
+QString MingwToolChain::makeCommand(const Environment &environment) const
{
QStringList makes;
- if (Utils::HostOsInfo::isWindowsHost()) {
+ if (HostOsInfo::isWindowsHost()) {
makes << QLatin1String("mingw32-make.exe");
makes << QLatin1String("make.exe");
} else {
diff --git a/src/plugins/projectexplorer/journaldwatcher.cpp b/src/plugins/projectexplorer/journaldwatcher.cpp
new file mode 100644
index 00000000000..05a2f15796c
--- /dev/null
+++ b/src/plugins/projectexplorer/journaldwatcher.cpp
@@ -0,0 +1,221 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "journaldwatcher.h"
+
+#include <utils/algorithm.h>
+#include <utils/qtcassert.h>
+
+#include <QDebug>
+#include <QSocketNotifier>
+
+#include <systemd/sd-journal.h>
+
+namespace ProjectExplorer {
+
+JournaldWatcher *JournaldWatcher::m_instance = 0;
+
+namespace Internal {
+
+class JournaldWatcherPrivate
+{
+public:
+ JournaldWatcherPrivate() :
+ m_journalContext(0),
+ m_notifier(0)
+ { }
+
+ ~JournaldWatcherPrivate()
+ {
+ teardown();
+ }
+
+ bool setup();
+ void teardown();
+
+ JournaldWatcher::LogEntry retrieveEntry();
+
+ class SubscriberInformation {
+ public:
+ SubscriberInformation(QObject *sr, const JournaldWatcher::Subscription &sn) :
+ subscriber(sr), subscription(sn)
+ { }
+
+ QObject *subscriber;
+ JournaldWatcher::Subscription subscription;
+ };
+ QList<SubscriberInformation> m_subscriptions;
+
+ sd_journal *m_journalContext;
+ QSocketNotifier *m_notifier;
+};
+
+bool JournaldWatcherPrivate::setup()
+{
+ QTC_ASSERT(!m_journalContext, return false);
+ int r = sd_journal_open(&m_journalContext, 0);
+ if (r != 0)
+ return false;
+
+ r = sd_journal_seek_tail(m_journalContext);
+ if (r != 0)
+ return false;
+
+ // Work around https://bugs.freedesktop.org/show_bug.cgi?id=64614
+ sd_journal_previous(m_journalContext);
+
+ int fd = sd_journal_get_fd(m_journalContext);
+ if (fd < 0)
+ return false;
+
+ m_notifier = new QSocketNotifier(fd, QSocketNotifier::Read);
+ return true;
+}
+
+void JournaldWatcherPrivate::teardown()
+{
+ delete m_notifier;
+ m_notifier = 0;
+
+ if (m_journalContext) {
+ sd_journal_close(m_journalContext);
+ m_journalContext = 0;
+ }
+}
+
+JournaldWatcher::LogEntry JournaldWatcherPrivate::retrieveEntry()
+{
+ JournaldWatcher::LogEntry result;
+
+ // Advance:
+ int r = sd_journal_next(m_journalContext);
+ if (r == 0)
+ return result;
+
+ const void *rawData;
+ size_t length;
+ SD_JOURNAL_FOREACH_DATA(m_journalContext, rawData, length) {
+ QByteArray tmp = QByteArray::fromRawData(static_cast<const char *>(rawData), length);
+ int offset = tmp.indexOf('=');
+ if (offset < 0)
+ continue;
+ result.insert(tmp.left(offset), tmp.mid(offset + 1));
+ }
+
+ return result;
+}
+
+} // namespace Internal
+
+using namespace Internal;
+
+static JournaldWatcherPrivate *d = 0;
+
+JournaldWatcher::~JournaldWatcher()
+{
+ d->teardown();
+
+ m_instance = 0;
+
+ delete d;
+ d = 0;
+}
+
+JournaldWatcher *JournaldWatcher::instance()
+{
+ return m_instance;
+}
+
+bool JournaldWatcher::subscribe(QObject *subscriber, const Subscription &subscription)
+{
+ // Check that we do not have that subscriber yet:
+ int pos = Utils::indexOf(d->m_subscriptions,
+ [subscriber](const JournaldWatcherPrivate::SubscriberInformation &info) {
+ return info.subscriber == subscriber;
+ });
+ QTC_ASSERT(pos >= 0, return false);
+
+ d->m_subscriptions.append(JournaldWatcherPrivate::SubscriberInformation(subscriber, subscription));
+ connect(subscriber, &QObject::destroyed, m_instance, &JournaldWatcher::unsubscribe);
+
+ return true;
+}
+
+void JournaldWatcher::unsubscribe(QObject *subscriber)
+{
+ int pos = Utils::indexOf(d->m_subscriptions,
+ [subscriber](const JournaldWatcherPrivate::SubscriberInformation &info) {
+ return info.subscriber == subscriber;
+ });
+ if (pos < 0)
+ return;
+
+ d->m_subscriptions.removeAt(pos);
+}
+
+JournaldWatcher::JournaldWatcher()
+{
+ QTC_ASSERT(!m_instance, return);
+
+ d = new JournaldWatcherPrivate;
+ m_instance = this;
+
+ if (!d->setup())
+ d->teardown();
+ else
+ connect(d->m_notifier, &QSocketNotifier::activated, m_instance, &JournaldWatcher::handleEntry);
+ m_instance->handleEntry(); // advance to the end of file...
+}
+
+void JournaldWatcher::handleEntry()
+{
+ // process events:
+ if (!d->m_notifier || sd_journal_process(d->m_journalContext) == SD_JOURNAL_NOP)
+ return;
+
+ LogEntry logEntry;
+ forever {
+ logEntry = d->retrieveEntry();
+ if (logEntry.isEmpty())
+ break;
+
+ foreach (const JournaldWatcherPrivate::SubscriberInformation &info, d->m_subscriptions)
+ info.subscription(logEntry);
+
+ QByteArray tmp = logEntry.value(QByteArrayLiteral("_PID"));
+ quint64 pid = tmp.isEmpty() ? 0 : QString::fromLatin1(tmp).toInt();
+
+ QString message = QString::fromUtf8(logEntry.value(QByteArrayLiteral("MESSAGE")));
+
+ emit journaldOutput(pid, message);
+ }
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/journaldwatcher.h b/src/plugins/projectexplorer/journaldwatcher.h
new file mode 100644
index 00000000000..9f266ef97e3
--- /dev/null
+++ b/src/plugins/projectexplorer/journaldwatcher.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 JOURNALDWATCHER_H
+#define JOURNALDWATCHER_H
+
+#include <QObject>
+
+#include <functional>
+
+namespace ProjectExplorer {
+
+class ProjectExplorerPlugin;
+
+class JournaldWatcher : public QObject
+{
+ Q_OBJECT
+
+public:
+ typedef QMap<QByteArray, QByteArray> LogEntry;
+ typedef std::function<void(LogEntry)> Subscription;
+
+ ~JournaldWatcher();
+
+ static JournaldWatcher *instance();
+
+ static bool subscribe(QObject *subscriber, const Subscription &subscription);
+ static void unsubscribe(QObject *subscriber);
+
+signals:
+ void journaldOutput(quint64 pid, const QString &message);
+
+private:
+ JournaldWatcher();
+
+ void handleEntry();
+
+ static JournaldWatcher *m_instance;
+
+ friend class ProjectExplorerPlugin;
+};
+
+} // namespace ProjectExplorer
+
+#endif // JOURNALDWATCHER_H
diff --git a/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp b/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp
index 261692c114e..0f6e9edcecc 100644
--- a/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp
+++ b/src/plugins/projectexplorer/jsonwizard/jsonfieldpage.cpp
@@ -97,7 +97,7 @@ public:
m_expander.setAccumulating(true);
m_expander.registerVariable("INPUT", tr("The text edit input to fix up."),
[this]() { return m_currentInput; });
- m_expander.registerSubProvider([expander]() -> Utils::MacroExpander * { return expander; });
+ m_expander.registerSubProvider([expander]() -> MacroExpander * { return expander; });
}
void setFixupExpando(const QString &expando)
@@ -690,13 +690,13 @@ bool JsonFieldPage::ComboBoxField::parseData(const QVariant &data, QString *erro
m_index = tmp.value(QLatin1String("index"), 0).toInt(&ok);
if (!ok) {
*errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
- "ComboBox 'index' is not a integer value.");
+ "ComboBox 'index' is not an integer value.");
return false;
}
m_disabledIndex = tmp.value(QLatin1String("disabledIndex"), -1).toInt(&ok);
if (!ok) {
*errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
- "ComboBox 'disabledIndex' is not a integer value.");
+ "ComboBox 'disabledIndex' is not an integer value.");
return false;
}
diff --git a/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp b/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp
index 05acd88da66..cd2c4b77a0b 100644
--- a/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp
+++ b/src/plugins/projectexplorer/jsonwizard/jsonsummarypage.cpp
@@ -31,7 +31,6 @@
#include "jsonsummarypage.h"
#include "jsonwizard.h"
-#include "../addnewmodel.h"
#include "../project.h"
#include "../projectexplorerconstants.h"
#include "../projectnodes.h"
diff --git a/src/plugins/projectexplorer/jsonwizard/jsonwizard.cpp b/src/plugins/projectexplorer/jsonwizard/jsonwizard.cpp
index d9319f27956..3a932ebcef6 100644
--- a/src/plugins/projectexplorer/jsonwizard/jsonwizard.cpp
+++ b/src/plugins/projectexplorer/jsonwizard/jsonwizard.cpp
@@ -32,8 +32,11 @@
#include "jsonwizardgeneratorfactory.h"
+#include <coreplugin/messagemanager.h>
+
#include <utils/algorithm.h>
#include <utils/qtcassert.h>
+#include <utils/wizardpage.h>
#include <QFileInfo>
#include <QMessageBox>
@@ -213,4 +216,18 @@ void JsonWizard::accept()
emit allDone(m_files);
}
+void JsonWizard::handleNewPages(int pageId)
+{
+ Utils::WizardPage *wp = qobject_cast<Utils::WizardPage *>(page(pageId));
+ if (!wp)
+ return;
+
+ connect(wp, &Utils::WizardPage::reportError, this, &JsonWizard::handleError);
+}
+
+void JsonWizard::handleError(const QString &message)
+{
+ Core::MessageManager::write(message, Core::MessageManager::ModeSwitch);
+}
+
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/jsonwizard/jsonwizard.h b/src/plugins/projectexplorer/jsonwizard/jsonwizard.h
index a1d58c8f15c..37362a2cfeb 100644
--- a/src/plugins/projectexplorer/jsonwizard/jsonwizard.h
+++ b/src/plugins/projectexplorer/jsonwizard/jsonwizard.h
@@ -95,6 +95,10 @@ signals:
public slots:
void accept();
+private slots:
+ void handleNewPages(int pageId);
+ void handleError(const QString &message);
+
private:
QList<JsonWizardGenerator *> m_generators;
diff --git a/src/plugins/projectexplorer/jsonwizard/jsonwizardfactory.cpp b/src/plugins/projectexplorer/jsonwizard/jsonwizardfactory.cpp
index 38cda366906..794f6849954 100644
--- a/src/plugins/projectexplorer/jsonwizard/jsonwizardfactory.cpp
+++ b/src/plugins/projectexplorer/jsonwizard/jsonwizardfactory.cpp
@@ -37,6 +37,7 @@
#include "../projectexplorerconstants.h"
#include <coreplugin/coreconstants.h>
+#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>
@@ -152,7 +153,7 @@ static JsonWizardFactory::Page parsePage(const QVariant &value, QString *errorMe
JsonWizardFactory::Page p;
if (value.type() != QVariant::Map) {
- *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", "Page is not a object.");
+ *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", "Page is not an object.");
return p;
}
@@ -311,7 +312,7 @@ QList<JsonWizardFactory *> JsonWizardFactory::createWizardFactories()
}
JsonWizardFactory *JsonWizardFactory::createWizardFactory(const QVariantMap &data, const QDir &baseDir,
- QString *errorMessage)
+ QString *errorMessage)
{
JsonWizardFactory *factory = new JsonWizardFactory;
if (!factory->initialize(data, baseDir, errorMessage)) {
@@ -366,6 +367,7 @@ void JsonWizardFactory::runWizard(const QString &path, QWidget *parent, const QS
{
JsonWizard wizard(parent);
wizard.setWindowIcon(icon());
+ wizard.setWindowTitle(displayName());
wizard.setValue(QStringLiteral("WizardDir"), m_wizardDir);
Core::FeatureSet tmp = requiredFeatures();
@@ -434,10 +436,12 @@ void JsonWizardFactory::runWizard(const QString &path, QWidget *parent, const QS
wizard.addGenerator(gen);
}
- if (!m_pages.isEmpty())
+ if (!m_pages.isEmpty()) {
+ Core::ICore::registerWindow(&wizard, Core::Context("Core.NewJSONWizard"));
wizard.exec();
- else
+ } else {
wizard.accept();
+ }
}
QList<QVariant> JsonWizardFactory::objectOrList(const QVariant &data, QString *errorMessage)
@@ -553,7 +557,7 @@ bool JsonWizardFactory::initialize(const QVariantMap &data, const QDir &baseDir,
// Generator:
QVariantList list = objectOrList(data.value(QLatin1String(GENERATOR_KEY)), errorMessage);
- if (list.isEmpty()) {
+ if (!errorMessage->isEmpty()) {
*errorMessage = tr("When parsing \"generators\": %1").arg(*errorMessage);
return false;
}
@@ -608,7 +612,7 @@ bool JsonWizardFactory::initialize(const QVariantMap &data, const QDir &baseDir,
m_options.insert(key, value);
}
} else if (optionValue.isValid()) {
- *errorMessage = tr("Value for \"options\" is not a list");
+ *errorMessage = tr("Value for \"options\" is not a list.");
return false;
}
diff --git a/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp b/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp
index 74590ef283e..2ca6972e96b 100644
--- a/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp
+++ b/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp
@@ -83,7 +83,7 @@ static ICodeStylePreferences *codeStylePreferences(Project *project, Id language
// JsonWizardGenerator:
// --------------------------------------------------------------------
-bool JsonWizardGenerator::formatFile(const JsonWizard *wizard, Core::GeneratedFile *file, QString *errorMessage)
+bool JsonWizardGenerator::formatFile(const JsonWizard *wizard, GeneratedFile *file, QString *errorMessage)
{
Q_UNUSED(errorMessage);
@@ -132,7 +132,7 @@ JsonWizardGenerator::OverwriteResult JsonWizardGenerator::promptForOverwrite(Jso
foreach (const JsonWizard::GeneratorFile &f, *files) {
const QFileInfo fi(f.file.path());
- if (fi.exists() && !(f.file.attributes() & Core::GeneratedFile::ForceOverwrite))
+ if (fi.exists() && !(f.file.attributes() & GeneratedFile::ForceOverwrite))
existingFiles.append(f.file.path());
}
if (existingFiles.isEmpty())
@@ -173,7 +173,7 @@ JsonWizardGenerator::OverwriteResult JsonWizardGenerator::promptForOverwrite(Jso
}
// Prompt to overwrite existing files.
- Core::PromptOverwriteDialog overwriteDialog;
+ PromptOverwriteDialog overwriteDialog;
// Scripts cannot handle overwrite
overwriteDialog.setFiles(existingFiles);
@@ -195,7 +195,7 @@ JsonWizardGenerator::OverwriteResult JsonWizardGenerator::promptForOverwrite(Jso
{ return f.file.path() == keepFile; });
if (!file.isValid())
return OverwriteCanceled;
- file.file.setAttributes(file.file.attributes() | Core::GeneratedFile::KeepExistingFileAttribute);
+ file.file.setAttributes(file.file.attributes() | GeneratedFile::KeepExistingFileAttribute);
}
return OverwriteOk;
}
@@ -243,7 +243,7 @@ bool JsonWizardGenerator::allDone(const JsonWizard *wizard, JsonWizard::Generato
void JsonWizardGeneratorFactory::setTypeIdsSuffixes(const QStringList &suffixes)
{
m_typeIds = Utils::transform(suffixes, [](QString suffix)
- { return Core::Id::fromString(QString::fromLatin1(Constants::GENERATOR_ID_PREFIX) + suffix); });
+ { return Id::fromString(QString::fromLatin1(Constants::GENERATOR_ID_PREFIX) + suffix); });
}
void JsonWizardGeneratorFactory::setTypeIdsSuffix(const QString &suffix)
@@ -261,7 +261,7 @@ FileGeneratorFactory::FileGeneratorFactory()
setTypeIdsSuffix(QLatin1String("File"));
}
-JsonWizardGenerator *FileGeneratorFactory::create(Core::Id typeId, const QVariant &data,
+JsonWizardGenerator *FileGeneratorFactory::create(Id typeId, const QVariant &data,
const QString &path, const QString &platform,
const QVariantMap &variables)
{
@@ -285,7 +285,7 @@ JsonWizardGenerator *FileGeneratorFactory::create(Core::Id typeId, const QVarian
return gen;
}
-bool FileGeneratorFactory::validateData(Core::Id typeId, const QVariant &data, QString *errorMessage)
+bool FileGeneratorFactory::validateData(Id typeId, const QVariant &data, QString *errorMessage)
{
Q_UNUSED(data);
Q_UNUSED(errorMessage);
diff --git a/src/plugins/projectexplorer/kit.cpp b/src/plugins/projectexplorer/kit.cpp
index 7fae069f369..acee118d72e 100644
--- a/src/plugins/projectexplorer/kit.cpp
+++ b/src/plugins/projectexplorer/kit.cpp
@@ -106,7 +106,7 @@ public:
[kit] { return kit->displayName(); },
false);
m_macroExpander.registerVariable(Constants::VAR_CURRENTKIT_FILESYSTEMNAME,
- tr("The name of the currently active kit in a filesystem friendly version."),
+ tr("The name of the currently active kit in a filesystem-friendly version."),
[kit] { return kit->fileSystemFriendlyName(); },
false);
m_macroExpander.registerVariable(Constants::VAR_CURRENTKIT_ID,
@@ -129,9 +129,9 @@ public:
QIcon m_icon;
FileName m_iconPath;
- QHash<Core::Id, QVariant> m_data;
- QSet<Core::Id> m_sticky;
- QSet<Core::Id> m_mutable;
+ QHash<Id, QVariant> m_data;
+ QSet<Id> m_sticky;
+ QSet<Id> m_mutable;
MacroExpander m_macroExpander;
};
@@ -141,7 +141,7 @@ public:
// Kit:
// -------------------------------------------------------------------------
-Kit::Kit(Core::Id id) :
+Kit::Kit(Id id) :
d(new Internal::KitPrivate(id, this))
{
foreach (KitInformation *sti, KitManager::kitInformation())
@@ -151,7 +151,7 @@ Kit::Kit(Core::Id id) :
}
Kit::Kit(const QVariantMap &data) :
- d(new Internal::KitPrivate(Core::Id(), this))
+ d(new Internal::KitPrivate(Id(), this))
{
d->m_id = Id::fromSetting(data.value(QLatin1String(ID_KEY)));
@@ -180,11 +180,11 @@ Kit::Kit(const QVariantMap &data) :
QStringList mutableInfoList = data.value(QLatin1String(MUTABLE_INFO_KEY)).toStringList();
foreach (const QString &mutableInfo, mutableInfoList)
- d->m_mutable.insert(Core::Id::fromString(mutableInfo));
+ d->m_mutable.insert(Id::fromString(mutableInfo));
QStringList stickyInfoList = data.value(QLatin1String(STICKY_INFO_KEY)).toStringList();
foreach (const QString &stickyInfo, stickyInfoList)
- d->m_sticky.insert(Core::Id::fromString(stickyInfo));
+ d->m_sticky.insert(Id::fromString(stickyInfo));
}
Kit::~Kit()
@@ -469,7 +469,7 @@ void Kit::removeKey(Id key)
kitUpdated();
}
-bool Kit::isSticky(Core::Id id) const
+bool Kit::isSticky(Id id) const
{
return d->m_sticky.contains(id);
}
@@ -491,7 +491,7 @@ bool Kit::isEqual(const Kit *other) const
QVariantMap Kit::toMap() const
{
- typedef QHash<Core::Id, QVariant>::ConstIterator IdVariantConstIt;
+ typedef QHash<Id, QVariant>::ConstIterator IdVariantConstIt;
QVariantMap data;
data.insert(QLatin1String(ID_KEY), QString::fromLatin1(d->m_id.name()));
@@ -504,12 +504,12 @@ QVariantMap Kit::toMap() const
data.insert(QLatin1String(ICON_KEY), d->m_iconPath.toString());
QStringList mutableInfo;
- foreach (Core::Id id, d->m_mutable)
+ foreach (Id id, d->m_mutable)
mutableInfo << id.toString();
data.insert(QLatin1String(MUTABLE_INFO_KEY), mutableInfo);
QStringList stickyInfo;
- foreach (Core::Id id, d->m_sticky)
+ foreach (Id id, d->m_sticky)
stickyInfo << id.toString();
data.insert(QLatin1String(STICKY_INFO_KEY), stickyInfo);
@@ -602,7 +602,7 @@ void Kit::makeSticky()
}
}
-void Kit::setSticky(Core::Id id, bool b)
+void Kit::setSticky(Id id, bool b)
{
if (b)
d->m_sticky.insert(id);
@@ -656,7 +656,7 @@ QString Kit::displayNameForPlatform(const QString &platform) const
FeatureSet Kit::availableFeatures() const
{
- Core::FeatureSet features;
+ FeatureSet features;
foreach (const KitInformation *ki, KitManager::kitInformation())
features |= ki->availableFeatures(this);
return features;
diff --git a/src/plugins/projectexplorer/kitinformationconfigwidget.cpp b/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
index 03717f74a07..3ee0c42f02b 100644
--- a/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
+++ b/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
@@ -215,7 +215,7 @@ void ToolChainInformationConfigWidget::toolChainUpdated(ToolChain *tc)
void ToolChainInformationConfigWidget::manageToolChains()
{
- Core::ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
Constants::TOOLCHAIN_SETTINGS_PAGE_ID,
buttonWidget());
}
@@ -261,7 +261,7 @@ DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workin
QList<IDeviceFactory *> factories
= ExtensionSystem::PluginManager::getObjects<IDeviceFactory>();
foreach (IDeviceFactory *factory, factories) {
- foreach (Core::Id id, factory->availableCreationIds())
+ foreach (Id id, factory->availableCreationIds())
m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());
}
@@ -293,7 +293,7 @@ QString DeviceTypeInformationConfigWidget::toolTip() const
void DeviceTypeInformationConfigWidget::refresh()
{
- Core::Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);
+ Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);
if (!devType.isValid())
m_comboBox->setCurrentIndex(-1);
for (int i = 0; i < m_comboBox->count(); ++i) {
@@ -311,7 +311,7 @@ void DeviceTypeInformationConfigWidget::makeReadOnly()
void DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)
{
- Core::Id type = idx < 0 ? Core::Id() : Core::Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt());
+ Id type = idx < 0 ? Id() : Id::fromUniqueIdentifier(m_comboBox->itemData(idx).toInt());
DeviceTypeKitInformation::setDeviceTypeId(m_kit, type);
}
@@ -415,7 +415,7 @@ KitEnvironmentConfigWidget::KitEnvironmentConfigWidget(Kit *workingCopy, const K
m_editor(0)
{
refresh();
- m_manageButton->setText(tr("Change ..."));
+ m_manageButton->setText(tr("Change..."));
connect(m_manageButton, SIGNAL(clicked()), this, SLOT(editEnvironmentChanges()));
}
diff --git a/src/plugins/projectexplorer/kitmodel.cpp b/src/plugins/projectexplorer/kitmodel.cpp
index f484be85589..e14889edeb5 100644
--- a/src/plugins/projectexplorer/kitmodel.cpp
+++ b/src/plugins/projectexplorer/kitmodel.cpp
@@ -41,21 +41,15 @@
#include <QApplication>
#include <QLayout>
+using namespace Utils;
+
namespace ProjectExplorer {
namespace Internal {
-class KitNode
+class KitNode : public TreeItem
{
public:
- KitNode(KitNode *kn) :
- parent(kn), widget(0)
- {
- if (kn)
- kn->childNodes.append(this);
- }
-
- KitNode(KitNode *kn, Kit *k) :
- parent(kn), widget(0)
+ KitNode(Kit *k)
{
widget = KitManager::createConfigWidget(k);
if (widget) {
@@ -63,25 +57,48 @@ public:
widget->makeStickySubWidgetsReadOnly();
widget->setVisible(false);
}
-
- if (kn)
- kn->childNodes.append(this);
}
~KitNode()
{
- if (parent)
- parent->childNodes.removeOne(this);
delete widget;
+ }
- // deleting a child removes it from childNodes
- // so operate on a temporary list
- QList<KitNode *> tmp = childNodes;
- qDeleteAll(tmp);
+ QVariant data(int, int role) const
+ {
+ static QIcon warningIcon(QString::fromLatin1(Core::Constants::ICON_WARNING));
+ static QIcon errorIcon(QString::fromLatin1(Core::Constants::ICON_ERROR));
+
+ if (widget) {
+ if (role == Qt::FontRole) {
+ QFont f = QApplication::font();
+ if (widget->isDirty())
+ f.setBold(!f.bold());
+ if (widget->isDefaultKit())
+ f.setItalic(f.style() != QFont::StyleItalic);
+ return f;
+ }
+ if (role == Qt::DisplayRole) {
+ QString baseName = widget->displayName();
+ if (widget->isDefaultKit())
+ //: Mark up a kit as the default one.
+ baseName = KitModel::tr("%1 (default)").arg(baseName);
+ return baseName;
+ }
+ if (role == Qt::DecorationRole) {
+ if (!widget->isValid())
+ return errorIcon;
+ if (widget->hasWarning())
+ return warningIcon;
+ return QIcon();
+ }
+ if (role == Qt::ToolTipRole) {
+ return widget->validityMessage();
+ }
+ }
+ return QVariant();
}
- KitNode *parent;
- QList<KitNode *> childNodes;
KitManagerConfigWidget *widget;
};
@@ -90,201 +107,73 @@ public:
// --------------------------------------------------------------------------
KitModel::KitModel(QBoxLayout *parentLayout, QObject *parent) :
- QAbstractItemModel(parent),
+ TreeModel(parent),
m_parentLayout(parentLayout),
m_defaultNode(0),
m_keepUnique(true)
{
- m_root = new KitNode(0);
- m_autoRoot = new KitNode(m_root);
- m_manualRoot = new KitNode(m_root);
+ setHeader(QStringList(tr("Name")));
+ m_autoRoot = new TreeItem(QStringList(tr("Auto-detected")));
+ m_manualRoot = new TreeItem(QStringList(tr("Manual")));
+ rootItem()->appendChild(m_autoRoot);
+ rootItem()->appendChild(m_manualRoot);
foreach (Kit *k, KitManager::sortedKits())
addKit(k);
changeDefaultKit();
- connect(KitManager::instance(), SIGNAL(kitAdded(ProjectExplorer::Kit*)),
- this, SLOT(addKit(ProjectExplorer::Kit*)));
- connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
- this, SLOT(updateKit(ProjectExplorer::Kit*)));
- connect(KitManager::instance(), SIGNAL(unmanagedKitUpdated(ProjectExplorer::Kit*)),
- this, SLOT(updateKit(ProjectExplorer::Kit*)));
- connect(KitManager::instance(), SIGNAL(kitRemoved(ProjectExplorer::Kit*)),
- this, SLOT(removeKit(ProjectExplorer::Kit*)));
- connect(KitManager::instance(), SIGNAL(defaultkitChanged()),
- this, SLOT(changeDefaultKit()));
-}
-
-KitModel::~KitModel()
-{
- delete m_root;
-}
-
-QModelIndex KitModel::index(int row, int column, const QModelIndex &parent) const
-{
- if (!parent.isValid()) {
- if (row >= 0 && row < m_root->childNodes.count())
- return createIndex(row, column, m_root->childNodes.at(row));
- }
- KitNode *node = static_cast<KitNode *>(parent.internalPointer());
- if (row < node->childNodes.count() && column == 0)
- return createIndex(row, column, node->childNodes.at(row));
- else
- return QModelIndex();
-}
-
-QModelIndex KitModel::parent(const QModelIndex &idx) const
-{
- if (!idx.isValid())
- return QModelIndex();
- KitNode *node = static_cast<KitNode *>(idx.internalPointer());
- if (node->parent == m_root)
- return QModelIndex();
- return index(node->parent);
-}
-
-int KitModel::rowCount(const QModelIndex &parent) const
-{
- if (!parent.isValid())
- return m_root->childNodes.count();
- KitNode *node = static_cast<KitNode *>(parent.internalPointer());
- return node->childNodes.count();
+ connect(KitManager::instance(), &KitManager::kitAdded,
+ this, &KitModel::addKit);
+ connect(KitManager::instance(), &KitManager::kitUpdated,
+ this, &KitModel::updateKit);
+ connect(KitManager::instance(), &KitManager::unmanagedKitUpdated,
+ this, &KitModel::updateKit);
+ connect(KitManager::instance(), &KitManager::kitRemoved,
+ this, &KitModel::removeKit);
+ connect(KitManager::instance(), &KitManager::defaultkitChanged,
+ this, &KitModel::changeDefaultKit);
}
-int KitModel::columnCount(const QModelIndex &parent) const
-{
- Q_UNUSED(parent);
- return 1;
-}
-
-QVariant KitModel::data(const QModelIndex &index, int role) const
-{
- static QIcon warningIcon(QString::fromLatin1(Core::Constants::ICON_WARNING));
- static QIcon errorIcon(QString::fromLatin1(Core::Constants::ICON_ERROR));
-
- if (!index.isValid() || index.column() != 0)
- return QVariant();
-
- KitNode *node = static_cast<KitNode *>(index.internalPointer());
- QTC_ASSERT(node, return QVariant());
- if (node == m_autoRoot && role == Qt::DisplayRole)
- return tr("Auto-detected");
- if (node == m_manualRoot && role == Qt::DisplayRole)
- return tr("Manual");
- if (node->widget) {
- if (role == Qt::FontRole) {
- QFont f = QApplication::font();
- if (node->widget->isDirty())
- f.setBold(!f.bold());
- if (node == m_defaultNode)
- f.setItalic(f.style() != QFont::StyleItalic);
- return f;
- } else if (role == Qt::DisplayRole) {
- QString baseName = node->widget->displayName();
- if (node == m_defaultNode)
- //: Mark up a kit as the default one.
- baseName = tr("%1 (default)").arg(baseName);
- return baseName;
- } else if (role == Qt::DecorationRole) {
- if (!node->widget->isValid())
- return errorIcon;
- if (node->widget->hasWarning())
- return warningIcon;
- return QIcon();
- } else if (role == Qt::ToolTipRole) {
- return node->widget->validityMessage();
- }
- }
- return QVariant();
-}
-
-Qt::ItemFlags KitModel::flags(const QModelIndex &index) const
+Kit *KitModel::kit(const QModelIndex &index)
{
- if (!index.isValid())
- return 0;
-
- KitNode *node = static_cast<KitNode *>(index.internalPointer());
- if (!node->widget)
- return Qt::ItemIsEnabled;
-
- return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
+ KitNode *n = kitNode(index);
+ return n ? n->widget->workingCopy() : 0;
}
-QVariant KitModel::headerData(int section, Qt::Orientation orientation, int role) const
+KitNode *KitModel::kitNode(const QModelIndex &index)
{
- Q_UNUSED(section);
- if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
- return tr("Name");
- return QVariant();
-}
-
-Kit *KitModel::kit(const QModelIndex &index)
-{
- if (!index.isValid())
- return 0;
- KitNode *node = static_cast<KitNode *>(index.internalPointer());
- return node->widget->workingCopy();
+ TreeItem *n = itemFromIndex(index);
+ return n && n->level() == 2 ? static_cast<KitNode *>(n) : 0;
}
QModelIndex KitModel::indexOf(Kit *k) const
{
KitNode *n = findWorkingCopy(k);
- return n ? index(n) : QModelIndex();
+ return indexFromItem(n);
}
void KitModel::setDefaultKit(const QModelIndex &index)
{
- if (!index.isValid())
- return;
- KitNode *node = static_cast<KitNode *>(index.internalPointer());
- if (node->widget)
- setDefaultNode(node);
+ if (KitNode *n = kitNode(index))
+ setDefaultNode(n);
}
-bool KitModel::isDefaultKit(const QModelIndex &index)
+bool KitModel::isDefaultKit(Kit *k) const
{
- return m_defaultNode == static_cast<KitNode *>(index.internalPointer());
+ return m_defaultNode && m_defaultNode->widget->workingCopy() == k;
}
KitManagerConfigWidget *KitModel::widget(const QModelIndex &index)
{
- if (!index.isValid())
- return 0;
- KitNode *node = static_cast<KitNode *>(index.internalPointer());
- return node->widget;
-}
-
-bool KitModel::isDirty() const
-{
- return Utils::anyOf(m_manualRoot->childNodes, [](KitNode *n) {
- return n->widget->isDirty();
- });
-}
-
-bool KitModel::isDirty(Kit *k) const
-{
- KitNode *n = findWorkingCopy(k);
- return n ? n->widget->isDirty() : false;
-}
-
-void KitModel::setDirty()
-{
- KitManagerConfigWidget *w = qobject_cast<KitManagerConfigWidget *>(sender());
- QList<KitNode *> nodes = m_manualRoot->childNodes;
- nodes << m_autoRoot->childNodes;
- foreach (KitNode *n, nodes) {
- if (n->widget == w)
- emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
- }
+ KitNode *n = kitNode(index);
+ return n ? n->widget : 0;
}
void KitModel::validateKitNames()
{
- QList<KitNode *> nodes = m_manualRoot->childNodes;
- nodes << m_autoRoot->childNodes;
QHash<QString, int> nameHash;
- foreach (KitNode *n, nodes) {
+ foreach (KitNode *n, treeLevelItems<KitNode *>(2)) {
const QString displayName = n->widget->displayName();
if (nameHash.contains(displayName))
++nameHash[displayName];
@@ -292,7 +181,7 @@ void KitModel::validateKitNames()
nameHash.insert(displayName, 1);
}
- foreach (KitNode *n, nodes) {
+ foreach (KitNode *n, treeLevelItems<KitNode *>(2)) {
const QString displayName = n->widget->displayName();
n->widget->setHasUniqueName(nameHash.value(displayName) == 1);
}
@@ -301,23 +190,18 @@ void KitModel::validateKitNames()
void KitModel::apply()
{
// Remove unused kits:
- QList<KitNode *> nodes = m_toRemoveList;
- foreach (KitNode *n, nodes) {
- Q_ASSERT(!n->parent);
+ foreach (KitNode *n, m_toRemoveList)
n->widget->removeKit();
- }
// Update kits:
- nodes = m_autoRoot->childNodes; // These can be dirty due to being made default!
- nodes.append(m_manualRoot->childNodes);
- foreach (KitNode *n, nodes) {
- Q_ASSERT(n);
- Q_ASSERT(n->widget);
+ foreach (KitNode *n, treeLevelItems<KitNode *>(2)) {
if (n->widget->isDirty()) {
n->widget->apply();
- emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
+ n->update();
}
}
+
+ layoutChanged(); // Force update.
}
void KitModel::markForRemoval(Kit *k)
@@ -327,30 +211,23 @@ void KitModel::markForRemoval(Kit *k)
return;
if (node == m_defaultNode) {
- KitNode *newDefault = 0;
- if (!m_autoRoot->childNodes.isEmpty())
- newDefault = m_autoRoot->childNodes.at(0);
- else if (!m_manualRoot->childNodes.isEmpty())
- newDefault = m_manualRoot->childNodes.at(0);
- setDefaultNode(newDefault);
+ TreeItem *newDefault = m_autoRoot->firstChild();
+ if (!newDefault)
+ newDefault = m_manualRoot->firstChild();
+ setDefaultNode(static_cast<KitNode *>(newDefault));
}
- beginRemoveRows(index(m_manualRoot), m_manualRoot->childNodes.indexOf(node), m_manualRoot->childNodes.indexOf(node));
- m_manualRoot->childNodes.removeOne(node);
- node->parent = 0;
+ removeItem(node);
if (node->widget->configures(0))
delete node;
else
m_toRemoveList.append(node);
- endRemoveRows();
}
Kit *KitModel::markForAddition(Kit *baseKit)
{
- int pos = m_manualRoot->childNodes.size();
- beginInsertRows(index(m_manualRoot), pos, pos);
-
- KitNode *node = createNode(m_manualRoot, 0);
+ KitNode *node = createNode(0);
+ m_manualRoot->appendChild(node);
Kit *k = node->widget->workingCopy();
KitGuard g(k);
if (baseKit) {
@@ -365,36 +242,27 @@ Kit *KitModel::markForAddition(Kit *baseKit)
if (!m_defaultNode)
setDefaultNode(node);
- endInsertRows();
-
return k;
}
-QModelIndex KitModel::index(KitNode *node, int column) const
-{
- if (node->parent == 0) // is root (or was marked for deletion)
- return QModelIndex();
- else if (node->parent == m_root)
- return index(m_root->childNodes.indexOf(node), column, QModelIndex());
- else
- return index(node->parent->childNodes.indexOf(node), column, index(node->parent));
-}
-
KitNode *KitModel::findWorkingCopy(Kit *k) const
{
- auto compareWorkingCopy = [&k](KitNode *n){ return n->widget->workingCopy() == k; };
-
- KitNode *n = Utils::findOrDefault(m_autoRoot->childNodes, compareWorkingCopy);
- if (!n)
- n = Utils::findOrDefault(m_manualRoot->childNodes, compareWorkingCopy);
- return n;
+ foreach (KitNode *n, treeLevelItems<KitNode *>(2)) {
+ if (n->widget->workingCopy() == k)
+ return n;
+ }
+ return 0;
}
-KitNode *KitModel::createNode(KitNode *parent, Kit *k)
+KitNode *KitModel::createNode(Kit *k)
{
- KitNode *node = new KitNode(parent, k);
+ KitNode *node = new KitNode(k);
m_parentLayout->addWidget(node->widget);
- connect(node->widget, SIGNAL(dirty()), this, SLOT(setDirty()));
+ connect(node->widget, &KitManagerConfigWidget::dirty, [this, node] {
+ if (m_autoRoot->children().contains(node)
+ || m_manualRoot->children().contains(node))
+ node->update();
+ });
return node;
}
@@ -402,43 +270,25 @@ void KitModel::setDefaultNode(KitNode *node)
{
if (m_defaultNode) {
m_defaultNode->widget->setIsDefaultKit(false);
- emit dataChanged(index(m_defaultNode), index(m_defaultNode));
+ m_defaultNode->update();
}
m_defaultNode = node;
if (m_defaultNode) {
m_defaultNode->widget->setIsDefaultKit(true);
- emit dataChanged(index(m_defaultNode), index(m_defaultNode));
+ m_defaultNode->update();
}
}
-QList<Kit *> KitModel::kitList(KitNode *node) const
-{
- QList<Kit *> result;
- if (!node)
- return result;
- foreach (KitNode *n, node->childNodes)
- result.append(kitList(n));
- if (node->widget)
- result.append(node->widget->workingCopy());
- return result;
-}
-
void KitModel::addKit(Kit *k)
{
- foreach (KitNode *n, m_manualRoot->childNodes) {
+ foreach (TreeItem *n, m_manualRoot->children()) {
// Was added by us
- if (n->widget->configures(k))
+ if (static_cast<KitNode *>(n)->widget->configures(k))
return;
}
- KitNode *parent = m_manualRoot;
- if (k->isAutoDetected())
- parent = m_autoRoot;
- int row = parent->childNodes.count();
-
- beginInsertRows(index(parent), row, row);
- createNode(parent, k);
- endInsertRows();
+ TreeItem *parent = k->isAutoDetected() ? m_autoRoot : m_manualRoot;
+ parent->appendChild(createNode(k));
validateKitNames();
emit kitStateChanged();
@@ -463,24 +313,17 @@ void KitModel::removeKit(Kit *k)
}
}
- KitNode *parent = m_manualRoot;
- if (k->isAutoDetected())
- parent = m_autoRoot;
- int row = 0;
KitNode *node = 0;
- foreach (KitNode *current, parent->childNodes) {
- if (current->widget->configures(k)) {
- node = current;
+ foreach (KitNode *n, treeLevelItems<KitNode *>(2)) {
+ if (n->widget->configures(k)) {
+ node = n;
break;
}
- ++row;
}
- beginRemoveRows(index(parent), row, row);
- parent->childNodes.removeAt(row);
if (m_defaultNode == node)
m_defaultNode = 0;
- endRemoveRows();
+ removeItem(node);
delete node;
validateKitNames();
@@ -490,12 +333,10 @@ void KitModel::removeKit(Kit *k)
void KitModel::changeDefaultKit()
{
Kit *defaultKit = KitManager::defaultKit();
- QList<KitNode *> nodes = m_autoRoot->childNodes;
- nodes << m_manualRoot->childNodes;
- foreach (KitNode *n, nodes) {
+ foreach (KitNode *n, treeLevelItems<KitNode *>(2)) {
if (n->widget->configures(defaultKit)) {
setDefaultNode(n);
- break;
+ return;
}
}
}
diff --git a/src/plugins/projectexplorer/kitmodel.h b/src/plugins/projectexplorer/kitmodel.h
index 2cde469b3f2..d3b7054fbbc 100644
--- a/src/plugins/projectexplorer/kitmodel.h
+++ b/src/plugins/projectexplorer/kitmodel.h
@@ -33,7 +33,7 @@
#include "projectexplorer_export.h"
-#include <QAbstractItemModel>
+#include <utils/treemodel.h>
QT_BEGIN_NAMESPACE
class QBoxLayout;
@@ -46,42 +46,30 @@ class KitFactory;
class KitManager;
namespace Internal {
-class KitManagerConfigWidget;
+class KitManagerConfigWidget;
class KitNode;
// --------------------------------------------------------------------------
// KitModel:
// --------------------------------------------------------------------------
-class KitModel : public QAbstractItemModel
+class KitModel : public Utils::TreeModel
{
Q_OBJECT
public:
explicit KitModel(QBoxLayout *parentLayout, QObject *parent = 0);
- ~KitModel();
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
- QModelIndex parent(const QModelIndex &index) const;
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
Kit *kit(const QModelIndex &);
+ KitNode *kitNode(const QModelIndex &);
QModelIndex indexOf(Kit *k) const;
void setDefaultKit(const QModelIndex &index);
- bool isDefaultKit(const QModelIndex &index);
+ bool isDefaultKit(Kit *k) const;
ProjectExplorer::Internal::KitManagerConfigWidget *widget(const QModelIndex &);
- bool isDirty() const;
- bool isDirty(Kit *k) const;
-
void apply();
void markForRemoval(Kit *k);
@@ -90,24 +78,19 @@ public:
signals:
void kitStateChanged();
-private slots:
+private:
void addKit(ProjectExplorer::Kit *k);
void updateKit(ProjectExplorer::Kit *k);
void removeKit(ProjectExplorer::Kit *k);
void changeDefaultKit();
- void setDirty();
void validateKitNames();
-private:
- QModelIndex index(KitNode *, int column = 0) const;
KitNode *findWorkingCopy(Kit *k) const;
- KitNode *createNode(KitNode *parent, Kit *k);
+ KitNode *createNode(Kit *k);
void setDefaultNode(KitNode *node);
- QList<Kit *> kitList(KitNode *node) const;
- KitNode *m_root;
- KitNode *m_autoRoot;
- KitNode *m_manualRoot;
+ Utils::TreeItem *m_autoRoot;
+ Utils::TreeItem *m_manualRoot;
QList<KitNode *> m_toRemoveList;
diff --git a/src/plugins/projectexplorer/kitoptionspage.cpp b/src/plugins/projectexplorer/kitoptionspage.cpp
index 5fcf9a5a27e..23cdd77f4c6 100644
--- a/src/plugins/projectexplorer/kitoptionspage.cpp
+++ b/src/plugins/projectexplorer/kitoptionspage.cpp
@@ -44,123 +44,106 @@
#include <QVBoxLayout>
namespace ProjectExplorer {
+namespace Internal {
// --------------------------------------------------------------------------
-// KitOptionsPage:
+// KitOptionsPageWidget:
// --------------------------------------------------------------------------
-KitOptionsPage::KitOptionsPage() :
- m_model(0), m_selectionModel(0), m_currentWidget(0), m_toShow(0)
+class KitOptionsPageWidget : public QWidget
{
- setId(Constants::KITS_SETTINGS_PAGE_ID);
- setDisplayName(tr("Kits"));
- setCategory(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
- setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
- Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
- setCategoryIcon(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
-}
-
-QWidget *KitOptionsPage::widget()
-{
- if (!m_configWidget) {
- m_configWidget = new QWidget;
-
- m_kitsView = new QTreeView(m_configWidget);
- m_kitsView->setUniformRowHeights(true);
- m_kitsView->header()->setStretchLastSection(true);
- m_kitsView->setSizePolicy(m_kitsView->sizePolicy().horizontalPolicy(),
- QSizePolicy::Ignored);
-
- 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_makeDefaultButton = new QPushButton(tr("Make Default"), m_configWidget);
-
- 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->addWidget(m_makeDefaultButton);
- buttonLayout->addStretch();
-
- QHBoxLayout *horizontalLayout = new QHBoxLayout();
- horizontalLayout->addWidget(m_kitsView);
- horizontalLayout->addLayout(buttonLayout);
-
- QVBoxLayout *verticalLayout = new QVBoxLayout(m_configWidget);
- verticalLayout->addLayout(horizontalLayout);
-
- m_model = new Internal::KitModel(verticalLayout);
- connect(m_model, SIGNAL(kitStateChanged()), this, SLOT(updateState()));
- verticalLayout->setStretch(0, 1);
- verticalLayout->setStretch(1, 0);
-
- m_kitsView->setModel(m_model);
- m_kitsView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
- m_kitsView->expandAll();
-
- m_selectionModel = m_kitsView->selectionModel();
- connect(m_selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(kitSelectionChanged()));
- connect(KitManager::instance(), SIGNAL(kitAdded(ProjectExplorer::Kit*)),
- this, SLOT(kitSelectionChanged()));
- connect(KitManager::instance(), SIGNAL(kitRemoved(ProjectExplorer::Kit*)),
- this, SLOT(kitSelectionChanged()));
- connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
- this, SLOT(kitSelectionChanged()));
-
- // Set up add menu:
- connect(m_addButton, SIGNAL(clicked()), this, SLOT(addNewKit()));
- connect(m_cloneButton, SIGNAL(clicked()), this, SLOT(cloneKit()));
- connect(m_delButton, SIGNAL(clicked()), this, SLOT(removeKit()));
- connect(m_makeDefaultButton, SIGNAL(clicked()), this, SLOT(makeDefaultKit()));
-
- updateState();
-
- if (m_toShow) {
- QModelIndex index = m_model->indexOf(m_toShow);
- m_selectionModel->select(index,
- QItemSelectionModel::Clear
- | QItemSelectionModel::SelectCurrent
- | QItemSelectionModel::Rows);
- m_kitsView->scrollTo(index);
- }
- m_toShow = 0;
- }
- return m_configWidget;
-}
-
-void KitOptionsPage::apply()
+public:
+ KitOptionsPageWidget();
+
+ QModelIndex currentIndex() const;
+ Kit *currentKit() const;
+
+ void kitSelectionChanged();
+ void addNewKit();
+ void cloneKit();
+ void removeKit();
+ void makeDefaultKit();
+ void updateState();
+
+public:
+ QTreeView *m_kitsView;
+ QPushButton *m_addButton;
+ QPushButton *m_cloneButton;
+ QPushButton *m_delButton;
+ QPushButton *m_makeDefaultButton;
+
+ KitModel *m_model;
+ QItemSelectionModel *m_selectionModel;
+ QWidget *m_currentWidget;
+};
+
+KitOptionsPageWidget::KitOptionsPageWidget()
+ : m_model(0), m_selectionModel(0), m_currentWidget(0)
{
- if (m_model)
- m_model->apply();
-}
+ m_kitsView = new QTreeView(this);
+ m_kitsView->setUniformRowHeights(true);
+ m_kitsView->header()->setStretchLastSection(true);
+ m_kitsView->setSizePolicy(m_kitsView->sizePolicy().horizontalPolicy(),
+ QSizePolicy::Ignored);
+
+ m_addButton = new QPushButton(KitOptionsPage::tr("Add"), this);
+ m_cloneButton = new QPushButton(KitOptionsPage::tr("Clone"), this);
+ m_delButton = new QPushButton(KitOptionsPage::tr("Remove"), this);
+ m_makeDefaultButton = new QPushButton(KitOptionsPage::tr("Make Default"), this);
+
+ auto 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->addWidget(m_makeDefaultButton);
+ buttonLayout->addStretch();
+
+ auto horizontalLayout = new QHBoxLayout;
+ horizontalLayout->addWidget(m_kitsView);
+ horizontalLayout->addLayout(buttonLayout);
+
+ auto verticalLayout = new QVBoxLayout(this);
+ verticalLayout->addLayout(horizontalLayout);
+
+ m_model = new Internal::KitModel(verticalLayout, this);
+ connect(m_model, &Internal::KitModel::kitStateChanged,
+ this, &KitOptionsPageWidget::updateState);
+ verticalLayout->setStretch(0, 1);
+ verticalLayout->setStretch(1, 0);
+
+ m_kitsView->setModel(m_model);
+ m_kitsView->header()->setSectionResizeMode(0, QHeaderView::Stretch);
+ m_kitsView->expandAll();
+
+ m_selectionModel = m_kitsView->selectionModel();
+ connect(m_selectionModel, &QItemSelectionModel::selectionChanged,
+ this, &KitOptionsPageWidget::kitSelectionChanged);
+ connect(KitManager::instance(), &KitManager::kitAdded,
+ this, &KitOptionsPageWidget::kitSelectionChanged);
+ connect(KitManager::instance(), &KitManager::kitRemoved,
+ this, &KitOptionsPageWidget::kitSelectionChanged);
+ connect(KitManager::instance(), &KitManager::kitUpdated,
+ this, &KitOptionsPageWidget::kitSelectionChanged);
+
+ // Set up add menu:
+ connect(m_addButton, &QAbstractButton::clicked,
+ this, &KitOptionsPageWidget::addNewKit);
+ connect(m_cloneButton, &QAbstractButton::clicked,
+ this, &KitOptionsPageWidget::cloneKit);
+ connect(m_delButton, &QAbstractButton::clicked,
+ this, &KitOptionsPageWidget::removeKit);
+ connect(m_makeDefaultButton, &QAbstractButton::clicked,
+ this, &KitOptionsPageWidget::makeDefaultKit);
-void KitOptionsPage::finish()
-{
- if (m_model) {
- delete m_model;
- m_model = 0;
- }
-
- delete m_configWidget;
- m_selectionModel = 0; // child of m_configWidget
- m_kitsView = 0; // child of m_configWidget
- m_currentWidget = 0; // deleted by the model
- m_toShow = 0;
-}
-
-void KitOptionsPage::showKit(Kit *k)
-{
- m_toShow = k;
+ updateState();
}
-void KitOptionsPage::kitSelectionChanged()
+void KitOptionsPageWidget::kitSelectionChanged()
{
QModelIndex current = currentIndex();
- QWidget *newWidget = current.isValid() ? m_model->widget(current) : 0;
+ QWidget *newWidget = m_model->widget(current);
if (newWidget == m_currentWidget)
return;
@@ -176,7 +159,7 @@ void KitOptionsPage::kitSelectionChanged()
updateState();
}
-void KitOptionsPage::addNewKit()
+void KitOptionsPageWidget::addNewKit()
{
Kit *k = m_model->markForAddition(0);
@@ -187,9 +170,14 @@ void KitOptionsPage::addNewKit()
| QItemSelectionModel::Rows);
}
-void KitOptionsPage::cloneKit()
+Kit *KitOptionsPageWidget::currentKit() const
{
- Kit *current = m_model->kit(currentIndex());
+ return m_model->kit(currentIndex());
+}
+
+void KitOptionsPageWidget::cloneKit()
+{
+ Kit *current = currentKit();
if (!current)
return;
@@ -202,21 +190,19 @@ void KitOptionsPage::cloneKit()
| QItemSelectionModel::Rows);
}
-void KitOptionsPage::removeKit()
+void KitOptionsPageWidget::removeKit()
{
- Kit *k = m_model->kit(currentIndex());
- if (!k)
- return;
- m_model->markForRemoval(k);
+ if (Kit *k = currentKit())
+ m_model->markForRemoval(k);
}
-void KitOptionsPage::makeDefaultKit()
+void KitOptionsPageWidget::makeDefaultKit()
{
m_model->setDefaultKit(currentIndex());
updateState();
}
-void KitOptionsPage::updateState()
+void KitOptionsPageWidget::updateState()
{
if (!m_kitsView)
return;
@@ -224,12 +210,11 @@ void KitOptionsPage::updateState()
bool canCopy = false;
bool canDelete = false;
bool canMakeDefault = false;
- QModelIndex index = currentIndex();
- Kit *k = m_model->kit(index);
- if (k) {
+
+ if (Kit *k = currentKit()) {
canCopy = true;
canDelete = !k->isAutoDetected();
- canMakeDefault = !m_model->isDefaultKit(index);
+ canMakeDefault = !m_model->isDefaultKit(k);
}
m_cloneButton->setEnabled(canCopy);
@@ -237,7 +222,7 @@ void KitOptionsPage::updateState()
m_makeDefaultButton->setEnabled(canMakeDefault);
}
-QModelIndex KitOptionsPage::currentIndex() const
+QModelIndex KitOptionsPageWidget::currentIndex() const
{
if (!m_selectionModel)
return QModelIndex();
@@ -248,4 +233,56 @@ QModelIndex KitOptionsPage::currentIndex() const
return idxs.at(0);
}
+} // namespace Internal
+
+// --------------------------------------------------------------------------
+// KitOptionsPage:
+// --------------------------------------------------------------------------
+
+KitOptionsPage::KitOptionsPage()
+{
+ setId(Constants::KITS_SETTINGS_PAGE_ID);
+ setDisplayName(tr("Kits"));
+ setCategory(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
+ setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
+ Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
+ setCategoryIcon(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
+}
+
+QWidget *KitOptionsPage::widget()
+{
+ if (!m_widget)
+ m_widget = new Internal::KitOptionsPageWidget;
+
+ return m_widget;
+}
+
+void KitOptionsPage::apply()
+{
+ if (m_widget)
+ m_widget->m_model->apply();
+}
+
+void KitOptionsPage::finish()
+{
+ if (m_widget) {
+ delete m_widget;
+ m_widget = 0;
+ }
+}
+
+void KitOptionsPage::showKit(Kit *k)
+{
+ if (!k)
+ return;
+
+ (void) widget();
+ QModelIndex index = m_widget->m_model->indexOf(k);
+ m_widget->m_selectionModel->select(index,
+ QItemSelectionModel::Clear
+ | QItemSelectionModel::SelectCurrent
+ | QItemSelectionModel::Rows);
+ m_widget->m_kitsView->scrollTo(index);
+}
+
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/kitoptionspage.h b/src/plugins/projectexplorer/kitoptionspage.h
index 5b146aeb97b..38f84684825 100644
--- a/src/plugins/projectexplorer/kitoptionspage.h
+++ b/src/plugins/projectexplorer/kitoptionspage.h
@@ -35,18 +35,11 @@
#include <coreplugin/dialogs/ioptionspage.h>
-#include <QModelIndex>
#include <QPointer>
-QT_BEGIN_NAMESPACE
-class QItemSelectionModel;
-class QTreeView;
-class QPushButton;
-QT_END_NAMESPACE
-
namespace ProjectExplorer {
-namespace Internal { class KitModel; }
+namespace Internal { class KitOptionsPageWidget; }
class Kit;
@@ -67,30 +60,8 @@ public:
void showKit(Kit *k);
-private slots:
- void kitSelectionChanged();
- void addNewKit();
- void cloneKit();
- void removeKit();
- void makeDefaultKit();
- void updateState();
-
private:
- QModelIndex currentIndex() const;
-
- QTreeView *m_kitsView;
- QPushButton *m_addButton;
- QPushButton *m_cloneButton;
- QPushButton *m_delButton;
- QPushButton *m_makeDefaultButton;
-
- QPointer<QWidget> m_configWidget;
-
- Internal::KitModel *m_model;
- QItemSelectionModel *m_selectionModel;
- QWidget *m_currentWidget;
-
- Kit *m_toShow;
+ QPointer<Internal::KitOptionsPageWidget> m_widget;
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/linuxiccparser.cpp b/src/plugins/projectexplorer/linuxiccparser.cpp
index 9cc8a3cacd5..640ea0cdae3 100644
--- a/src/plugins/projectexplorer/linuxiccparser.cpp
+++ b/src/plugins/projectexplorer/linuxiccparser.cpp
@@ -61,11 +61,22 @@ LinuxIccParser::LinuxIccParser()
m_caretLine.setMinimal(true);
QTC_CHECK(m_caretLine.isValid());
+ // ".pch/Qt5Core.pchi.cpp": creating precompiled header file ".pch/Qt5Core.pchi"
+ // "animation/qabstractanimation.cpp": using precompiled header file ".pch/Qt5Core.pchi"
+ m_pchInfoLine.setPattern(QLatin1String("^\".*\": (creating|using) precompiled header file \".*\"\n$"));
+ m_pchInfoLine.setMinimal(true);
+ QTC_CHECK(m_pchInfoLine.isValid());
+
appendOutputParser(new LdParser);
}
void LinuxIccParser::stdError(const QString &line)
{
+ if (m_pchInfoLine.indexIn(line) != -1) {
+ // totally ignore this line
+ return;
+ }
+
if (m_expectFirstLine && m_firstLine.indexIn(line) != -1) {
// Clear out old task
Task::TaskType type = Task::Unknown;
@@ -129,7 +140,7 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_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")
@@ -143,6 +154,13 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
<< QList<Task>()
<< QString();
+ QTest::newRow("pch creation")
+ << QString::fromLatin1("\".pch/Qt5Core.pchi.cpp\": creating precompiled header file \".pch/Qt5Core.pchi\"")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << QList<Task>()
+ << QString();
+
QTest::newRow("undeclared function")
<< QString::fromLatin1("main.cpp(13): error: identifier \"f\" is undefined\n"
" f(0);\n"
@@ -157,6 +175,23 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
Constants::TASK_CATEGORY_COMPILE))
<< QString();
+ // same, with PCH remark
+ QTest::newRow("pch use+undeclared function")
+ << QString::fromLatin1("\"main.cpp\": using precompiled header file \".pch/Qt5Core.pchi\"\n"
+ "main.cpp(13): error: identifier \"f\" is undefined\n"
+ " f(0);\n"
+ " ^\n"
+ "\n")
+ << OutputParserTester::STDERR
+ << QString() << QString::fromLatin1("\n")
+ << (QList<Task>()
+ << Task(Task::Error,
+ QLatin1String("identifier \"f\" is undefined\nf(0);"),
+ Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 13,
+ Constants::TASK_CATEGORY_COMPILE))
+ << QString();
+
+
QTest::newRow("private function")
<< QString::fromLatin1("main.cpp(53): error #308: function \"AClass::privatefunc\" (declared at line 4 of \"main.h\") is inaccessible\n"
" b.privatefunc();\n"
diff --git a/src/plugins/projectexplorer/linuxiccparser.h b/src/plugins/projectexplorer/linuxiccparser.h
index 7f92fe0dc70..1414ac38ec1 100644
--- a/src/plugins/projectexplorer/linuxiccparser.h
+++ b/src/plugins/projectexplorer/linuxiccparser.h
@@ -53,6 +53,7 @@ private:
QRegExp m_firstLine;
QRegExp m_continuationLines;
QRegExp m_caretLine;
+ QRegExp m_pchInfoLine;
bool m_expectFirstLine;
int m_indent;
diff --git a/src/plugins/projectexplorer/localapplicationruncontrol.h b/src/plugins/projectexplorer/localapplicationruncontrol.h
index 04f7e194345..1e3957e2345 100644
--- a/src/plugins/projectexplorer/localapplicationruncontrol.h
+++ b/src/plugins/projectexplorer/localapplicationruncontrol.h
@@ -44,9 +44,9 @@ class LocalApplicationRunControlFactory : public IRunControlFactory
Q_OBJECT
public:
LocalApplicationRunControlFactory ();
- virtual ~LocalApplicationRunControlFactory();
- virtual bool canRun(RunConfiguration *runConfiguration, RunMode mode) const;
- virtual RunControl* create(RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage);
+ ~LocalApplicationRunControlFactory();
+ bool canRun(RunConfiguration *runConfiguration, RunMode mode) const;
+ RunControl* create(RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage);
};
class LocalApplicationRunControl : public RunControl
@@ -54,10 +54,10 @@ class LocalApplicationRunControl : public RunControl
Q_OBJECT
public:
LocalApplicationRunControl(LocalApplicationRunConfiguration *runConfiguration, RunMode mode);
- virtual ~LocalApplicationRunControl();
- virtual void start();
- virtual StopResult stop();
- virtual bool isRunning() const;
+ ~LocalApplicationRunControl();
+ void start();
+ StopResult stop();
+ bool isRunning() const;
private slots:
void processStarted();
void processExited(int exitCode, QProcess::ExitStatus status);
@@ -67,7 +67,6 @@ private:
QString m_executable;
QString m_commandLineArguments;
ApplicationLauncher::Mode m_runMode;
- ProcessHandle m_applicationProcessHandle;
bool m_running;
};
diff --git a/src/plugins/projectexplorer/miniprojecttargetselector.cpp b/src/plugins/projectexplorer/miniprojecttargetselector.cpp
index b65d128c7e9..5eb390c546b 100644
--- a/src/plugins/projectexplorer/miniprojecttargetselector.cpp
+++ b/src/plugins/projectexplorer/miniprojecttargetselector.cpp
@@ -142,7 +142,7 @@ void TargetSelectorDelegate::paint(QPainter *painter,
option.palette.highlight().color() :
option.palette.dark().color();
painter->fillRect(option.rect, color.darker(140));
- Utils::StyleHelper::drawCornerImage(selectionGradient, painter, option.rect.adjusted(0, 0, 0, -1), 5, 5, 5, 5);
+ StyleHelper::drawCornerImage(selectionGradient, painter, option.rect.adjusted(0, 0, 0, -1), 5, 5, 5, 5);
painter->setPen(QColor(255, 255, 255, 60));
painter->drawLine(option.rect.topLeft(), option.rect.topRight());
painter->setPen(QColor(255, 255, 255, 30));
@@ -625,7 +625,7 @@ void KitAreaWidget::updateKit(Kit *k)
QWidget *MiniProjectTargetSelector::createTitleLabel(const QString &text)
{
- Utils::StyledBar *bar = new Utils::StyledBar(this);
+ StyledBar *bar = new StyledBar(this);
bar->setSingleRow(true);
QVBoxLayout *toolLayout = new QVBoxLayout(bar);
toolLayout->setContentsMargins(6, 0, 6, 0);
@@ -1599,7 +1599,7 @@ void MiniProjectTargetSelector::paintEvent(QPaintEvent *)
// draw thicker border on the bottom
QRect bottomRect(0, rect().height() - 8, rect().width(), 8);
static QImage image(QLatin1String(":/projectexplorer/images/targetpanel_bottom.png"));
- Utils::StyleHelper::drawCornerImage(image, &painter, bottomRect, 1, 1, 1, 1);
+ StyleHelper::drawCornerImage(image, &painter, bottomRect, 1, 1, 1, 1);
}
}
diff --git a/src/plugins/projectexplorer/nodesvisitor.cpp b/src/plugins/projectexplorer/nodesvisitor.cpp
index 233ee9dc797..2ea12fc87c6 100644
--- a/src/plugins/projectexplorer/nodesvisitor.cpp
+++ b/src/plugins/projectexplorer/nodesvisitor.cpp
@@ -101,6 +101,11 @@ void FindNodesForFileVisitor::visitFolderNode(FolderNode *node)
}
}
+void FindNodesForFileVisitor::visitSessionNode(SessionNode *node)
+{
+ visitFolderNode(node);
+}
+
/*!
\class FindAllFilesVisitor
diff --git a/src/plugins/projectexplorer/nodesvisitor.h b/src/plugins/projectexplorer/nodesvisitor.h
index f72ebe25890..565683ee4ac 100644
--- a/src/plugins/projectexplorer/nodesvisitor.h
+++ b/src/plugins/projectexplorer/nodesvisitor.h
@@ -64,6 +64,7 @@ public:
void visitProjectNode(ProjectNode *node);
void visitFolderNode(FolderNode *node);
+ void visitSessionNode(SessionNode *node);
private:
QString m_path;
QList<Node*> m_nodes;
diff --git a/src/plugins/projectexplorer/panelswidget.cpp b/src/plugins/projectexplorer/panelswidget.cpp
index ac79f77aa08..6b0c6c3736e 100644
--- a/src/plugins/projectexplorer/panelswidget.cpp
+++ b/src/plugins/projectexplorer/panelswidget.cpp
@@ -92,9 +92,9 @@ void RootWidget::paintEvent(QPaintEvent *e)
if (creatorTheme()->widgetStyle() == Theme::StyleDefault) {
// draw separator line to the right of the settings panel
QPainter painter(this);
- QColor light = Utils::StyleHelper::mergedColors(
+ QColor light = StyleHelper::mergedColors(
palette().button().color(), Qt::white, 30);
- QColor dark = Utils::StyleHelper::mergedColors(
+ QColor dark = StyleHelper::mergedColors(
palette().button().color(), Qt::black, 85);
painter.setPen(light);
@@ -119,7 +119,7 @@ PanelsWidget::PanelsWidget(QWidget *parent) :
m_root->setContentsMargins(0, 0, 40, 0);
QPalette pal;
- QColor background = Utils::StyleHelper::mergedColors(
+ QColor background = StyleHelper::mergedColors(
palette().window().color(), Qt::white, 85);
pal.setColor(QPalette::All, QPalette::Window, background.darker(102));
setPalette(pal);
diff --git a/src/plugins/projectexplorer/processparameters.cpp b/src/plugins/projectexplorer/processparameters.cpp
index c65be8d5ede..909862ba58c 100644
--- a/src/plugins/projectexplorer/processparameters.cpp
+++ b/src/plugins/projectexplorer/processparameters.cpp
@@ -30,10 +30,10 @@
#include "processparameters.h"
+#include <utils/fileutils.h>
#include <utils/macroexpander.h>
#include <utils/qtcprocess.h>
-#include <QFileInfo>
#include <QDir>
/*!
@@ -163,7 +163,7 @@ QString ProcessParameters::prettyCommand() const
QString cmd = m_command;
if (m_macroExpander)
cmd = m_macroExpander->expand(cmd);
- return QFileInfo(cmd).fileName();
+ return Utils::FileName::fromString(cmd).fileName();
}
QString ProcessParameters::prettyArguments() const
diff --git a/src/plugins/projectexplorer/project.cpp b/src/plugins/projectexplorer/project.cpp
index 512b19a8994..2482e059ebf 100644
--- a/src/plugins/projectexplorer/project.cpp
+++ b/src/plugins/projectexplorer/project.cpp
@@ -134,7 +134,7 @@ Core::Id Project::id() const
Utils::FileName Project::projectFilePath() const
{
- return Utils::FileName::fromString(document()->filePath());
+ return document()->filePath();
}
bool Project::hasActiveBuildSettings() const
diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp
index 91afb6820b9..89dcd44dd39 100644
--- a/src/plugins/projectexplorer/projectexplorer.cpp
+++ b/src/plugins/projectexplorer/projectexplorer.cpp
@@ -36,6 +36,9 @@
#include "deployablefile.h"
#include "deployconfiguration.h"
#include "gcctoolchainfactories.h"
+#ifdef WITH_JOURNALD
+#include "journaldwatcher.h"
+#endif
#include "jsonwizard/jsonwizardfactory.h"
#include "jsonwizard/jsonwizardgeneratorfactory.h"
#include "jsonwizard/jsonwizardpagefactory_p.h"
@@ -96,6 +99,7 @@
# include "wincetoolchain.h"
#endif
+#include "projecttree.h"
#include "projectwelcomepage.h"
#include <extensionsystem/pluginspec.h>
@@ -162,7 +166,6 @@
namespace {
bool debug = false;
-const char EXTERNAL_FILE_WARNING[] = "ExternalFile";
}
using namespace Core;
@@ -172,7 +175,7 @@ namespace ProjectExplorer {
static Target *activeTarget()
{
- Project *project = ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
return project ? project->activeTarget() : 0;
}
@@ -194,13 +197,12 @@ public:
ProjectExplorerPluginPrivate();
void deploy(QList<Project *>);
- int queue(QList<Project *>, QList<Core::Id> stepIds);
+ int queue(QList<Project *>, QList<Id> stepIds);
void updateContextMenuActions();
void executeRunConfiguration(RunConfiguration *, RunMode mode);
QPair<bool, QString> buildSettingsEnabledForSession();
QPair<bool, QString> buildSettingsEnabled(Project *pro);
- void setCurrent(Project *project, QString filePath, Node *node);
void addToRecentProjects(const QString &fileName, const QString &displayName);
void startRunControl(RunControl *runControl, RunMode runMode);
@@ -209,12 +211,7 @@ public:
void updateDeployActions();
void updateRunWithoutDeployMenu();
- QMenu *m_sessionContextMenu;
QMenu *m_sessionMenu;
- QMenu *m_projectMenu;
- QMenu *m_subProjectMenu;
- QMenu *m_folderMenu;
- QMenu *m_fileMenu;
QMenu *m_openWithMenu;
QMultiMap<int, QObject*> m_actionMap;
@@ -266,10 +263,6 @@ public:
ProjectWindow *m_proWindow;
QString m_sessionToRestoreAtStartup;
- Project *m_currentProject;
- Context m_lastProjectContext;
- Node *m_currentNode;
-
QStringList m_profileMimeTypes;
AppOutputPane *m_outputPane;
@@ -291,22 +284,24 @@ public:
KitManager *m_kitManager;
ToolChainManager *m_toolChainManager;
bool m_shuttingDown;
- bool m_ignoreDocumentManagerChangedFile;
QStringList m_arguments;
QList<ProjectPanelFactory *> m_panelFactories;
QString m_renameFileError;
+#ifdef WITH_JOURNALD
+ JournaldWatcher *m_journalWatcher;
+#endif
};
ProjectExplorerPluginPrivate::ProjectExplorerPluginPrivate() :
- m_currentProject(0),
- m_currentNode(0),
m_shouldHaveRunConfiguration(false),
m_runMode(NoRunMode),
m_projectsMode(0),
m_kitManager(0),
m_toolChainManager(0),
- m_shuttingDown(false),
- m_ignoreDocumentManagerChangedFile(false)
+ m_shuttingDown(false)
+#ifdef WITH_JOURNALD
+ , m_journalWatcher(0)
+#endif
{
}
@@ -345,6 +340,9 @@ ProjectExplorerPlugin::~ProjectExplorerPlugin()
// Force sequence of deletion:
delete dd->m_kitManager; // remove all the profile information
delete dd->m_toolChainManager;
+#ifdef WITH_JOURNALD
+ delete dd->m_journalWatcher;
+#endif
ProjectPanelFactory::destroyFactories();
delete dd;
}
@@ -368,6 +366,10 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
addAutoReleasedObject(new DeviceManager);
+#ifdef WITH_JOURNALD
+ dd->m_journalWatcher = new JournaldWatcher;
+#endif
+
// Add ToolChainFactories:
#ifdef Q_OS_WIN
addAutoReleasedObject(new WinDebugInterface);
@@ -389,7 +391,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
dd->m_kitManager = new KitManager; // register before ToolChainManager
dd->m_toolChainManager = new ToolChainManager;
- Core::IWizardFactory::registerFeatureProvider(new KitFeatureProvider);
+ IWizardFactory::registerFeatureProvider(new KitFeatureProvider);
// Register KitInformation:
KitManager::registerKitInformation(new DeviceTypeKitInformation);
@@ -409,9 +411,6 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
connect(dd->m_welcomePage, SIGNAL(manageSessions()), this, SLOT(showSessionManager()));
addObject(dd->m_welcomePage);
- connect(DocumentManager::instance(), SIGNAL(currentFileChanged(QString)),
- this, SLOT(setCurrentFile(QString)));
-
QObject *sessionManager = new SessionManager(this);
connect(sessionManager, SIGNAL(projectAdded(ProjectExplorer::Project*)),
@@ -435,17 +434,17 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
connect(sessionManager, SIGNAL(sessionLoaded(QString)),
this, SLOT(updateWelcomePage()));
- NodesWatcher *watcher = new NodesWatcher(this);
- SessionManager::sessionNode()->registerWatcher(watcher);
-
- connect(watcher, &NodesWatcher::foldersAboutToBeRemoved,
- this, &ProjectExplorerPlugin::foldersAboutToBeRemoved);
- connect(watcher, &NodesWatcher::filesAboutToBeRemoved,
- this, &ProjectExplorerPlugin::filesAboutToBeRemoved);
+ ProjectTree *tree = new ProjectTree(this);
+ connect(tree, &ProjectTree::currentProjectChanged,
+ dd, &ProjectExplorerPluginPrivate::updateContextMenuActions);
+ connect(tree, &ProjectTree::currentNodeChanged,
+ dd, &ProjectExplorerPluginPrivate::updateContextMenuActions);
+ connect(tree, &ProjectTree::currentProjectChanged,
+ dd, &ProjectExplorerPluginPrivate::updateActions);
- addAutoReleasedObject(new CustomWizardMetaFactory<CustomProjectWizard>(Core::IWizardFactory::ProjectWizard));
- addAutoReleasedObject(new CustomWizardMetaFactory<CustomWizard>(Core::IWizardFactory::FileWizard));
- addAutoReleasedObject(new CustomWizardMetaFactory<CustomWizard>(Core::IWizardFactory::ClassWizard));
+ addAutoReleasedObject(new CustomWizardMetaFactory<CustomProjectWizard>(IWizardFactory::ProjectWizard));
+ addAutoReleasedObject(new CustomWizardMetaFactory<CustomWizard>(IWizardFactory::FileWizard));
+ addAutoReleasedObject(new CustomWizardMetaFactory<CustomWizard>(IWizardFactory::ClassWizard));
// For JsonWizard:
JsonWizardFactory::registerPageFactory(new FieldPageFactory);
@@ -562,12 +561,6 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
ActionContainer *mfileContextMenu =
ActionManager::createMenu(Constants::M_FILECONTEXT);
- dd->m_sessionContextMenu = msessionContextMenu->menu();
- dd->m_projectMenu = mprojectContextMenu->menu();
- dd->m_subProjectMenu = msubProjectContextMenu->menu();
- dd->m_folderMenu = mfolderContextMenu->menu();
- dd->m_fileMenu = mfileContextMenu->menu();
-
ActionContainer *mfile =
ActionManager::actionContainer(Core::Constants::M_FILE);
ActionContainer *menubar =
@@ -913,7 +906,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// add existing directory action
dd->m_addExistingDirectoryAction = new QAction(tr("Add Existing Directory..."), this);
- cmd = Core::ActionManager::registerAction(dd->m_addExistingDirectoryAction,
+ cmd = ActionManager::registerAction(dd->m_addExistingDirectoryAction,
Constants::ADDEXISTINGDIRECTORY,
projecTreeContext);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_FILES);
@@ -1020,7 +1013,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
addAutoReleasedObject(new ProjectTreeWidgetFactory);
addAutoReleasedObject(new FolderNavigationWidgetFactory);
- addAutoReleasedObject(new DeployConfigurationFactory);
+ addAutoReleasedObject(new DefaultDeployConfigurationFactory);
QSettings *s = ICore::settings();
const QStringList fileNames =
@@ -1104,6 +1097,8 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
connect(dd->m_deleteFileAction, SIGNAL(triggered()), this, SLOT(deleteFile()));
connect(dd->m_renameFileAction, SIGNAL(triggered()), this, SLOT(renameFile()));
connect(dd->m_setStartupProjectAction, SIGNAL(triggered()), this, SLOT(setStartupProject()));
+ connect(dd->m_projectTreeCollapseAllAction, &QAction::triggered,
+ ProjectTree::instance(), &ProjectTree::collapseAll);
connect(this, SIGNAL(updateRunActions()), this, SLOT(slotUpdateRunActions()));
connect(this, &ProjectExplorerPlugin::settingsChanged,
@@ -1132,11 +1127,11 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
expander->registerFileVariables(Constants::VAR_CURRENTPROJECT_PREFIX,
tr("Current project's main file"),
[this]() -> QString {
- QString projectFilePath;
- if (Project *project = ProjectExplorerPlugin::currentProject())
+ Utils::FileName projectFilePath;
+ if (Project *project = ProjectTree::currentProject())
if (IDocument *doc = project->document())
projectFilePath = doc->filePath();
- return projectFilePath;
+ return projectFilePath.toString();
});
expander->registerVariable(Constants::VAR_CURRENTPROJECT_BUILDPATH,
@@ -1149,7 +1144,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
expander->registerVariable(Constants::VAR_CURRENTPROJECT_NAME,
tr("The name of the current project."),
[this]() -> QString {
- Project *project = ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
return project ? project->displayName() : QString();
});
@@ -1161,7 +1156,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
});
expander->registerVariable(Constants::VAR_CURRENTKIT_FILESYSTEMNAME,
- tr("The name of the currently active kit in a filesystem friendly version."),
+ tr("The name of the currently active kit in a filesystem-friendly version."),
[]() -> QString {
Kit *kit = currentKit();
return kit ? kit->fileSystemFriendlyName() : QString();
@@ -1254,12 +1249,12 @@ void ProjectExplorerPlugin::loadAction()
// for your special convenience, we preselect a pro file if it is
// the current file
if (const IDocument *document = EditorManager::currentDocument()) {
- const QString fn = document->filePath();
+ const QString fn = document->filePath().toString();
const bool isProject = dd->m_profileMimeTypes.contains(document->mimeType());
dir = isProject ? fn : QFileInfo(fn).absolutePath();
}
- QString filename = QFileDialog::getOpenFileName(Core::ICore::dialogParent(),
+ QString filename = QFileDialog::getOpenFileName(ICore::dialogParent(),
tr("Load Project"), dir,
dd->m_projectFilterString);
if (filename.isEmpty())
@@ -1277,7 +1272,7 @@ void ProjectExplorerPlugin::unloadProjectContextMenu()
if (debug)
qDebug() << "ProjectExplorerPlugin::unloadProjectContextMenu";
- if (Project *p = currentProject())
+ if (Project *p = ProjectTree::currentProject())
unloadProject(p);
}
@@ -1316,7 +1311,7 @@ void ProjectExplorerPlugin::unloadProject(Project *project)
if (!DocumentManager::saveModifiedDocumentSilently(document))
return;
- dd->addToRecentProjects(document->filePath(), project->displayName());
+ dd->addToRecentProjects(document->filePath().toString(), project->displayName());
SessionManager::removeProject(project);
m_instance->updateActions();
@@ -1342,7 +1337,7 @@ void ProjectExplorerPlugin::extensionsInitialized()
QList<IProjectManager*> projectManagers =
ExtensionSystem::PluginManager::getObjects<IProjectManager>();
- QList<Core::MimeGlobPattern> allGlobPatterns;
+ QList<MimeGlobPattern> allGlobPatterns;
const QString filterSeparator = QLatin1String(";;");
QStringList filterStrings;
@@ -1352,7 +1347,7 @@ void ProjectExplorerPlugin::extensionsInitialized()
QString errorMessage;
ProjectExplorerPlugin::openProject(fileName, &errorMessage);
if (!errorMessage.isEmpty())
- QMessageBox::critical(Core::ICore::mainWindow(),
+ QMessageBox::critical(ICore::mainWindow(),
tr("Failed to open project"), errorMessage);
return 0;
});
@@ -1404,6 +1399,7 @@ ExtensionSystem::IPlugin::ShutdownFlag ProjectExplorerPlugin::aboutToShutdown()
{
disconnect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*,Core::IMode*)),
this, SLOT(currentModeChanged(Core::IMode*,Core::IMode*)));
+ ProjectTree::aboutToShutDown();
dd->m_proWindow->aboutToShutdown(); // disconnect from session
SessionManager::closeAllProjects();
dd->m_projectsMode = 0;
@@ -1587,9 +1583,6 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName
if (pro->restoreSettings()) {
connect(pro, SIGNAL(fileListChanged()), m_instance, SIGNAL(fileListChanged()));
SessionManager::addProject(pro);
- // Make sure we always have a current project / node
- if (!dd->m_currentProject && !openedPro.isEmpty())
- setCurrentNode(pro->rootProjectNode());
openedPro += pro;
} else {
appendError(errorString, tr("Failed opening project \"%1\": Settings could not be restored.")
@@ -1629,46 +1622,6 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName
return openedPro;
}
-Project *ProjectExplorerPlugin::currentProject()
-{
- Project *project = dd->m_currentProject;
- if (debug) {
- if (project)
- qDebug() << "ProjectExplorerPlugin::currentProject returns " << project->displayName();
- else
- qDebug() << "ProjectExplorerPlugin::currentProject returns 0";
- }
- return project;
-}
-
-Node *ProjectExplorerPlugin::currentNode()
-{
- return dd->m_currentNode;
-}
-
-void ProjectExplorerPlugin::setCurrentFile(Project *project, const QString &filePath)
-{
- dd->setCurrent(project, filePath, 0);
-}
-
-void ProjectExplorerPlugin::setCurrentFile(const QString &filePath)
-{
- if (dd->m_ignoreDocumentManagerChangedFile)
- return;
- 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
- if (!project)
- project = dd->m_currentProject;
- dd->setCurrent(project, filePath, 0);
-}
-
-void ProjectExplorerPlugin::setCurrentNode(Node *node)
-{
- dd->setCurrent(SessionManager::projectForNode(node), QString(), node);
-}
-
void ProjectExplorerPlugin::updateWelcomePage()
{
dd->m_welcomePage->reloadWelcomeScreenData();
@@ -1723,6 +1676,11 @@ QStringList ProjectExplorerPlugin::projectFileGlobs()
return result;
}
+void ProjectExplorerPlugin::updateContextMenuActions()
+{
+ dd->updateContextMenuActions();
+}
+
/*!
This function is connected to the ICore::coreOpened signal. If
there was no session explicitly loaded, it creates an empty new
@@ -1812,50 +1770,6 @@ void ProjectExplorerPlugin::loadSession(const QString &session)
SessionManager::loadSession(session);
}
-
-void ProjectExplorerPlugin::showContextMenu(QWidget *view, const QPoint &globalPos, Node *node)
-{
- QMenu *contextMenu = 0;
-
- if (!node)
- node = SessionManager::sessionNode();
-
- if (node->nodeType() != SessionNodeType) {
- Project *project = SessionManager::projectForNode(node);
- setCurrentNode(node);
-
- emit m_instance->aboutToShowContextMenu(project, node);
- switch (node->nodeType()) {
- case ProjectNodeType:
- if (node->parentFolderNode() == SessionManager::sessionNode())
- contextMenu = dd->m_projectMenu;
- else
- contextMenu = dd->m_subProjectMenu;
- break;
- case VirtualFolderNodeType:
- case FolderNodeType:
- contextMenu = dd->m_folderMenu;
- break;
- case FileNodeType:
- m_instance->populateOpenWithMenu();
- contextMenu = dd->m_fileMenu;
- break;
- default:
- qWarning("ProjectExplorerPlugin::showContextMenu - Missing handler for node type");
- }
- } else { // session item
- emit m_instance->aboutToShowContextMenu(0, node);
-
- contextMenu = dd->m_sessionContextMenu;
- }
-
- dd->updateContextMenuActions();
- dd->m_projectTreeCollapseAllAction->disconnect(SIGNAL(triggered()));
- connect(dd->m_projectTreeCollapseAllAction, SIGNAL(triggered()), view, SLOT(collapseAll()));
- if (contextMenu && contextMenu->actions().count() > 0)
- contextMenu->popup(globalPos);
-}
-
void ProjectExplorerPlugin::buildStateChanged(Project * pro)
{
if (debug) {
@@ -1971,57 +1885,6 @@ void ProjectExplorerPlugin::buildQueueFinished(bool success)
dd->m_runMode = NoRunMode;
}
-void ProjectExplorerPlugin::updateExternalFileWarning()
-{
- IDocument *document = qobject_cast<IDocument *>(sender());
- if (!document || document->filePath().isEmpty())
- return;
- InfoBar *infoBar = document->infoBar();
- Id externalFileId(EXTERNAL_FILE_WARNING);
- if (!document->isModified()) {
- infoBar->removeInfo(externalFileId);
- return;
- }
- if (!dd->m_currentProject || !infoBar->canInfoBeAdded(externalFileId))
- return;
- Utils::FileName fileName = Utils::FileName::fromString(document->filePath());
- Utils::FileName projectDir = dd->m_currentProject->projectDirectory();
- if (projectDir.isEmpty() || fileName.isChildOf(projectDir))
- return;
- // External file. Test if it under the same VCS
- QString topLevel;
- if (VcsManager::findVersionControlForDirectory(projectDir.toString(), &topLevel)
- && fileName.isChildOf(Utils::FileName::fromString(topLevel))) {
- return;
- }
- infoBar->addInfo(InfoBarEntry(externalFileId,
- tr("<b>Warning:</b> This file is outside the project directory."),
- InfoBarEntry::GlobalSuppressionEnabled));
-}
-
-void ProjectExplorerPlugin::updateContext()
-{
- dd->updateContext();
-}
-
-void ProjectExplorerPluginPrivate::updateContext()
-{
- Context oldContext;
- oldContext.add(m_lastProjectContext);
-
- Context newContext;
- if (m_currentProject) {
- newContext.add(m_currentProject->projectContext());
- newContext.add(m_currentProject->projectLanguages());
-
- m_lastProjectContext = newContext;
- } else {
- m_lastProjectContext = Context();
- }
-
- ICore::updateAdditionalContexts(oldContext, newContext);
-}
-
void ProjectExplorerPlugin::runConfigurationConfigurationFinished()
{
RunConfiguration *rc = qobject_cast<RunConfiguration *>(sender());
@@ -2041,7 +1904,7 @@ static QString pathOrDirectoryFor(Node *node, bool dir)
{
QString path = node->path();
QString location;
- FolderNode *folder = qobject_cast<FolderNode *>(node);
+ FolderNode *folder = dynamic_cast<FolderNode *>(node);
if (node->nodeType() == VirtualFolderNodeType && folder) {
// Virtual Folder case
// If there are files directly below or no subfolders, take the folder path
@@ -2086,59 +1949,6 @@ QString ProjectExplorerPlugin::directoryFor(Node *node)
return pathOrDirectoryFor(node, true);
}
-void ProjectExplorerPluginPrivate::setCurrent(Project *project, QString filePath, Node *node)
-{
- if (debug)
- qDebug() << "ProjectExplorer - setting path to " << (node ? pathFor(node) : filePath)
- << " and project to " << (project ? project->displayName() : QLatin1String("0"));
-
- if (node)
- filePath = pathFor(node);
- else
- node = ProjectTreeWidget::nodeForFile(filePath, project);
-
- bool projectChanged = false;
- if (m_currentProject != project) {
- if (m_currentProject) {
- disconnect(m_currentProject, SIGNAL(projectContextUpdated()),
- m_instance, SLOT(updateContext()));
- disconnect(m_currentProject, SIGNAL(projectLanguagesUpdated()),
- m_instance, SLOT(updateContext()));
- }
- if (project) {
- connect(project, SIGNAL(projectContextUpdated()),
- m_instance, SLOT(updateContext()));
- connect(project, SIGNAL(projectLanguagesUpdated()),
- m_instance, SLOT(updateContext()));
- }
- projectChanged = true;
- }
- m_currentProject = project;
-
- if (!node && EditorManager::currentDocument()) {
- connect(EditorManager::currentDocument(), SIGNAL(changed()),
- m_instance, SLOT(updateExternalFileWarning()), Qt::UniqueConnection);
- }
- if (projectChanged || m_currentNode != node) {
- m_currentNode = node;
- if (debug)
- qDebug() << "ProjectExplorer - currentNodeChanged(" << (node ? node->path() : QLatin1String("0")) << ", " << (project ? project->displayName() : QLatin1String("0")) << ')';
- emit m_instance->currentNodeChanged(m_currentNode, project);
- updateContextMenuActions();
- }
- if (projectChanged) {
- if (debug)
- qDebug() << "ProjectExplorer - currentProjectChanged(" << (project ? project->displayName() : QLatin1String("0")) << ')';
- emit m_instance->currentProjectChanged(project);
- updateActions();
- }
-
- m_ignoreDocumentManagerChangedFile = true;
- DocumentManager::setCurrentFile(filePath);
- updateContext();
- m_ignoreDocumentManagerChangedFile = false;
-}
-
void ProjectExplorerPlugin::updateActions()
{
dd->updateActions();
@@ -2152,13 +1962,14 @@ void ProjectExplorerPluginPrivate::updateActions()
m_newAction->setEnabled(!ICore::isNewItemDialogRunning());
Project *project = SessionManager::startupProject();
+ Project *currentProject = ProjectTree::currentProject(); // for context menu actions
QPair<bool, QString> buildActionState = buildSettingsEnabled(project);
- QPair<bool, QString> buildActionContextState = buildSettingsEnabled(m_currentProject);
+ QPair<bool, QString> buildActionContextState = buildSettingsEnabled(currentProject);
QPair<bool, QString> buildSessionState = buildSettingsEnabledForSession();
QString projectName = project ? project->displayName() : QString();
- QString projectNameContextMenu = m_currentProject ? m_currentProject->displayName() : QString();
+ QString projectNameContextMenu = currentProject ? currentProject->displayName() : QString();
m_unloadAction->setParameter(projectName);
m_unloadActionContextMenu->setParameter(projectNameContextMenu);
@@ -2179,7 +1990,7 @@ void ProjectExplorerPluginPrivate::updateActions()
// Context menu actions
m_setStartupProjectAction->setParameter(projectNameContextMenu);
- bool hasDependencies = SessionManager::projectOrder(m_currentProject).size() > 1;
+ bool hasDependencies = SessionManager::projectOrder(currentProject).size() > 1;
if (hasDependencies) {
m_buildActionContextMenu->setText(tr("Build Without Dependencies"));
m_rebuildActionContextMenu->setText(tr("Rebuild Without Dependencies"));
@@ -2359,7 +2170,7 @@ void ProjectExplorerPlugin::buildProject()
void ProjectExplorerPlugin::buildProjectContextMenu()
{
- dd->queue(QList<Project *>() << dd->m_currentProject,
+ dd->queue(QList<Project *>() << ProjectTree::currentProject(),
QList<Id>() << Id(Constants::BUILDSTEPS_BUILD));
}
@@ -2383,7 +2194,7 @@ void ProjectExplorerPlugin::rebuildProject()
void ProjectExplorerPlugin::rebuildProjectContextMenu()
{
- dd->queue(QList<Project *>() << dd->m_currentProject,
+ dd->queue(QList<Project *>() << ProjectTree::currentProject(),
QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN) << Id(Constants::BUILDSTEPS_BUILD));
}
@@ -2405,7 +2216,7 @@ void ProjectExplorerPlugin::deployProject()
void ProjectExplorerPlugin::deployProjectContextMenu()
{
- dd->deploy(QList<Project *>() << dd->m_currentProject);
+ dd->deploy(QList<Project *>() << ProjectTree::currentProject());
}
void ProjectExplorerPlugin::deploySession()
@@ -2427,7 +2238,7 @@ void ProjectExplorerPlugin::cleanProject()
void ProjectExplorerPlugin::cleanProjectContextMenu()
{
- dd->queue(QList<Project *>() << dd->m_currentProject,
+ dd->queue(QList<Project *>() << ProjectTree::currentProject(),
QList<Id>() << Id(Constants::BUILDSTEPS_CLEAN));
}
@@ -2449,9 +2260,9 @@ void ProjectExplorerPlugin::runProjectWithoutDeploy()
void ProjectExplorerPlugin::runProjectContextMenu()
{
- ProjectNode *projectNode = qobject_cast<ProjectNode*>(dd->m_currentNode);
- if (projectNode == dd->m_currentProject->rootProjectNode() || !projectNode) {
- runProject(dd->m_currentProject, NormalRunMode);
+ ProjectNode *projectNode = dynamic_cast<ProjectNode*>(ProjectTree::currentNode());
+ if (projectNode == ProjectTree::currentProject()->rootProjectNode() || !projectNode) {
+ runProject(ProjectTree::currentProject(), NormalRunMode);
} else {
QAction *act = qobject_cast<QAction *>(sender());
if (!act)
@@ -2708,16 +2519,17 @@ void ProjectExplorerPluginPrivate::updateDeployActions()
bool enableDeployActions = project
&& !BuildManager::isBuilding(project)
&& hasDeploySettings(project);
- bool enableDeployActionsContextMenu = m_currentProject
- && !BuildManager::isBuilding(m_currentProject)
- && hasDeploySettings(m_currentProject);
+ Project *currentProject = ProjectTree::currentProject();
+ bool enableDeployActionsContextMenu = currentProject
+ && !BuildManager::isBuilding(currentProject)
+ && hasDeploySettings(currentProject);
if (m_projectExplorerSettings.buildBeforeDeploy) {
if (hasBuildSettings(project)
&& !buildSettingsEnabled(project).first)
enableDeployActions = false;
- if (hasBuildSettings(m_currentProject)
- && !buildSettingsEnabled(m_currentProject).first)
+ if (hasBuildSettings(currentProject)
+ && !buildSettingsEnabled(currentProject).first)
enableDeployActionsContextMenu = false;
}
@@ -2929,45 +2741,11 @@ void ProjectExplorerPlugin::invalidateProject(Project *project)
{
if (debug)
qDebug() << "ProjectExplorerPlugin::invalidateProject" << project->displayName();
- if (dd->m_currentProject == project) {
- //
- // Workaround for a bug in QItemSelectionModel
- // - currentChanged etc are not emitted if the
- // item is removed from the underlying data model
- //
- dd->setCurrent(0, QString(), 0);
- }
disconnect(project, SIGNAL(fileListChanged()), this, SIGNAL(fileListChanged()));
updateActions();
}
-void ProjectExplorerPlugin::foldersAboutToBeRemoved(FolderNode *, const QList<FolderNode*> &list)
-{
- Node *n = ProjectExplorerPlugin::currentNode();
- while (n) {
- if (FolderNode *fn = qobject_cast<FolderNode *>(n)) {
- if (list.contains(fn)) {
- ProjectNode *pn = n->projectNode();
- // Make sure the node we are switching too isn't going to be removed also
- while (list.contains(pn))
- pn = pn->parentFolderNode()->projectNode();
- ProjectExplorerPlugin::setCurrentNode(pn);
- break;
- }
- }
- n = n->parentFolderNode();
- }
-}
-
-void ProjectExplorerPlugin::filesAboutToBeRemoved(FolderNode *, const QList<FileNode*> &list)
-{
- if (FileNode *fileNode = qobject_cast<FileNode *>(ProjectExplorerPlugin::currentNode())) {
- if (list.contains(fileNode))
- ProjectExplorerPlugin::setCurrentNode(fileNode->projectNode());
- }
-}
-
void ProjectExplorerPluginPrivate::updateContextMenuActions()
{
m_addExistingFilesAction->setEnabled(false);
@@ -2996,17 +2774,19 @@ void ProjectExplorerPluginPrivate::updateContextMenuActions()
runMenu->menu()->clear();
runMenu->menu()->menuAction()->setVisible(false);
- if (dd->m_currentNode && dd->m_currentNode->projectNode()) {
- QList<ProjectAction> actions = dd->m_currentNode->supportedActions(dd->m_currentNode);
+ Node *currentNode = ProjectTree::currentNode();
- if (ProjectNode *pn = qobject_cast<ProjectNode *>(dd->m_currentNode)) {
- if (pn == dd->m_currentProject->rootProjectNode()) {
- dd->m_runActionContextMenu->setVisible(true);
+ if (currentNode && currentNode->projectNode()) {
+ QList<ProjectAction> actions = currentNode->supportedActions(currentNode);
+
+ if (ProjectNode *pn = dynamic_cast<ProjectNode *>(currentNode)) {
+ if (ProjectTree::currentProject() && pn == ProjectTree::currentProject()->rootProjectNode()) {
+ m_runActionContextMenu->setVisible(true);
} else {
QList<RunConfiguration *> runConfigs = pn->runConfigurations();
if (runConfigs.count() == 1) {
- dd->m_runActionContextMenu->setVisible(true);
- dd->m_runActionContextMenu->setData(QVariant::fromValue(runConfigs.first()));
+ m_runActionContextMenu->setVisible(true);
+ m_runActionContextMenu->setData(QVariant::fromValue(runConfigs.first()));
} else if (runConfigs.count() > 1) {
runMenu->menu()->menuAction()->setVisible(true);
foreach (RunConfiguration *rc, runConfigs) {
@@ -3020,64 +2800,66 @@ void ProjectExplorerPluginPrivate::updateContextMenuActions()
}
}
}
- if (qobject_cast<FolderNode*>(dd->m_currentNode)) {
+ if (dynamic_cast<FolderNode*>(currentNode)) {
// Also handles ProjectNode
- dd->m_addNewFileAction->setEnabled(actions.contains(AddNewFile)
+ m_addNewFileAction->setEnabled(actions.contains(AddNewFile)
&& !ICore::isNewItemDialogRunning());
- dd->m_addNewSubprojectAction->setEnabled(dd->m_currentNode->nodeType() == ProjectNodeType
+ m_addNewSubprojectAction->setEnabled(currentNode->nodeType() == ProjectNodeType
&& actions.contains(AddSubProject)
&& !ICore::isNewItemDialogRunning());
- dd->m_removeProjectAction->setEnabled(dd->m_currentNode->nodeType() == ProjectNodeType
+ m_removeProjectAction->setEnabled(currentNode->nodeType() == ProjectNodeType
&& actions.contains(RemoveSubProject));
- dd->m_addExistingFilesAction->setEnabled(actions.contains(AddExistingFile));
- dd->m_addExistingDirectoryAction->setEnabled(actions.contains(AddExistingDirectory));
- dd->m_renameFileAction->setEnabled(actions.contains(Rename));
- } else if (qobject_cast<FileNode*>(dd->m_currentNode)) {
+ m_addExistingFilesAction->setEnabled(actions.contains(AddExistingFile));
+ m_addExistingDirectoryAction->setEnabled(actions.contains(AddExistingDirectory));
+ m_renameFileAction->setEnabled(actions.contains(Rename));
+ } else if (dynamic_cast<FileNode*>(currentNode)) {
// Enable and show remove / delete in magic ways:
// If both are disabled show Remove
// If both are enabled show both (can't happen atm)
// If only removeFile is enabled only show it
// If only deleteFile is enable only show it
bool enableRemove = actions.contains(RemoveFile);
- dd->m_removeFileAction->setEnabled(enableRemove);
+ m_removeFileAction->setEnabled(enableRemove);
bool enableDelete = actions.contains(EraseFile);
- dd->m_deleteFileAction->setEnabled(enableDelete);
- dd->m_deleteFileAction->setVisible(enableDelete);
+ m_deleteFileAction->setEnabled(enableDelete);
+ m_deleteFileAction->setVisible(enableDelete);
+
+ m_removeFileAction->setVisible(!enableDelete || enableRemove);
+ m_renameFileAction->setEnabled(actions.contains(Rename));
- dd->m_removeFileAction->setVisible(!enableDelete || enableRemove);
- dd->m_renameFileAction->setEnabled(actions.contains(Rename));
+ DocumentManager::populateOpenWithMenu(m_openWithMenu, ProjectTree::currentNode()->path());
}
if (actions.contains(HidePathActions)) {
- dd->m_openTerminalHere->setVisible(false);
- dd->m_showInGraphicalShell->setVisible(false);
- dd->m_searchOnFileSystem->setVisible(false);
+ m_openTerminalHere->setVisible(false);
+ m_showInGraphicalShell->setVisible(false);
+ m_searchOnFileSystem->setVisible(false);
}
if (actions.contains(HideFileActions)) {
- dd->m_deleteFileAction->setVisible(false);
- dd->m_removeFileAction->setVisible(false);
+ m_deleteFileAction->setVisible(false);
+ m_removeFileAction->setVisible(false);
}
if (actions.contains(HideFolderActions)) {
- dd->m_addNewFileAction->setVisible(false);
- dd->m_addNewSubprojectAction->setVisible(false);
- dd->m_removeProjectAction->setVisible(false);
- dd->m_addExistingFilesAction->setVisible(false);
- dd->m_addExistingDirectoryAction->setVisible(false);
+ m_addNewFileAction->setVisible(false);
+ m_addNewSubprojectAction->setVisible(false);
+ m_removeProjectAction->setVisible(false);
+ m_addExistingFilesAction->setVisible(false);
+ m_addExistingDirectoryAction->setVisible(false);
}
}
}
void ProjectExplorerPlugin::addNewFile()
{
- QTC_ASSERT(dd->m_currentNode, return);
- QString location = directoryFor(dd->m_currentNode);
+ QTC_ASSERT(ProjectTree::currentNode(), return);
+ QString location = directoryFor(ProjectTree::currentNode());
QVariantMap map;
- map.insert(QLatin1String(Constants::PREFERRED_PROJECT_NODE), QVariant::fromValue(dd->m_currentNode));
- if (dd->m_currentProject) {
- QList<Id> profileIds = Utils::transform(dd->m_currentProject->targets(), &Target::id);
+ map.insert(QLatin1String(Constants::PREFERRED_PROJECT_NODE), QVariant::fromValue(ProjectTree::currentNode()));
+ if (ProjectTree::currentProject()) {
+ QList<Id> profileIds = Utils::transform(ProjectTree::currentProject()->targets(), &Target::id);
map.insert(QLatin1String(Constants::PROJECT_KIT_IDS), QVariant::fromValue(profileIds));
}
ICore::showNewItemDialog(tr("New File", "Title of dialog"),
@@ -3088,16 +2870,17 @@ void ProjectExplorerPlugin::addNewFile()
void ProjectExplorerPlugin::addNewSubproject()
{
- QTC_ASSERT(dd->m_currentNode, return);
- QString location = directoryFor(dd->m_currentNode);
+ QTC_ASSERT(ProjectTree::currentNode(), return);
+ Node *currentNode = ProjectTree::currentNode();
+ QString location = directoryFor(currentNode);
- if (dd->m_currentNode->nodeType() == ProjectNodeType
- && dd->m_currentNode->supportedActions(
- dd->m_currentNode).contains(AddSubProject)) {
+ if (currentNode->nodeType() == ProjectNodeType
+ && currentNode->supportedActions(
+ currentNode).contains(AddSubProject)) {
QVariantMap map;
- map.insert(QLatin1String(Constants::PREFERRED_PROJECT_NODE), QVariant::fromValue(dd->m_currentNode));
- if (dd->m_currentProject) {
- QList<Id> profileIds = Utils::transform(dd->m_currentProject->targets(), &Target::id);
+ map.insert(QLatin1String(Constants::PREFERRED_PROJECT_NODE), QVariant::fromValue(currentNode));
+ if (ProjectTree::currentProject()) {
+ QList<Id> profileIds = Utils::transform(ProjectTree::currentProject()->targets(), &Target::id);
map.insert(QLatin1String(Constants::PROJECT_KIT_IDS), QVariant::fromValue(profileIds));
}
@@ -3109,10 +2892,10 @@ void ProjectExplorerPlugin::addNewSubproject()
void ProjectExplorerPlugin::addExistingFiles()
{
- QTC_ASSERT(dd->m_currentNode, return);
+ QTC_ASSERT(ProjectTree::currentNode(), return);
QStringList fileNames = QFileDialog::getOpenFileNames(ICore::mainWindow(),
- tr("Add Existing Files"), directoryFor(dd->m_currentNode));
+ tr("Add Existing Files"), directoryFor(ProjectTree::currentNode()));
if (fileNames.isEmpty())
return;
addExistingFiles(fileNames);
@@ -3120,9 +2903,9 @@ void ProjectExplorerPlugin::addExistingFiles()
void ProjectExplorerPlugin::addExistingDirectory()
{
- QTC_ASSERT(dd->m_currentNode, return);
+ QTC_ASSERT(ProjectTree::currentNode(), return);
- SelectableFilesDialogAddDirectory dialog(directoryFor(dd->m_currentNode), QStringList(), Core::ICore::mainWindow());
+ SelectableFilesDialogAddDirectory dialog(directoryFor(ProjectTree::currentNode()), QStringList(), ICore::mainWindow());
if (dialog.exec() == QDialog::Accepted)
addExistingFiles(dialog.selectedFiles());
@@ -3130,7 +2913,7 @@ void ProjectExplorerPlugin::addExistingDirectory()
void ProjectExplorerPlugin::addExistingFiles(const QStringList &filePaths)
{
- FolderNode *folderNode = qobject_cast<FolderNode *>(dd->m_currentNode);
+ FolderNode *folderNode = dynamic_cast<FolderNode *>(ProjectTree::currentNode());
addExistingFiles(folderNode, filePaths);
}
@@ -3159,8 +2942,8 @@ void ProjectExplorerPlugin::addExistingFiles(FolderNode *folderNode, const QStri
void ProjectExplorerPlugin::removeProject()
{
- ProjectNode *subProjectNode = qobject_cast<ProjectNode*>(dd->m_currentNode->projectNode());
- ProjectNode *projectNode = qobject_cast<ProjectNode *>(subProjectNode->parentFolderNode());
+ ProjectNode *subProjectNode = dynamic_cast<ProjectNode*>(ProjectTree::currentNode()->projectNode());
+ ProjectNode *projectNode = dynamic_cast<ProjectNode *>(subProjectNode->parentFolderNode());
if (projectNode) {
RemoveFileDialog removeFileDialog(subProjectNode->path(), ICore::mainWindow());
removeFileDialog.setDeleteFileVisible(false);
@@ -3171,35 +2954,36 @@ void ProjectExplorerPlugin::removeProject()
void ProjectExplorerPlugin::openFile()
{
- QTC_ASSERT(dd->m_currentNode, return);
- EditorManager::openEditor(dd->m_currentNode->path());
+ QTC_ASSERT(ProjectTree::currentNode(), return);
+ EditorManager::openEditor(ProjectTree::currentNode()->path());
}
void ProjectExplorerPlugin::searchOnFileSystem()
{
- QTC_ASSERT(dd->m_currentNode, return);
- TextEditor::FindInFiles::findOnFileSystem(pathFor(dd->m_currentNode));
+ QTC_ASSERT(ProjectTree::currentNode(), return);
+ TextEditor::FindInFiles::findOnFileSystem(pathFor(ProjectTree::currentNode()));
}
void ProjectExplorerPlugin::showInGraphicalShell()
{
- QTC_ASSERT(dd->m_currentNode, return);
- FileUtils::showInGraphicalShell(ICore::mainWindow(), pathFor(dd->m_currentNode));
+ QTC_ASSERT(ProjectTree::currentNode(), return);
+ FileUtils::showInGraphicalShell(ICore::mainWindow(), pathFor(ProjectTree::currentNode()));
}
void ProjectExplorerPlugin::openTerminalHere()
{
- QTC_ASSERT(dd->m_currentNode, return);
- FileUtils::openTerminal(directoryFor(dd->m_currentNode));
+ QTC_ASSERT(ProjectTree::currentNode(), return);
+ FileUtils::openTerminal(directoryFor(ProjectTree::currentNode()));
}
void ProjectExplorerPlugin::removeFile()
{
- QTC_ASSERT(dd->m_currentNode && dd->m_currentNode->nodeType() == FileNodeType, return);
+ Node *currentNode = ProjectTree::currentNode();
+ QTC_ASSERT(currentNode && currentNode->nodeType() == FileNodeType, return);
- FileNode *fileNode = qobject_cast<FileNode*>(dd->m_currentNode);
+ FileNode *fileNode = dynamic_cast<FileNode*>(currentNode);
- QString filePath = dd->m_currentNode->path();
+ QString filePath = currentNode->path();
RemoveFileDialog removeFileDialog(filePath, ICore::mainWindow());
if (removeFileDialog.exec() == QDialog::Accepted) {
@@ -3223,11 +3007,12 @@ void ProjectExplorerPlugin::removeFile()
void ProjectExplorerPlugin::deleteFile()
{
- QTC_ASSERT(dd->m_currentNode && dd->m_currentNode->nodeType() == FileNodeType, return);
+ Node *currentNode = ProjectTree::currentNode();
+ QTC_ASSERT(currentNode && currentNode->nodeType() == FileNodeType, return);
- FileNode *fileNode = qobject_cast<FileNode*>(dd->m_currentNode);
+ FileNode *fileNode = dynamic_cast<FileNode*>(currentNode);
- QString filePath = dd->m_currentNode->path();
+ QString filePath = currentNode->path();
QMessageBox::StandardButton button =
QMessageBox::question(ICore::mainWindow(),
tr("Delete File"),
@@ -3268,11 +3053,9 @@ void ProjectExplorerPlugin::renameFile()
}
}
-void ProjectExplorerPlugin::renameFile(Node *node, const QString &to)
+void ProjectExplorerPlugin::renameFile(Node *node, const QString &newFilePath)
{
QString orgFilePath = QFileInfo(node->path()).absoluteFilePath();
- QString dir = QFileInfo(orgFilePath).absolutePath();
- QString newFilePath = dir + QLatin1Char('/') + to;
if (FileUtils::renameFile(orgFilePath, newFilePath)) {
// Tell the project plugin about rename
@@ -3285,15 +3068,13 @@ void ProjectExplorerPlugin::renameFile(Node *node, const QString &to)
.arg(projectDisplayName);
QTimer::singleShot(0, m_instance, SLOT(showRenameFileError()));
- } else {
- dd->setCurrent(SessionManager::projectForFile(newFilePath), newFilePath, 0);
}
}
}
void ProjectExplorerPlugin::setStartupProject()
{
- setStartupProject(dd->m_currentProject);
+ setStartupProject(ProjectTree::currentProject());
}
void ProjectExplorerPlugin::showRenameFileError()
@@ -3301,11 +3082,6 @@ void ProjectExplorerPlugin::showRenameFileError()
QMessageBox::warning(ICore::mainWindow(), tr("Project Editing Failed"), dd->m_renameFileError);
}
-void ProjectExplorerPlugin::populateOpenWithMenu()
-{
- DocumentManager::populateOpenWithMenu(dd->m_openWithMenu, currentNode()->path());
-}
-
void ProjectExplorerPlugin::updateSessionMenu()
{
dd->m_sessionMenu->clear();
diff --git a/src/plugins/projectexplorer/projectexplorer.h b/src/plugins/projectexplorer/projectexplorer.h
index 3f030bc8f98..b1c17c633e5 100644
--- a/src/plugins/projectexplorer/projectexplorer.h
+++ b/src/plugins/projectexplorer/projectexplorer.h
@@ -76,12 +76,6 @@ public:
Q_SLOT void openProjectWelcomePage(const QString &fileName);
static void unloadProject(Project *project);
- static Project *currentProject();
- static Node *currentNode();
-
- static void setCurrentFile(Project *project, const QString &file);
- static void setCurrentNode(Node *node);
-
static bool saveModifiedFiles();
static void showContextMenu(QWidget *view, const QPoint &globalPos, Node *node);
@@ -98,7 +92,7 @@ public:
static void showRunErrorMessage(const QString &errorMessage);
// internal public for FlatModel
- static void renameFile(Node *node, const QString &to);
+ static void renameFile(Node *node, const QString &newFilePath);
static QStringList projectFilePatterns();
static bool coreAboutToClose();
static QList<QPair<QString, QString> > recentProjects();
@@ -123,18 +117,16 @@ public:
static QString directoryFor(Node *node);
static QStringList projectFileGlobs();
+ static void updateContextMenuActions();
+
signals:
void runControlStarted(ProjectExplorer::RunControl *rc);
void runControlFinished(ProjectExplorer::RunControl *rc);
- void aboutToShowContextMenu(ProjectExplorer::Project *project,
- ProjectExplorer::Node *node);
// Is emitted when a project has been added/removed,
// or the file list of a specific project has changed.
void fileListChanged();
- void currentProjectChanged(ProjectExplorer::Project *project);
- void currentNodeChanged(ProjectExplorer::Node *node, ProjectExplorer::Project *project);
void aboutToExecuteProject(ProjectExplorer::Project *project, RunMode runMode);
void recentProjectsChanged();
@@ -171,7 +163,6 @@ private slots:
void closeAllProjects();
void newProject();
void showSessionManager();
- void populateOpenWithMenu();
void updateSessionMenu();
void setSession(QAction *action);
@@ -204,12 +195,7 @@ private slots:
void updateUnloadProjectMenu();
void openTerminalHere();
- // for keeping current node / current project up to date
void invalidateProject(ProjectExplorer::Project *project);
- void foldersAboutToBeRemoved(FolderNode *, const QList<FolderNode*> &);
- void filesAboutToBeRemoved(FolderNode *, const QList<FileNode*> &);
-
- void setCurrentFile(const QString &filePath);
void runControlFinished();
@@ -226,10 +212,8 @@ private slots:
void loadCustomWizards();
void updateWelcomePage();
- void updateExternalFileWarning();
void updateActions();
- void updateContext();
void runConfigurationConfigurationFinished();
void showRenameFileError();
diff --git a/src/plugins/projectexplorer/projectexplorer.pro b/src/plugins/projectexplorer/projectexplorer.pro
index 195fa457375..e0c9ca9b9e5 100644
--- a/src/plugins/projectexplorer/projectexplorer.pro
+++ b/src/plugins/projectexplorer/projectexplorer.pro
@@ -147,12 +147,12 @@ HEADERS += projectexplorer.h \
customparserconfigdialog.h \
ipotentialkit.h \
selectablefilesmodel.h \
- addnewmodel.h \
xcodebuildparser.h \
propertiespanel.h \
panelswidget.h \
projectwelcomepage.h \
- projectpanelfactory.h
+ projectpanelfactory.h \
+ projecttree.h
SOURCES += projectexplorer.cpp \
abi.cpp \
@@ -285,12 +285,12 @@ SOURCES += projectexplorer.cpp \
customparserconfigdialog.cpp \
ipotentialkit.cpp \
selectablefilesmodel.cpp \
- addnewmodel.cpp \
xcodebuildparser.cpp \
propertiespanel.cpp \
panelswidget.cpp \
projectwelcomepage.cpp \
- projectpanelfactory.cpp
+ projectpanelfactory.cpp \
+ projecttree.cpp
FORMS += processstep.ui \
editorsettingspropertiespage.ui \
@@ -333,6 +333,13 @@ equals(TEST, 1) {
outputparser_test.h
}
+journald {
+ SOURCES += journaldwatcher.cpp
+ HEADERS += journaldwatcher.h
+ DEFINES += WITH_JOURNALD
+ LIBS += -lsystemd
+}
+
macx:LIBS += -framework Carbon
RESOURCES += projectexplorer.qrc
diff --git a/src/plugins/projectexplorer/projectexplorer.qbs b/src/plugins/projectexplorer/projectexplorer.qbs
index a7c62f689f5..1b328792c43 100644
--- a/src/plugins/projectexplorer/projectexplorer.qbs
+++ b/src/plugins/projectexplorer/projectexplorer.qbs
@@ -24,7 +24,6 @@ QtcPlugin {
"abi.cpp", "abi.h",
"abiwidget.cpp", "abiwidget.h",
"abstractprocessstep.cpp", "abstractprocessstep.h",
- "addnewmodel.cpp", "addnewmodel.h",
"allprojectsfilter.cpp", "allprojectsfilter.h",
"allprojectsfind.cpp", "allprojectsfind.h",
"ansifilterparser.cpp", "ansifilterparser.h",
@@ -120,6 +119,8 @@ QtcPlugin {
"projectmodels.cpp", "projectmodels.h",
"projectnodes.cpp", "projectnodes.h",
"projectpanelfactory.cpp", "projectpanelfactory.h",
+ "projecttree.cpp",
+ "projecttree.h",
"projecttreewidget.cpp", "projecttreewidget.h",
"projectwindow.cpp", "projectwindow.h",
"projectwizardpage.cpp", "projectwizardpage.h", "projectwizardpage.ui",
diff --git a/src/plugins/projectexplorer/projectexplorerconstants.h b/src/plugins/projectexplorer/projectexplorerconstants.h
index 68eaff76573..997a7483715 100644
--- a/src/plugins/projectexplorer/projectexplorerconstants.h
+++ b/src/plugins/projectexplorer/projectexplorerconstants.h
@@ -274,6 +274,7 @@ enum RunMode {
QmlProfilerRunMode,
CallgrindRunMode,
MemcheckRunMode,
+ MemcheckWithGdbRunMode,
ClangStaticAnalyzerMode
};
diff --git a/src/plugins/projectexplorer/projectmodels.cpp b/src/plugins/projectexplorer/projectmodels.cpp
index 3d46085e48f..e1654f897c4 100644
--- a/src/plugins/projectexplorer/projectmodels.cpp
+++ b/src/plugins/projectexplorer/projectmodels.cpp
@@ -33,6 +33,7 @@
#include "project.h"
#include "projectnodes.h"
#include "projectexplorer.h"
+#include "projecttree.h"
#include <coreplugin/fileiconprovider.h>
#include <utils/algorithm.h>
@@ -58,12 +59,12 @@ bool sortNodes(Node *n1, Node *n2)
const NodeType n2Type = n2->nodeType();
// project files
- FileNode *file1 = qobject_cast<FileNode*>(n1);
- FileNode *file2 = qobject_cast<FileNode*>(n2);
+ FileNode *file1 = dynamic_cast<FileNode*>(n1);
+ FileNode *file2 = dynamic_cast<FileNode*>(n2);
if (file1 && file1->fileType() == ProjectFileType) {
if (file2 && file2->fileType() == ProjectFileType) {
- const QString fileName1 = QFileInfo(file1->path()).fileName();
- const QString fileName2 = QFileInfo(file2->path()).fileName();
+ const QString fileName1 = Utils::FileName::fromString(file1->path()).fileName();
+ const QString fileName2 = Utils::FileName::fromString(file2->path()).fileName();
int result = caseFriendlyCompare(fileName1, fileName2);
if (result != 0)
@@ -148,8 +149,8 @@ bool sortNodes(Node *n1, Node *n2)
const QString filePath1 = n1->path();
const QString filePath2 = n2->path();
- const QString fileName1 = QFileInfo(filePath1).fileName();
- const QString fileName2 = QFileInfo(filePath2).fileName();
+ const QString fileName1 = Utils::FileName::fromString(filePath1).fileName();
+ const QString fileName2 = Utils::FileName::fromString(filePath2).fileName();
result = caseFriendlyCompare(fileName1, fileName2);
if (result != 0) {
@@ -177,42 +178,41 @@ FlatModel::FlatModel(SessionNode *rootNode, QObject *parent)
m_startupProject(0),
m_parentFolderForChange(0)
{
- NodesWatcher *watcher = new NodesWatcher(this);
- m_rootNode->registerWatcher(watcher);
+ ProjectTree *tree = ProjectTree::instance();
- connect(watcher, SIGNAL(aboutToChangeShowInSimpleTree(ProjectExplorer::FolderNode*)),
- this, SLOT(aboutToShowInSimpleTreeChanged(ProjectExplorer::FolderNode*)));
+ connect(tree, &ProjectTree::aboutToChangeShowInSimpleTree,
+ this, &FlatModel::aboutToShowInSimpleTreeChanged);
- connect(watcher, SIGNAL(showInSimpleTreeChanged(ProjectExplorer::FolderNode*)),
- this, SLOT(showInSimpleTreeChanged(ProjectExplorer::FolderNode*)));
+ connect(tree, &ProjectTree::showInSimpleTreeChanged,
+ this, &FlatModel::showInSimpleTreeChanged);
- connect(watcher, SIGNAL(foldersAboutToBeAdded(FolderNode*,QList<FolderNode*>)),
- this, SLOT(foldersAboutToBeAdded(FolderNode*,QList<FolderNode*>)));
- connect(watcher, SIGNAL(foldersAdded()),
- this, SLOT(foldersAdded()));
+ connect(tree, &ProjectTree::foldersAboutToBeAdded,
+ this, &FlatModel::foldersAboutToBeAdded);
+ connect(tree, &ProjectTree::foldersAdded,
+ this, &FlatModel::foldersAdded);
- connect(watcher, SIGNAL(foldersAboutToBeRemoved(FolderNode*,QList<FolderNode*>)),
- this, SLOT(foldersAboutToBeRemoved(FolderNode*,QList<FolderNode*>)));
- connect(watcher, SIGNAL(foldersRemoved()),
- this, SLOT(foldersRemoved()));
+ connect(tree, &ProjectTree::foldersAboutToBeRemoved,
+ this, &FlatModel::foldersAboutToBeRemoved);
+ connect(tree, &ProjectTree::foldersRemoved,
+ this, &FlatModel::foldersRemoved);
- connect(watcher, SIGNAL(filesAboutToBeAdded(FolderNode*,QList<FileNode*>)),
- this, SLOT(filesAboutToBeAdded(FolderNode*,QList<FileNode*>)));
- connect(watcher, SIGNAL(filesAdded()),
- this, SLOT(filesAdded()));
+ connect(tree, &ProjectTree::filesAboutToBeAdded,
+ this, &FlatModel::filesAboutToBeAdded);
+ connect(tree, &ProjectTree::filesAdded,
+ this, &FlatModel::filesAdded);
- connect(watcher, SIGNAL(filesAboutToBeRemoved(FolderNode*,QList<FileNode*>)),
- this, SLOT(filesAboutToBeRemoved(FolderNode*,QList<FileNode*>)));
- connect(watcher, SIGNAL(filesRemoved()),
- this, SLOT(filesRemoved()));
+ connect(tree, &ProjectTree::filesAboutToBeRemoved,
+ this, &FlatModel::filesAboutToBeRemoved);
+ connect(tree, &ProjectTree::filesRemoved,
+ this, &FlatModel::filesRemoved);
- connect(watcher, SIGNAL(nodeSortKeyAboutToChange(Node*)),
- this, SLOT(nodeSortKeyAboutToChange(Node*)));
- connect(watcher, SIGNAL(nodeSortKeyChanged()),
- this, SLOT(nodeSortKeyChanged()));
+ connect(tree, &ProjectTree::nodeSortKeyAboutToChange,
+ this, &FlatModel::nodeSortKeyAboutToChange);
+ connect(tree, &ProjectTree::nodeSortKeyChanged,
+ this, &FlatModel::nodeSortKeyChanged);
- connect(watcher, SIGNAL(nodeUpdated(ProjectExplorer::Node*)),
- this, SLOT(nodeUpdated(ProjectExplorer::Node*)));
+ connect(tree, &ProjectTree::nodeUpdated,
+ this, &FlatModel::nodeUpdated);
}
QModelIndex FlatModel::index(int row, int column, const QModelIndex &parent) const
@@ -221,7 +221,7 @@ QModelIndex FlatModel::index(int row, int column, const QModelIndex &parent) con
if (!parent.isValid() && row == 0 && column == 0) { // session
result = createIndex(0, 0, m_rootNode);
} else if (parent.isValid() && column == 0) {
- FolderNode *parentNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
+ FolderNode *parentNode = dynamic_cast<FolderNode*>(nodeForIndex(parent));
Q_ASSERT(parentNode);
QHash<FolderNode*, QList<Node*> >::const_iterator it = m_childNodes.constFind(parentNode);
if (it == m_childNodes.constEnd()) {
@@ -270,7 +270,7 @@ QVariant FlatModel::data(const QModelIndex &index, int role) const
QVariant result;
if (Node *node = nodeForIndex(index)) {
- FolderNode *folderNode = qobject_cast<FolderNode*>(node);
+ FolderNode *folderNode = dynamic_cast<FolderNode*>(node);
switch (role) {
case Qt::DisplayRole: {
QString name = node->displayName();
@@ -288,7 +288,7 @@ QVariant FlatModel::data(const QModelIndex &index, int role) const
break;
}
case Qt::EditRole: {
- result = QFileInfo(node->path()).fileName();
+ result = Utils::FileName::fromString(node->path()).fileName();
break;
}
case Qt::ToolTipRole: {
@@ -334,11 +334,11 @@ Qt::ItemFlags FlatModel::flags(const QModelIndex &index) const
if (Node *node = nodeForIndex(index)) {
if (node == m_rootNode)
return 0; // no flags for session node...
- if (!qobject_cast<ProjectNode *>(node)) {
+ if (!dynamic_cast<ProjectNode *>(node)) {
// either folder or file node
if (node->supportedActions(node).contains(Rename))
f = f | Qt::ItemIsEditable;
- if (qobject_cast<FileNode *>(node))
+ if (dynamic_cast<FileNode *>(node))
f = f | Qt::ItemIsDragEnabled;
}
}
@@ -352,7 +352,14 @@ bool FlatModel::setData(const QModelIndex &index, const QVariant &value, int rol
if (role != Qt::EditRole)
return false;
- ProjectExplorerPlugin::renameFile(nodeForIndex(index), value.toString());
+ Node *node = nodeForIndex(index);
+
+ QString orgFilePath = QFileInfo(node->path()).absoluteFilePath();
+ QString dir = QFileInfo(orgFilePath).absolutePath();
+ QString newFilePath = dir + QLatin1Char('/') + value.toString();
+
+ ProjectExplorerPlugin::renameFile(node, newFilePath);
+ emit renamed(orgFilePath, newFilePath);
return true;
}
@@ -362,7 +369,7 @@ int FlatModel::rowCount(const QModelIndex &parent) const
if (!parent.isValid()) {
rows = 1;
} else {
- FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
+ FolderNode *folderNode = dynamic_cast<FolderNode*>(nodeForIndex(parent));
if (folderNode && m_childNodes.contains(folderNode))
rows = m_childNodes.value(folderNode).size();
}
@@ -379,7 +386,7 @@ bool FlatModel::hasChildren(const QModelIndex &parent) const
if (!parent.isValid())
return true;
- FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
+ FolderNode *folderNode = dynamic_cast<FolderNode*>(nodeForIndex(parent));
if (!folderNode)
return false;
@@ -396,7 +403,7 @@ bool FlatModel::canFetchMore(const QModelIndex & parent) const
if (!parent.isValid()) {
return false;
} else {
- if (FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent)))
+ if (FolderNode *folderNode = dynamic_cast<FolderNode*>(nodeForIndex(parent)))
return !m_childNodes.contains(folderNode);
else
return false;
@@ -466,7 +473,7 @@ void FlatModel::fetchMore(FolderNode *folderNode) const
void FlatModel::fetchMore(const QModelIndex &parent)
{
- FolderNode *folderNode = qobject_cast<FolderNode*>(nodeForIndex(parent));
+ FolderNode *folderNode = dynamic_cast<FolderNode*>(nodeForIndex(parent));
Q_ASSERT(folderNode);
fetchMore(folderNode);
@@ -507,7 +514,7 @@ QMimeData *FlatModel::mimeData(const QModelIndexList &indexes) const
auto data = new Utils::FileDropMimeData;
foreach (const QModelIndex &index, indexes) {
Node *node = nodeForIndex(index);
- if (qobject_cast<FileNode *>(node))
+ if (dynamic_cast<FileNode *>(node))
data->addFile(node->path());
}
return data;
@@ -594,10 +601,10 @@ FolderNode *FlatModel::visibleFolderNode(FolderNode *node) const
bool FlatModel::filter(Node *node) const
{
bool isHidden = false;
- if (FolderNode *folderNode = qobject_cast<FolderNode*>(node)) {
+ if (FolderNode *folderNode = dynamic_cast<FolderNode*>(node)) {
if (m_filterProjects)
isHidden = !folderNode->showInSimpleTree();
- } else if (FileNode *fileNode = qobject_cast<FileNode*>(node)) {
+ } else if (FileNode *fileNode = dynamic_cast<FileNode*>(node)) {
if (m_filterGeneratedFiles)
isHidden = fileNode->isGenerated();
}
@@ -796,7 +803,7 @@ void FlatModel::aboutToShowInSimpleTreeChanged(FolderNode* node)
QList<Node *> staleFolders;
recursiveAddFolderNodesImpl(node, &staleFolders);
foreach (Node *n, staleFolders)
- if (FolderNode *fn = qobject_cast<FolderNode *>(n))
+ if (FolderNode *fn = dynamic_cast<FolderNode *>(n))
m_childNodes.remove(fn);
}
diff --git a/src/plugins/projectexplorer/projectmodels.h b/src/plugins/projectexplorer/projectmodels.h
index 6bc073cc85f..b72ac015fa2 100644
--- a/src/plugins/projectexplorer/projectmodels.h
+++ b/src/plugins/projectexplorer/projectmodels.h
@@ -78,6 +78,9 @@ public:
bool projectFilterEnabled();
bool generatedFilesFilterEnabled();
+signals:
+ void renamed(const QString &oldName, const QString &newName);
+
public slots:
void setProjectFilterEnabled(bool filter);
void setGeneratedFilesFilterEnabled(bool filter);
diff --git a/src/plugins/projectexplorer/projectnodes.cpp b/src/plugins/projectexplorer/projectnodes.cpp
index d40acd1a68e..9255261f877 100644
--- a/src/plugins/projectexplorer/projectnodes.cpp
+++ b/src/plugins/projectexplorer/projectnodes.cpp
@@ -32,6 +32,7 @@
#include "nodesvisitor.h"
#include "projectexplorerconstants.h"
+#include "projecttree.h"
#include <coreplugin/mimedatabase.h>
#include <coreplugin/fileiconprovider.h>
@@ -39,6 +40,7 @@
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
#include <utils/algorithm.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
@@ -65,30 +67,30 @@ using namespace ProjectExplorer;
Node::Node(NodeType nodeType,
const QString &filePath, int line)
- : QObject(),
- m_nodeType(nodeType),
+ : m_nodeType(nodeType),
+ m_line(line),
m_projectNode(0),
m_folderNode(0),
- m_path(filePath),
- m_line(line)
+ m_path(filePath)
+{
+
+}
+
+Node::~Node()
{
}
void Node::emitNodeSortKeyAboutToChange()
{
- if (ProjectNode *project = projectNode()) {
- foreach (NodesWatcher *watcher, project->watchers())
- emit watcher->nodeSortKeyAboutToChange(this);
- }
+ if (parentFolderNode())
+ ProjectTree::instance()->emitNodeSortKeyAboutToChange(this);
}
void Node::emitNodeSortKeyChanged()
{
- if (ProjectNode *project = projectNode()) {
- foreach (NodesWatcher *watcher, project->watchers())
- emit watcher->nodeSortKeyChanged();
- }
+ if (parentFolderNode())
+ ProjectTree::instance()->emitNodeSortKeyChanged(this);
}
/*!
@@ -167,7 +169,7 @@ int Node::line() const
QString Node::displayName() const
{
- return QFileInfo(path()).fileName();
+ return Utils::FileName::fromString(path()).fileName();
}
QString Node::tooltip() const
@@ -183,7 +185,7 @@ bool Node::isEnabled() const
QList<ProjectAction> Node::supportedActions(Node *node) const
{
QList<ProjectAction> list = parentFolderNode()->supportedActions(node);
- list.append(ProjectExplorer::InheritedFromParent);
+ list.append(InheritedFromParent);
return list;
}
@@ -199,9 +201,8 @@ void Node::setProjectNode(ProjectNode *project)
void Node::emitNodeUpdated()
{
- if (ProjectNode *node = projectNode())
- foreach (NodesWatcher *watcher, node->watchers())
- emit watcher->nodeUpdated(this);
+ if (parentFolderNode())
+ ProjectTree::instance()->emitNodeUpdated(this);
}
void Node::setParentFolderNode(FolderNode *parentFolder)
@@ -348,7 +349,7 @@ bool FolderNode::renameFile(const QString &filePath, const QString &newFilePath)
FolderNode::AddNewInformation FolderNode::addNewInformation(const QStringList &files, Node *context) const
{
Q_UNUSED(files);
- return AddNewInformation(QFileInfo(path()).fileName(), context == this ? 120 : 100);
+ return AddNewInformation(Utils::FileName::fromString(path()).fileName(), context == this ? 120 : 100);
}
/*!
@@ -362,19 +363,17 @@ FolderNode::AddNewInformation FolderNode::addNewInformation(const QStringList &f
void FolderNode::addFileNodes(const QList<FileNode *> &files)
{
Q_ASSERT(projectNode());
- ProjectNode *pn = projectNode();
if (files.isEmpty())
return;
- foreach (NodesWatcher *watcher, pn->watchers())
- emit watcher->filesAboutToBeAdded(this, files);
+ ProjectTree::instance()->emitFilesAboutToBeAdded(this, files);
foreach (FileNode *file, files) {
QTC_ASSERT(!file->parentFolderNode(),
qDebug("File node has already a parent folder"));
file->setParentFolderNode(this);
- file->setProjectNode(pn);
+ file->setProjectNode(projectNode());
// Now find the correct place to insert file
if (m_fileNodes.count() == 0
|| m_fileNodes.last() < file) {
@@ -389,8 +388,7 @@ void FolderNode::addFileNodes(const QList<FileNode *> &files)
}
}
- foreach (NodesWatcher *watcher, pn->watchers())
- emit watcher->filesAdded();
+ ProjectTree::instance()->emitFilesAdded(this);
}
/*!
@@ -404,7 +402,6 @@ void FolderNode::addFileNodes(const QList<FileNode *> &files)
void FolderNode::removeFileNodes(const QList<FileNode *> &files)
{
Q_ASSERT(projectNode());
- ProjectNode *pn = projectNode();
if (files.isEmpty())
return;
@@ -412,8 +409,7 @@ void FolderNode::removeFileNodes(const QList<FileNode *> &files)
QList<FileNode*> toRemove = files;
Utils::sort(toRemove);
- foreach (NodesWatcher *watcher, pn->watchers())
- emit watcher->filesAboutToBeRemoved(this, toRemove);
+ ProjectTree::instance()->emitFilesAboutToBeRemoved(this, toRemove);
QList<FileNode*>::const_iterator toRemoveIter = toRemove.constBegin();
QList<FileNode*>::iterator filesIter = m_fileNodes.begin();
@@ -427,8 +423,7 @@ void FolderNode::removeFileNodes(const QList<FileNode *> &files)
filesIter = m_fileNodes.erase(filesIter);
}
- foreach (NodesWatcher *watcher, pn->watchers())
- emit watcher->filesRemoved();
+ ProjectTree::instance()->emitFilesRemoved(this);
}
/*!
@@ -438,19 +433,16 @@ void FolderNode::removeFileNodes(const QList<FileNode *> &files)
void FolderNode::addFolderNodes(const QList<FolderNode*> &subFolders)
{
Q_ASSERT(projectNode());
- ProjectNode *pn = projectNode();
if (subFolders.isEmpty())
return;
- foreach (NodesWatcher *watcher, pn->watchers())
- watcher->foldersAboutToBeAdded(this, subFolders);
-
+ ProjectTree::instance()->emitFoldersAboutToBeAdded(this, subFolders);
foreach (FolderNode *folder, subFolders) {
QTC_ASSERT(!folder->parentFolderNode(),
qDebug("Project node has already a parent folder"));
folder->setParentFolderNode(this);
- folder->setProjectNode(pn);
+ folder->setProjectNode(projectNode());
// Find the correct place to insert
if (m_subFolderNodes.count() == 0
@@ -471,8 +463,7 @@ void FolderNode::addFolderNodes(const QList<FolderNode*> &subFolders)
qDebug("project nodes have to be added via addProjectNodes"));
}
- foreach (NodesWatcher *watcher, pn->watchers())
- emit watcher->foldersAdded();
+ ProjectTree::instance()->emitFoldersAdded(this);
}
/*!
@@ -484,7 +475,6 @@ void FolderNode::addFolderNodes(const QList<FolderNode*> &subFolders)
void FolderNode::removeFolderNodes(const QList<FolderNode*> &subFolders)
{
Q_ASSERT(projectNode());
- ProjectNode *pn = projectNode();
if (subFolders.isEmpty())
return;
@@ -492,8 +482,7 @@ void FolderNode::removeFolderNodes(const QList<FolderNode*> &subFolders)
QList<FolderNode*> toRemove = subFolders;
Utils::sort(toRemove);
- foreach (NodesWatcher *watcher, pn->watchers())
- emit watcher->foldersAboutToBeRemoved(this, toRemove);
+ ProjectTree::instance()->emitFoldersAboutToBeRemoved(this, toRemove);
QList<FolderNode*>::const_iterator toRemoveIter = toRemove.constBegin();
QList<FolderNode*>::iterator folderIter = m_subFolderNodes.begin();
@@ -509,20 +498,7 @@ void FolderNode::removeFolderNodes(const QList<FolderNode*> &subFolders)
folderIter = m_subFolderNodes.erase(folderIter);
}
- foreach (NodesWatcher *watcher, pn->watchers())
- emit watcher->foldersRemoved();
-}
-
-void FolderNode::aboutToChangeShowInSimpleTree()
-{
- foreach (NodesWatcher *watcher, projectNode()->watchers())
- emit watcher->aboutToChangeShowInSimpleTree(this);
-}
-
-void FolderNode::showInSimpleTreeChanged()
-{
- foreach (NodesWatcher *watcher, projectNode()->watchers())
- emit watcher->showInSimpleTreeChanged(this);
+ ProjectTree::instance()->emitFoldersRemoved(this);
}
bool FolderNode::showInSimpleTree() const
@@ -574,7 +550,7 @@ ProjectNode::ProjectNode(const QString &projectFilePath)
setNodeType(ProjectNodeType);
// project node "manages" itself
setProjectNode(this);
- setDisplayName(QFileInfo(projectFilePath).fileName());
+ setDisplayName(Utils::FileName::fromString(projectFilePath).fileName());
}
QString ProjectNode::vcsTopic() const
@@ -629,40 +605,6 @@ QList<RunConfiguration *> ProjectNode::runConfigurations() const
return QList<RunConfiguration *>();
}
-QList<NodesWatcher*> ProjectNode::watchers() const
-{
- return m_watchers;
-}
-
-/*!
- Registers \a watcher for the current project and all subprojects.
-
- It does not take ownership of the watcher.
-*/
-
-void ProjectNode::registerWatcher(NodesWatcher *watcher)
-{
- if (!watcher)
- return;
- connect(watcher, SIGNAL(destroyed(QObject*)),
- this, SLOT(watcherDestroyed(QObject*)));
- m_watchers.append(watcher);
- foreach (ProjectNode *subProject, m_subProjectNodes)
- subProject->registerWatcher(watcher);
-}
-
-/*!
- Removes \a watcher from the current project and all subprojects.
-*/
-void ProjectNode::unregisterWatcher(NodesWatcher *watcher)
-{
- if (!watcher)
- return;
- m_watchers.removeOne(watcher);
- foreach (ProjectNode *subProject, m_subProjectNodes)
- subProject->unregisterWatcher(watcher);
-}
-
void ProjectNode::accept(NodesVisitor *visitor)
{
visitor->visitProjectNode(this);
@@ -682,23 +624,19 @@ void ProjectNode::addProjectNodes(const QList<ProjectNode*> &subProjects)
foreach (ProjectNode *projectNode, subProjects)
folderNodes << projectNode;
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersAboutToBeAdded(this, folderNodes);
+ ProjectTree::instance()->emitFoldersAboutToBeAdded(this, folderNodes);
foreach (ProjectNode *project, subProjects) {
QTC_ASSERT(!project->parentFolderNode() || project->parentFolderNode() == this,
qDebug("Project node has already a parent"));
project->setParentFolderNode(this);
- foreach (NodesWatcher *watcher, m_watchers)
- project->registerWatcher(watcher);
m_subFolderNodes.append(project);
m_subProjectNodes.append(project);
}
Utils::sort(m_subFolderNodes);
Utils::sort(m_subProjectNodes);
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersAdded();
+ ProjectTree::instance()->emitFoldersAdded(this);
}
}
@@ -717,8 +655,7 @@ void ProjectNode::removeProjectNodes(const QList<ProjectNode*> &subProjects)
toRemove << projectNode;
Utils::sort(toRemove);
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersAboutToBeRemoved(this, toRemove);
+ ProjectTree::instance()->emitFoldersAboutToBeRemoved(this, toRemove);
QList<FolderNode*>::const_iterator toRemoveIter = toRemove.constBegin();
QList<FolderNode*>::iterator folderIter = m_subFolderNodes.begin();
@@ -739,26 +676,18 @@ void ProjectNode::removeProjectNodes(const QList<ProjectNode*> &subProjects)
folderIter = m_subFolderNodes.erase(folderIter);
}
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersRemoved();
+ ProjectTree::instance()->emitFoldersRemoved(this);
}
}
-void ProjectNode::watcherDestroyed(QObject *watcher)
-{
- // cannot use qobject_cast here
- unregisterWatcher(static_cast<NodesWatcher*>(watcher));
-}
-
/*!
\class ProjectExplorer::SessionNode
*/
-SessionNode::SessionNode(QObject *parentObject)
+SessionNode::SessionNode()
: FolderNode(QLatin1String("session"))
{
- setParent(parentObject);
setNodeType(SessionNodeType);
}
@@ -768,39 +697,6 @@ QList<ProjectAction> SessionNode::supportedActions(Node *node) const
return QList<ProjectAction>();
}
-QList<NodesWatcher*> SessionNode::watchers() const
-{
- return m_watchers;
-}
-
-/*!
- Registers \a watcher for the complete session tree.
- It does not take ownership of the watcher.
-*/
-
-void SessionNode::registerWatcher(NodesWatcher *watcher)
-{
- if (!watcher)
- return;
- connect(watcher, SIGNAL(destroyed(QObject*)),
- this, SLOT(watcherDestroyed(QObject*)));
- m_watchers.append(watcher);
- foreach (ProjectNode *project, m_projectNodes)
- project->registerWatcher(watcher);
-}
-
-/*!
- Removes \a watcher from the complete session tree.
-*/
-
-void SessionNode::unregisterWatcher(NodesWatcher *watcher)
-{
- if (!watcher)
- return;
- m_watchers.removeOne(watcher);
- foreach (ProjectNode *project, m_projectNodes)
- project->unregisterWatcher(watcher);
-}
void SessionNode::accept(NodesVisitor *visitor)
{
@@ -816,10 +712,8 @@ bool SessionNode::showInSimpleTree() const
void SessionNode::projectDisplayNameChanged(Node *node)
{
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->nodeSortKeyAboutToChange(node);
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->nodeSortKeyChanged();
+ ProjectTree::instance()->emitNodeSortKeyAboutToChange(node);
+ ProjectTree::instance()->emitNodeSortKeyChanged(node);
}
QList<ProjectNode*> SessionNode::projectNodes() const
@@ -834,15 +728,12 @@ void SessionNode::addProjectNodes(const QList<ProjectNode*> &projectNodes)
foreach (ProjectNode *projectNode, projectNodes)
folderNodes << projectNode;
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersAboutToBeAdded(this, folderNodes);
+ ProjectTree::instance()->emitFoldersAboutToBeAdded(this, folderNodes);
foreach (ProjectNode *project, projectNodes) {
QTC_ASSERT(!project->parentFolderNode(),
qDebug("Project node has already a parent folder"));
project->setParentFolderNode(this);
- foreach (NodesWatcher *watcher, m_watchers)
- project->registerWatcher(watcher);
m_subFolderNodes.append(project);
m_projectNodes.append(project);
}
@@ -850,8 +741,7 @@ void SessionNode::addProjectNodes(const QList<ProjectNode*> &projectNodes)
Utils::sort(m_subFolderNodes);
Utils::sort(m_projectNodes);
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersAdded();
+ ProjectTree::instance()->emitFoldersAdded(this);
}
}
@@ -864,8 +754,7 @@ void SessionNode::removeProjectNodes(const QList<ProjectNode*> &projectNodes)
Utils::sort(toRemove);
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersAboutToBeRemoved(this, toRemove);
+ ProjectTree::instance()->emitFoldersAboutToBeRemoved(this, toRemove);
QList<FolderNode*>::const_iterator toRemoveIter = toRemove.constBegin();
QList<FolderNode*>::iterator folderIter = m_subFolderNodes.begin();
@@ -885,38 +774,6 @@ void SessionNode::removeProjectNodes(const QList<ProjectNode*> &projectNodes)
folderIter = m_subFolderNodes.erase(folderIter);
}
- foreach (NodesWatcher *watcher, m_watchers)
- emit watcher->foldersRemoved();
+ ProjectTree::instance()->emitFoldersRemoved(this);
}
}
-
-void SessionNode::watcherDestroyed(QObject *watcher)
-{
- // cannot use qobject_cast here
- unregisterWatcher(static_cast<NodesWatcher*>(watcher));
-}
-
-/*!
- \class ProjectExplorer::NodesWatcher
-
- \brief The NodesWatcher class enables you to keep track of changes in the
- tree.
-
- Add a watcher by calling ProjectNode::registerWatcher() or
- SessionNode::registerWatcher(). Whenever the tree underneath the
- project node or session node changes (for example, nodes are added or removed),
- the corresponding signals of the watcher are emitted.
- Watchers can be removed from the complete tree or a subtree
- by calling ProjectNode::unregisterWatcher and
- SessionNode::unregisterWatcher().
-
- The NodesWatcher class is similar to the Observer class in the
- well-known Observer pattern (Booch et al).
-
- \sa ProjectExplorer::Node
-*/
-
-NodesWatcher::NodesWatcher(QObject *parent)
- : QObject(parent)
-{
-}
diff --git a/src/plugins/projectexplorer/projectnodes.h b/src/plugins/projectexplorer/projectnodes.h
index 8389754257a..0cb6b3e6a07 100644
--- a/src/plugins/projectexplorer/projectnodes.h
+++ b/src/plugins/projectexplorer/projectnodes.h
@@ -100,14 +100,14 @@ class FileNode;
class FileContainerNode;
class FolderNode;
class ProjectNode;
-class NodesWatcher;
class NodesVisitor;
class SessionManager;
// Documentation inside.
-class PROJECTEXPLORER_EXPORT Node : public QObject {
- Q_OBJECT
+class PROJECTEXPLORER_EXPORT Node
+{
public:
+ virtual ~Node();
NodeType nodeType() const;
ProjectNode *projectNode() const; // managing project
FolderNode *parentFolderNode() const; // parent folder or project
@@ -136,14 +136,14 @@ protected:
private:
NodeType m_nodeType;
+ int m_line;
ProjectNode *m_projectNode;
FolderNode *m_folderNode;
QString m_path;
- int m_line;
};
-class PROJECTEXPLORER_EXPORT FileNode : public Node {
- Q_OBJECT
+class PROJECTEXPLORER_EXPORT FileNode : public Node
+{
public:
FileNode(const QString &filePath, const FileType fileType, bool generated, int line = -1);
@@ -160,8 +160,8 @@ private:
};
// Documentation inside.
-class PROJECTEXPLORER_EXPORT FolderNode : public Node {
- Q_OBJECT
+class PROJECTEXPLORER_EXPORT FolderNode : public Node
+{
public:
explicit FolderNode(const QString &folderPath, NodeType nodeType = FolderNodeType,
const QString &displayName = QString());
@@ -197,8 +197,6 @@ public:
// determines if node will be shown in the flat view, by default folder and projects aren't shown
- void aboutToChangeShowInSimpleTree();
- void showInSimpleTreeChanged();
virtual bool showInSimpleTree() const;
void addFileNodes(const QList<FileNode*> &files);
@@ -221,7 +219,6 @@ private:
class PROJECTEXPLORER_EXPORT VirtualFolderNode : public FolderNode
{
- Q_OBJECT
public:
explicit VirtualFolderNode(const QString &folderPath, int priority);
virtual ~VirtualFolderNode();
@@ -234,8 +231,6 @@ private:
// Documentation inside.
class PROJECTEXPLORER_EXPORT ProjectNode : public FolderNode
{
- Q_OBJECT
-
public:
QString vcsTopic() const;
@@ -253,11 +248,6 @@ public:
virtual QList<RunConfiguration *> runConfigurations() const;
-
- QList<NodesWatcher*> watchers() const;
- void registerWatcher(NodesWatcher *watcher);
- void unregisterWatcher(NodesWatcher *watcher);
-
void accept(NodesVisitor *visitor);
bool isEnabled() const { return true; }
@@ -272,32 +262,24 @@ protected:
// will add the persistent stuff
explicit ProjectNode(const QString &projectFilePath);
-private slots:
- void watcherDestroyed(QObject *watcher);
-
private:
QList<ProjectNode*> m_subProjectNodes;
- QList<NodesWatcher*> m_watchers;
// let SessionNode call setParentFolderNode
friend class SessionNode;
};
// Documentation inside.
-class PROJECTEXPLORER_EXPORT SessionNode : public FolderNode {
- Q_OBJECT
+class PROJECTEXPLORER_EXPORT SessionNode : public FolderNode
+{
friend class SessionManager;
public:
- SessionNode(QObject *parentObject);
+ SessionNode();
QList<ProjectAction> supportedActions(Node *node) const;
QList<ProjectNode*> projectNodes() const;
- QList<NodesWatcher*> watchers() const;
- void registerWatcher(NodesWatcher *watcher);
- void unregisterWatcher(NodesWatcher *watcher);
-
void accept(NodesVisitor *visitor);
bool isEnabled() const { return true; }
@@ -308,57 +290,8 @@ protected:
void addProjectNodes(const QList<ProjectNode*> &projectNodes);
void removeProjectNodes(const QList<ProjectNode*> &projectNodes);
-private slots:
- void watcherDestroyed(QObject *watcher);
-
private:
QList<ProjectNode*> m_projectNodes;
- QList<NodesWatcher*> m_watchers;
-};
-
-// Documentation inside.
-class PROJECTEXPLORER_EXPORT NodesWatcher : public QObject {
- Q_OBJECT
-public:
- explicit NodesWatcher(QObject *parent = 0);
-
-signals:
- // everything
-
- // Emitted whenever the model needs to send a update signal.
- void nodeUpdated(ProjectExplorer::Node *node);
-
- // projects
- void aboutToChangeShowInSimpleTree(ProjectExplorer::FolderNode*);
- void showInSimpleTreeChanged(ProjectExplorer::FolderNode *node);
-
- // folders & projects
- void foldersAboutToBeAdded(FolderNode *parentFolder,
- const QList<FolderNode*> &newFolders);
- void foldersAdded();
-
- void foldersAboutToBeRemoved(FolderNode *parentFolder,
- const QList<FolderNode*> &staleFolders);
- void foldersRemoved();
-
- // files
- void filesAboutToBeAdded(FolderNode *folder,
- const QList<FileNode*> &newFiles);
- void filesAdded();
-
- void filesAboutToBeRemoved(FolderNode *folder,
- const QList<FileNode*> &staleFiles);
- void filesRemoved();
- void nodeSortKeyAboutToChange(Node *node);
- void nodeSortKeyChanged();
-
-private:
-
- // let project & session emit signals
- friend class ProjectNode;
- friend class FolderNode;
- friend class SessionNode;
- friend class Node;
};
template<class T1, class T3>
@@ -460,5 +393,6 @@ T1 subtractSortedList(T1 list1, T1 list2, T3 sorter)
} // namespace ProjectExplorer
Q_DECLARE_METATYPE(ProjectExplorer::Node *)
+Q_DECLARE_METATYPE(ProjectExplorer::FolderNode *)
#endif // PROJECTNODES_H
diff --git a/src/plugins/projectexplorer/projecttree.cpp b/src/plugins/projectexplorer/projecttree.cpp
new file mode 100644
index 00000000000..1fc8c525ba1
--- /dev/null
+++ b/src/plugins/projectexplorer/projecttree.cpp
@@ -0,0 +1,505 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "projecttree.h"
+#include "projecttreewidget.h"
+#include "session.h"
+#include "project.h"
+#include "projectnodes.h"
+#include "projectexplorerconstants.h"
+
+#include <utils/algorithm.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/editormanager/ieditor.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/infobar.h>
+#include <coreplugin/vcsmanager.h>
+#include <coreplugin/actionmanager/actioncontainer.h>
+#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/documentmanager.h>
+
+#include <QApplication>
+#include <QTimer>
+
+namespace {
+const char EXTERNAL_FILE_WARNING[] = "ExternalFile";
+}
+
+using namespace Utils;
+
+namespace ProjectExplorer {
+
+using namespace Internal;
+
+ProjectTree *ProjectTree::s_instance = 0;
+
+ProjectTree::ProjectTree(QObject *parent)
+ : QObject(parent),
+ m_currentNode(0),
+ m_currentProject(0),
+ m_resetCurrentNodeFolder(false),
+ m_resetCurrentNodeFile(false),
+ m_resetCurrentNodeProject(false),
+ m_focusForContextMenu(0)
+{
+ s_instance = this;
+
+ connect(Core::EditorManager::instance(), &Core::EditorManager::currentEditorChanged,
+ this, &ProjectTree::documentManagerCurrentFileChanged);
+
+ connect(qApp, &QApplication::focusChanged,
+ this, &ProjectTree::focusChanged);
+
+ connect(SessionManager::instance(), &SessionManager::projectAdded,
+ this, &ProjectTree::updateDefaultLocationForNewFiles);
+ connect(SessionManager::instance(), &SessionManager::projectRemoved,
+ this, &ProjectTree::updateDefaultLocationForNewFiles);
+ connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
+ this, &ProjectTree::updateDefaultLocationForNewFiles);
+}
+
+void ProjectTree::aboutToShutDown()
+{
+ disconnect(qApp, &QApplication::focusChanged,
+ s_instance, &ProjectTree::focusChanged);
+ s_instance->update(0, 0);
+}
+
+ProjectTree *ProjectTree::instance()
+{
+ return s_instance;
+}
+
+Project *ProjectTree::currentProject()
+{
+ return s_instance->m_currentProject;
+}
+
+Node *ProjectTree::currentNode()
+{
+ return s_instance->m_currentNode;
+}
+
+void ProjectTree::registerWidget(ProjectTreeWidget *widget)
+{
+ s_instance->m_projectTreeWidgets.append(widget);
+ if (hasFocus(widget))
+ s_instance->updateFromProjectTreeWidget(widget);
+}
+
+void ProjectTree::unregisterWidget(ProjectTreeWidget *widget)
+{
+ s_instance->m_projectTreeWidgets.removeOne(widget);
+ if (hasFocus(widget))
+ s_instance->updateFromDocumentManager();
+}
+
+void ProjectTree::nodeChanged(ProjectTreeWidget *widget)
+{
+ if (hasFocus(widget))
+ s_instance->updateFromProjectTreeWidget(widget);
+}
+
+void ProjectTree::focusChanged()
+{
+ s_instance->updateFromFocus();
+}
+
+void ProjectTree::updateFromFocus(bool invalidCurrentNode)
+{
+ ProjectTreeWidget *focus = m_focusForContextMenu;
+ if (!focus)
+ focus = Utils::findOrDefault(m_projectTreeWidgets, &ProjectTree::hasFocus);
+
+ if (focus)
+ updateFromProjectTreeWidget(focus);
+ else
+ updateFromDocumentManager(invalidCurrentNode);
+}
+
+void ProjectTree::updateFromProjectTreeWidget(ProjectTreeWidget *widget)
+{
+ Node *currentNode = widget->currentNode();
+ Project *project = projectForNode(currentNode);
+
+ update(currentNode, project);
+}
+
+void ProjectTree::documentManagerCurrentFileChanged()
+{
+ updateFromFocus();
+}
+
+Project *ProjectTree::projectForNode(Node *node)
+{
+ if (!node)
+ return 0;
+
+ FolderNode *rootProjectNode = dynamic_cast<FolderNode*>(node);
+ if (!rootProjectNode)
+ rootProjectNode = node->parentFolderNode();
+
+ while (rootProjectNode && rootProjectNode->parentFolderNode() != SessionManager::sessionNode())
+ rootProjectNode = rootProjectNode->parentFolderNode();
+
+ Q_ASSERT(rootProjectNode);
+
+ return Utils::findOrDefault(SessionManager::projects(), Utils::equal(&Project::rootProjectNode, rootProjectNode));
+}
+
+void ProjectTree::updateFromDocumentManager(bool invalidCurrentNode)
+{
+ Core::IDocument *document = Core::EditorManager::currentDocument();
+ const QString &fileName = document ? document->filePath().toString() : QString();
+
+ Node *currentNode = 0;
+ if (!invalidCurrentNode && m_currentNode && m_currentNode->path() == fileName)
+ currentNode = m_currentNode;
+ else
+ currentNode = ProjectTreeWidget::nodeForFile(fileName);
+
+ Project *project = projectForNode(currentNode);
+
+ update(currentNode, project);
+ foreach (ProjectTreeWidget *widget, m_projectTreeWidgets)
+ widget->sync(currentNode);
+}
+
+void ProjectTree::update(Node *node, Project *project)
+{
+ bool changedProject = project != m_currentProject;
+ bool changedNode = node != m_currentNode;
+ if (changedProject) {
+ if (m_currentProject) {
+ disconnect(m_currentProject, &Project::projectContextUpdated,
+ this, &ProjectTree::updateContext);
+ disconnect(m_currentProject, &Project::projectLanguagesUpdated,
+ this, &ProjectTree::updateContext);
+ }
+
+ m_currentProject = project;
+
+ if (m_currentProject) {
+ connect(m_currentProject, &Project::projectContextUpdated,
+ this, &ProjectTree::updateContext);
+ connect(m_currentProject, &Project::projectLanguagesUpdated,
+ this, &ProjectTree::updateContext);
+ }
+ }
+
+ if (!node && Core::EditorManager::currentDocument()) {
+ connect(Core::EditorManager::currentDocument(), &Core::IDocument::changed,
+ this, &ProjectTree::updateExternalFileWarning,
+ Qt::UniqueConnection);
+ }
+
+ if (changedNode) {
+ m_currentNode = node;
+ emit currentNodeChanged(m_currentNode, project);
+ }
+
+
+ if (changedProject) {
+ emit currentProjectChanged(m_currentProject);
+ updateDefaultLocationForNewFiles();
+ updateContext();
+ }
+}
+
+void ProjectTree::updateDefaultLocationForNewFiles()
+{
+ if (m_currentProject)
+ Core::DocumentManager::setDefaultLocationForNewFiles(m_currentProject->projectDirectory().toString());
+ else if (SessionManager::startupProject())
+ Core::DocumentManager::setDefaultLocationForNewFiles(SessionManager::startupProject()->projectDirectory().toString());
+ else
+ Core::DocumentManager::setDefaultLocationForNewFiles(QString());
+}
+
+void ProjectTree::updateContext()
+{
+ Core::Context oldContext;
+ oldContext.add(m_lastProjectContext);
+
+ Core::Context newContext;
+ if (m_currentProject) {
+ newContext.add(m_currentProject->projectContext());
+ newContext.add(m_currentProject->projectLanguages());
+
+ m_lastProjectContext = newContext;
+ } else {
+ m_lastProjectContext = Core::Context();
+ }
+
+ Core::ICore::updateAdditionalContexts(oldContext, newContext);
+}
+
+void ProjectTree::emitNodeUpdated(Node *node)
+{
+ if (!isInNodeHierarchy(node))
+ return;
+ emit nodeUpdated(node);
+}
+
+void ProjectTree::emitAboutToChangeShowInSimpleTree(FolderNode *node)
+{
+ if (!isInNodeHierarchy(node))
+ return;
+ emit aboutToChangeShowInSimpleTree(node);
+}
+
+void ProjectTree::emitShowInSimpleTreeChanged(FolderNode *node)
+{
+ if (!isInNodeHierarchy(node))
+ return;
+ emit showInSimpleTreeChanged(node);
+}
+
+void ProjectTree::emitFoldersAboutToBeAdded(FolderNode *parentFolder, const QList<FolderNode *> &newFolders)
+{
+ if (!isInNodeHierarchy(parentFolder))
+ return;
+
+ emit foldersAboutToBeAdded(parentFolder, newFolders);
+}
+
+void ProjectTree::emitFoldersAdded(FolderNode *folder)
+{
+ if (!isInNodeHierarchy(folder))
+ return;
+
+ emit foldersAdded();
+
+ if (Utils::anyOf(m_projectTreeWidgets, &ProjectTreeWidget::hasFocus))
+ return;
+
+ updateFromDocumentManager();
+}
+
+void ProjectTree::emitFoldersAboutToBeRemoved(FolderNode *parentFolder, const QList<FolderNode *> &staleFolders)
+{
+ if (!isInNodeHierarchy(parentFolder))
+ return;
+
+ Node *n = ProjectTree::currentNode();
+ while (n) {
+ if (FolderNode *fn = dynamic_cast<FolderNode *>(n)) {
+ if (staleFolders.contains(fn)) {
+ ProjectNode *pn = n->projectNode();
+ // Make sure the node we are switching too isn't going to be removed also
+ while (staleFolders.contains(pn))
+ pn = pn->parentFolderNode()->projectNode();
+ m_resetCurrentNodeFolder = true;
+ break;
+ }
+ }
+ n = n->parentFolderNode();
+ }
+ emit foldersAboutToBeRemoved(parentFolder, staleFolders);
+}
+
+void ProjectTree::emitFoldersRemoved(FolderNode *folder)
+{
+ if (!isInNodeHierarchy(folder))
+ return;
+
+ emit foldersRemoved();
+
+ if (m_resetCurrentNodeFolder) {
+ updateFromFocus(true);
+ m_resetCurrentNodeFolder = false;
+ }
+}
+
+void ProjectTree::emitFilesAboutToBeAdded(FolderNode *folder, const QList<FileNode *> &newFiles)
+{
+ if (!isInNodeHierarchy(folder))
+ return;
+ emit filesAboutToBeAdded(folder, newFiles);
+}
+
+void ProjectTree::emitFilesAdded(FolderNode *folder)
+{
+ if (!isInNodeHierarchy(folder))
+ return;
+
+ emit filesAdded();
+
+ if (Utils::anyOf(m_projectTreeWidgets, &ProjectTreeWidget::hasFocus))
+ return;
+
+ updateFromDocumentManager();
+}
+
+void ProjectTree::emitFilesAboutToBeRemoved(FolderNode *folder, const QList<FileNode *> &staleFiles)
+{
+ if (!isInNodeHierarchy(folder))
+ return;
+
+ if (FileNode *fileNode = dynamic_cast<FileNode *>(m_currentNode))
+ if (staleFiles.contains(fileNode))
+ m_resetCurrentNodeFile = true;
+
+ emit filesAboutToBeRemoved(folder, staleFiles);
+}
+
+void ProjectTree::emitFilesRemoved(FolderNode *folder)
+{
+ if (!isInNodeHierarchy(folder))
+ return;
+ emit filesRemoved();
+
+ if (m_resetCurrentNodeFile) {
+ updateFromFocus(true);
+ m_resetCurrentNodeFile = false;
+ }
+}
+
+void ProjectTree::emitNodeSortKeyAboutToChange(Node *node)
+{
+ if (!isInNodeHierarchy(node))
+ return;
+ emit nodeSortKeyAboutToChange(node);
+}
+
+void ProjectTree::emitNodeSortKeyChanged(Node *node)
+{
+ if (!isInNodeHierarchy(node))
+ return;
+ emit nodeSortKeyChanged();
+}
+
+void ProjectTree::collapseAll()
+{
+ if (m_focusForContextMenu)
+ m_focusForContextMenu->collapseAll();
+}
+
+void ProjectTree::updateExternalFileWarning()
+{
+ Core::IDocument *document = qobject_cast<Core::IDocument *>(sender());
+ if (!document || document->filePath().isEmpty())
+ return;
+ Core::InfoBar *infoBar = document->infoBar();
+ Core::Id externalFileId(EXTERNAL_FILE_WARNING);
+ if (!document->isModified()) {
+ infoBar->removeInfo(externalFileId);
+ return;
+ }
+ if (!infoBar->canInfoBeAdded(externalFileId))
+ return;
+ const FileName fileName = document->filePath();
+ const QList<Project *> projects = SessionManager::projects();
+ if (projects.isEmpty())
+ return;
+ foreach (Project *project, projects) {
+ FileName projectDir = project->projectDirectory();
+ if (projectDir.isEmpty())
+ continue;
+ if (fileName.isChildOf(projectDir))
+ return;
+ // External file. Test if it under the same VCS
+ QString topLevel;
+ if (Core::VcsManager::findVersionControlForDirectory(projectDir.toString(), &topLevel)
+ && fileName.isChildOf(FileName::fromString(topLevel))) {
+ return;
+ }
+ }
+ infoBar->addInfo(Core::InfoBarEntry(externalFileId,
+ tr("<b>Warning:</b> This file is outside the project directory."),
+ Core::InfoBarEntry::GlobalSuppressionEnabled));
+}
+
+bool ProjectTree::hasFocus(ProjectTreeWidget *widget)
+{
+ return widget
+ && ((widget->focusWidget() && widget->focusWidget()->hasFocus())
+ || s_instance->m_focusForContextMenu == widget);
+}
+
+void ProjectTree::showContextMenu(ProjectTreeWidget *focus, const QPoint &globalPos, Node *node)
+{
+ QMenu *contextMenu = 0;
+
+ if (!node)
+ node = SessionManager::sessionNode();
+ if (node->nodeType() != SessionNodeType) {
+ Project *project = SessionManager::projectForNode(node);
+
+ emit s_instance->aboutToShowContextMenu(project, node);
+ switch (node->nodeType()) {
+ case ProjectNodeType:
+ if (node->parentFolderNode() == SessionManager::sessionNode())
+ contextMenu = Core::ActionManager::actionContainer(Constants::M_PROJECTCONTEXT)->menu();
+ else
+ contextMenu = Core::ActionManager::actionContainer(Constants::M_SUBPROJECTCONTEXT)->menu();
+ break;
+ case VirtualFolderNodeType:
+ case FolderNodeType:
+ contextMenu = Core::ActionManager::actionContainer(Constants::M_FOLDERCONTEXT)->menu();
+ break;
+ case FileNodeType:
+ contextMenu = Core::ActionManager::actionContainer(Constants::M_FILECONTEXT)->menu();
+ break;
+ default:
+ qWarning("ProjectExplorerPlugin::showContextMenu - Missing handler for node type");
+ }
+ } else { // session item
+ emit s_instance->aboutToShowContextMenu(0, node);
+
+ contextMenu = Core::ActionManager::actionContainer(Constants::M_SESSIONCONTEXT)->menu();
+ }
+
+ if (contextMenu && contextMenu->actions().count() > 0) {
+ contextMenu->popup(globalPos);
+ s_instance->m_focusForContextMenu = focus;
+ connect(contextMenu, &QMenu::aboutToHide,
+ s_instance, &ProjectTree::hideContextMenu,
+ Qt::ConnectionType(Qt::UniqueConnection | Qt::QueuedConnection));
+ }
+}
+
+void ProjectTree::hideContextMenu()
+{
+ m_focusForContextMenu = 0;
+}
+
+bool ProjectTree::isInNodeHierarchy(Node *n)
+{
+ Node *sessionNode = SessionManager::sessionNode();
+ do {
+ if (n == sessionNode)
+ return true;
+ n = n->parentFolderNode();
+ } while (n);
+ return false;
+}
+
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/projecttree.h b/src/plugins/projectexplorer/projecttree.h
new file mode 100644
index 00000000000..642458221e3
--- /dev/null
+++ b/src/plugins/projectexplorer/projecttree.h
@@ -0,0 +1,161 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 PROJECTTREE_H
+#define PROJECTTREE_H
+
+#include "projectexplorer_export.h"
+
+#include <coreplugin/icontext.h>
+
+namespace ProjectExplorer {
+class FileNode;
+class FolderNode;
+class Node;
+class Project;
+class ProjectNode;
+class SessionNode;
+
+namespace Internal { class ProjectTreeWidget; }
+
+class PROJECTEXPLORER_EXPORT ProjectTree : public QObject
+{
+ Q_OBJECT
+public:
+ explicit ProjectTree(QObject *parent = 0);
+
+ static ProjectTree *instance();
+
+ static Project *currentProject();
+ static Node *currentNode();
+
+ // Integration with ProjectTreeWidget
+ static void registerWidget(Internal::ProjectTreeWidget *widget);
+ static void unregisterWidget(Internal::ProjectTreeWidget *widget);
+ static void nodeChanged(Internal::ProjectTreeWidget *widget);
+ static Project *projectForNode(Node *node);
+
+ static void aboutToShutDown();
+
+ static void showContextMenu(Internal::ProjectTreeWidget *focus, const QPoint &globalPos, Node *node);
+
+signals:
+ void currentProjectChanged(ProjectExplorer::Project *project);
+ void currentNodeChanged(ProjectExplorer::Node *node, ProjectExplorer::Project *project);
+
+ // Emitted whenever the model needs to send a update signal.
+ void nodeUpdated(ProjectExplorer::Node *node);
+
+ // projects
+ void aboutToChangeShowInSimpleTree(ProjectExplorer::FolderNode*);
+ void showInSimpleTreeChanged(ProjectExplorer::FolderNode *node);
+
+ // folders & projects
+ void foldersAboutToBeAdded(FolderNode *parentFolder,
+ const QList<FolderNode*> &newFolders);
+ void foldersAdded();
+
+ void foldersAboutToBeRemoved(FolderNode *parentFolder,
+ const QList<FolderNode*> &staleFolders);
+ void foldersRemoved();
+
+ // files
+ void filesAboutToBeAdded(FolderNode *folder,
+ const QList<FileNode*> &newFiles);
+ void filesAdded();
+
+ void filesAboutToBeRemoved(FolderNode *folder,
+ const QList<FileNode*> &staleFiles);
+ void filesRemoved();
+ void nodeSortKeyAboutToChange(Node *node);
+ void nodeSortKeyChanged();
+
+ void aboutToShowContextMenu(ProjectExplorer::Project *project,
+ ProjectExplorer::Node *node);
+
+public: // for nodes to emit signals, do not call unless you are a node
+ void emitNodeUpdated(ProjectExplorer::Node *node);
+
+ // projects
+ void emitAboutToChangeShowInSimpleTree(ProjectExplorer::FolderNode *node);
+ void emitShowInSimpleTreeChanged(ProjectExplorer::FolderNode *node);
+
+ // folders & projects
+ void emitFoldersAboutToBeAdded(FolderNode *parentFolder,
+ const QList<FolderNode*> &newFolders);
+ void emitFoldersAdded(FolderNode *folder);
+
+ void emitFoldersAboutToBeRemoved(FolderNode *parentFolder,
+ const QList<FolderNode*> &staleFolders);
+ void emitFoldersRemoved(FolderNode *folder);
+
+ // files
+ void emitFilesAboutToBeAdded(FolderNode *folder,
+ const QList<FileNode*> &newFiles);
+ void emitFilesAdded(FolderNode *folder);
+
+ void emitFilesAboutToBeRemoved(FolderNode *folder,
+ const QList<FileNode*> &staleFiles);
+ void emitFilesRemoved(FolderNode *folder);
+ void emitNodeSortKeyAboutToChange(Node *node);
+ void emitNodeSortKeyChanged(Node *node);
+
+ void collapseAll();
+
+private:
+ void updateDefaultLocationForNewFiles();
+ void focusChanged();
+ void updateFromProjectTreeWidget(Internal::ProjectTreeWidget *widget);
+ void documentManagerCurrentFileChanged();
+ void updateFromDocumentManager(bool invalidCurrentNode = false);
+ void update(Node *node, Project *project);
+ void updateContext();
+
+ void updateFromFocus(bool invalidCurrentNode = false);
+
+ void updateExternalFileWarning();
+ static bool hasFocus(Internal::ProjectTreeWidget *widget);
+ void hideContextMenu();
+ bool isInNodeHierarchy(Node *n);
+
+private:
+ static ProjectTree *s_instance;
+ QList<Internal::ProjectTreeWidget *> m_projectTreeWidgets;
+ Node *m_currentNode;
+ Project *m_currentProject;
+ bool m_resetCurrentNodeFolder;
+ bool m_resetCurrentNodeFile;
+ bool m_resetCurrentNodeProject;
+ Internal::ProjectTreeWidget *m_focusForContextMenu;
+ Core::Context m_lastProjectContext;
+};
+}
+
+#endif // PROJECTTREE_H
diff --git a/src/plugins/projectexplorer/projecttreewidget.cpp b/src/plugins/projectexplorer/projecttreewidget.cpp
index 538d4429e24..badb3b51656 100644
--- a/src/plugins/projectexplorer/projecttreewidget.cpp
+++ b/src/plugins/projectexplorer/projecttreewidget.cpp
@@ -35,9 +35,11 @@
#include "project.h"
#include "session.h"
#include "projectmodels.h"
+#include "projecttree.h"
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
+#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
@@ -127,10 +129,11 @@ ProjectTreeWidget::ProjectTreeWidget(QWidget *parent)
m_view->setModel(m_model);
m_view->setItemDelegate(new ProjectTreeItemDelegate(this));
setFocusProxy(m_view);
+ m_view->installEventFilter(this);
initView();
QVBoxLayout *layout = new QVBoxLayout();
- layout->addWidget(Core::ItemViewFind::createSearchableWrapper(
+ layout->addWidget(ItemViewFind::createSearchableWrapper(
m_view, ItemViewFind::DarkColored,
ItemViewFind::FetchMoreWhileSearching));
layout->setContentsMargins(0, 0, 0, 0);
@@ -149,6 +152,8 @@ ProjectTreeWidget::ProjectTreeWidget(QWidget *parent)
// connections
connect(m_model, SIGNAL(modelReset()),
this, SLOT(initView()));
+ connect(m_model, &FlatModel::renamed,
+ this, &ProjectTreeWidget::renamed);
connect(m_view, SIGNAL(activated(QModelIndex)),
this, SLOT(openItem(QModelIndex)));
connect(m_view->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
@@ -179,11 +184,13 @@ ProjectTreeWidget::ProjectTreeWidget(QWidget *parent)
setAutoSynchronization(true);
m_projectTreeWidgets << this;
+ ProjectTree::registerWidget(this);
}
ProjectTreeWidget::~ProjectTreeWidget()
{
m_projectTreeWidgets.removeOne(this);
+ ProjectTree::unregisterWidget(this);
}
// returns how many nodes need to be expanded to make node visible
@@ -208,32 +215,43 @@ int ProjectTreeWidget::expandedCount(Node *node)
return count;
}
-void ProjectTreeWidget::rowsInserted(const QModelIndex &parent, int, int)
+void ProjectTreeWidget::rowsInserted(const QModelIndex &parent, int start, int end)
{
const QString &path = m_model->nodeForIndex(parent)->path();
if (m_toExpand.contains(path)) {
m_view->expand(parent);
m_toExpand.remove(path);
}
+ int i = start;
+ while (i <= end) {
+ QModelIndex idx = m_model->index(i, 0, parent);
+ Node *n = m_model->nodeForIndex(idx);
+ if (n && n->path() == m_delayedRename) {
+ m_view->setCurrentIndex(idx);
+ m_delayedRename.clear();
+ break;
+ }
+ ++i;
+ }
}
-Node *ProjectTreeWidget::nodeForFile(const QString &fileName, Project *project)
+Node *ProjectTreeWidget::nodeForFile(const QString &fileName)
{
Node *bestNode = 0;
int bestNodeExpandCount = INT_MAX;
- foreach (Node *node, SessionManager::nodesForFile(fileName, project)) {
+ foreach (Node *node, SessionManager::nodesForFile(fileName)) {
if (!bestNode) {
bestNode = node;
- bestNodeExpandCount = ProjectTreeWidget::expandedCount(node->parentFolderNode());
+ bestNodeExpandCount = ProjectTreeWidget::expandedCount(node);
} else if (node->nodeType() < bestNode->nodeType()) {
bestNode = node;
- bestNodeExpandCount = ProjectTreeWidget::expandedCount(node->parentFolderNode());
+ bestNodeExpandCount = ProjectTreeWidget::expandedCount(node);
} else if (node->nodeType() == bestNode->nodeType()) {
- int nodeExpandCount = ProjectTreeWidget::expandedCount(node->parentFolderNode());
+ int nodeExpandCount = ProjectTreeWidget::expandedCount(node);
if (nodeExpandCount < bestNodeExpandCount) {
bestNode = node;
- bestNodeExpandCount = ProjectTreeWidget::expandedCount(node->parentFolderNode());
+ bestNodeExpandCount = ProjectTreeWidget::expandedCount(node);
}
}
}
@@ -304,7 +322,7 @@ bool ProjectTreeWidget::autoSynchronization() const
return m_autoSync;
}
-void ProjectTreeWidget::setAutoSynchronization(bool sync, bool syncNow)
+void ProjectTreeWidget::setAutoSynchronization(bool sync)
{
m_toggleSync->setChecked(sync);
if (sync == m_autoSync)
@@ -314,14 +332,14 @@ void ProjectTreeWidget::setAutoSynchronization(bool sync, bool syncNow)
if (debug)
qDebug() << (m_autoSync ? "Enabling auto synchronization" : "Disabling auto synchronization");
+
if (m_autoSync) {
- connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::currentNodeChanged,
- this, &ProjectTreeWidget::setCurrentItem);
- if (syncNow)
- setCurrentItem(ProjectExplorerPlugin::currentNode(), ProjectExplorerPlugin::currentProject());
- } else {
- disconnect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::currentNodeChanged,
- this, &ProjectTreeWidget::setCurrentItem);
+ // sync from document manager
+ QString fileName;
+ if (IDocument *doc = EditorManager::currentDocument())
+ fileName = doc->filePath().toString();
+ if (!currentNode() || currentNode()->path() != fileName)
+ setCurrentItem(ProjectTreeWidget::nodeForFile(fileName));
}
}
@@ -332,19 +350,27 @@ void ProjectTreeWidget::collapseAll()
void ProjectTreeWidget::editCurrentItem()
{
+ m_delayedRename.clear();
if (m_view->selectionModel()->currentIndex().isValid())
m_view->edit(m_view->selectionModel()->currentIndex());
}
-void ProjectTreeWidget::setCurrentItem(Node *node, Project *project)
-{
- if (debug)
- qDebug() << "ProjectTreeWidget::setCurrentItem(" << (project ? project->displayName() : QLatin1String("0"))
- << ", " << (node ? node->path() : QLatin1String("0")) << ")";
- if (!project)
- return;
+void ProjectTreeWidget::renamed(const QString &oldPath, const QString &newPath)
+{
+ Q_UNUSED(oldPath);
+ if (!currentNode() || currentNode()->path() != newPath) {
+ // try to find the node
+ Node *node = nodeForFile(newPath);
+ if (node)
+ m_view->setCurrentIndex(m_model->indexForNode(node));
+ else
+ m_delayedRename = newPath;
+ }
+}
+void ProjectTreeWidget::setCurrentItem(Node *node)
+{
const QModelIndex mainIndex = m_model->indexForNode(node);
if (mainIndex.isValid()) {
@@ -353,8 +379,6 @@ void ProjectTreeWidget::setCurrentItem(Node *node, Project *project)
m_view->scrollTo(mainIndex);
}
} else {
- if (debug)
- qDebug() << "clear selection";
m_view->clearSelection();
}
@@ -362,19 +386,26 @@ void ProjectTreeWidget::setCurrentItem(Node *node, Project *project)
void ProjectTreeWidget::handleCurrentItemChange(const QModelIndex &current)
{
- Node *node = m_model->nodeForIndex(current);
- // node might be 0. that's okay
- bool autoSync = autoSynchronization();
- setAutoSynchronization(false);
- ProjectExplorerPlugin::setCurrentNode(node);
- setAutoSynchronization(autoSync, false);
+ Q_UNUSED(current);
+ ProjectTree::nodeChanged(this);
+}
+
+Node *ProjectTreeWidget::currentNode()
+{
+ return m_model->nodeForIndex(m_view->currentIndex());
+}
+
+void ProjectTreeWidget::sync(Node *node)
+{
+ if (m_autoSync)
+ setCurrentItem(node);
}
void ProjectTreeWidget::showContextMenu(const QPoint &pos)
{
QModelIndex index = m_view->indexAt(pos);
Node *node = m_model->nodeForIndex(index);
- ProjectExplorerPlugin::showContextMenu(this, m_view->mapToGlobal(pos), node);
+ ProjectTree::showContextMenu(this, m_view->mapToGlobal(pos), node);
}
void ProjectTreeWidget::handleProjectAdded(Project *project)
@@ -413,7 +444,7 @@ void ProjectTreeWidget::initView()
for (int i = 0; i < m_model->rowCount(sessionIndex); ++i)
m_view->expand(m_model->index(i, 0, sessionIndex));
- setCurrentItem(ProjectExplorerPlugin::currentNode(), ProjectExplorerPlugin::currentProject());
+ setCurrentItem(ProjectTree::currentNode());
}
void ProjectTreeWidget::openItem(const QModelIndex &mainIndex)
@@ -496,5 +527,5 @@ void ProjectTreeWidgetFactory::restoreSettings(int position, QWidget *widget)
const QString baseKey = QLatin1String("ProjectTreeWidget.") + QString::number(position);
ptw->setProjectFilter(settings->value(baseKey + QLatin1String(".ProjectFilter"), false).toBool());
ptw->setGeneratedFilesFilter(settings->value(baseKey + QLatin1String(".GeneratedFilter"), true).toBool());
- ptw->setAutoSynchronization(settings->value(baseKey + QLatin1String(".SyncWithEditor"), true).toBool());
+ ptw->setAutoSynchronization(settings->value(baseKey + QLatin1String(".SyncWithEditor")).toBool());
}
diff --git a/src/plugins/projectexplorer/projecttreewidget.h b/src/plugins/projectexplorer/projecttreewidget.h
index eaf1f6468c1..753aca31178 100644
--- a/src/plugins/projectexplorer/projecttreewidget.h
+++ b/src/plugins/projectexplorer/projecttreewidget.h
@@ -58,12 +58,14 @@ public:
~ProjectTreeWidget();
bool autoSynchronization() const;
- void setAutoSynchronization(bool sync, bool syncNow = true);
+ void setAutoSynchronization(bool sync);
bool projectFilter();
bool generatedFilesFilter();
QToolButton *toggleSync();
+ Node *currentNode();
+ void sync(ProjectExplorer::Node *node);
- static Node *nodeForFile(const QString &fileName, Project *project);
+ static Node *nodeForFile(const QString &fileName);
public slots:
void toggleAutoSynchronization();
@@ -71,7 +73,6 @@ public slots:
void collapseAll();
private slots:
- void setCurrentItem(ProjectExplorer::Node *node, ProjectExplorer::Project *project);
void setProjectFilter(bool filter);
void setGeneratedFilesFilter(bool filter);
@@ -87,10 +88,12 @@ private slots:
void disableAutoExpand();
private:
+ void setCurrentItem(ProjectExplorer::Node *node);
void recursiveLoadExpandData(const QModelIndex &index, QSet<QString> &data);
void recursiveSaveExpandData(const QModelIndex &index, QStringList *data);
static int expandedCount(Node *node);
- void rowsInserted(const QModelIndex &parent, int, int);
+ void rowsInserted(const QModelIndex &parent, int start, int end);
+ void renamed(const QString &oldPath, const QString &newPath);
QSet<QString> m_toExpand;
QTreeView *m_view;
@@ -103,6 +106,7 @@ private:
QString m_modelId;
bool m_autoSync;
bool m_autoExpand;
+ QString m_delayedRename;
static QList<ProjectTreeWidget *> m_projectTreeWidgets;
friend class ProjectTreeWidgetFactory;
diff --git a/src/plugins/projectexplorer/projectwelcomepage.cpp b/src/plugins/projectexplorer/projectwelcomepage.cpp
index de0b3a37c02..74935dab674 100644
--- a/src/plugins/projectexplorer/projectwelcomepage.cpp
+++ b/src/plugins/projectexplorer/projectwelcomepage.cpp
@@ -236,9 +236,9 @@ QUrl ProjectWelcomePage::pageLocation() const
return QUrl::fromLocalFile(resourcePath + QLatin1String("/welcomescreen/develop.qml"));
}
-ProjectWelcomePage::Id ProjectWelcomePage::id() const
+Core::Id ProjectWelcomePage::id() const
{
- return Develop;
+ return "Develop";
}
void ProjectWelcomePage::reloadWelcomeScreenData()
diff --git a/src/plugins/projectexplorer/projectwelcomepage.h b/src/plugins/projectexplorer/projectwelcomepage.h
index 0cf8fa00e7f..31a39e90da4 100644
--- a/src/plugins/projectexplorer/projectwelcomepage.h
+++ b/src/plugins/projectexplorer/projectwelcomepage.h
@@ -33,7 +33,7 @@
#include <QAbstractListModel>
-#include <utils/iwelcomepage.h>
+#include <coreplugin/iwelcomepage.h>
QT_BEGIN_NAMESPACE
class QQmlEngine;
@@ -78,7 +78,7 @@ public slots:
void resetProjects();
};
-class ProjectWelcomePage : public Utils::IWelcomePage
+class ProjectWelcomePage : public Core::IWelcomePage
{
Q_OBJECT
public:
@@ -89,7 +89,7 @@ public:
QWidget *page() { return 0; }
QString title() const { return tr("Projects"); }
int priority() const { return 20; }
- Id id() const;
+ Core::Id id() const;
void reloadWelcomeScreenData();
diff --git a/src/plugins/projectexplorer/projectwizardpage.cpp b/src/plugins/projectexplorer/projectwizardpage.cpp
index 09d185e7070..7d257e5298b 100644
--- a/src/plugins/projectexplorer/projectwizardpage.cpp
+++ b/src/plugins/projectexplorer/projectwizardpage.cpp
@@ -31,7 +31,6 @@
#include "projectwizardpage.h"
#include "ui_projectwizardpage.h"
-#include "addnewmodel.h"
#include "projectexplorer.h"
#include "session.h"
@@ -39,11 +38,11 @@
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/iwizardfactory.h>
#include <coreplugin/vcsmanager.h>
-#include <extensionsystem/pluginmanager.h>
#include <utils/algorithm.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
+#include <utils/treemodel.h>
#include <utils/wizard.h>
#include <vcsbase/vcsbaseconstants.h>
@@ -61,10 +60,84 @@
*/
using namespace Core;
+using namespace Utils;
namespace ProjectExplorer {
namespace Internal {
+class AddNewTree : public TreeItem
+{
+public:
+ AddNewTree(const QString &displayName);
+ AddNewTree(FolderNode *node, QList<AddNewTree *> children, const QString &displayName);
+ AddNewTree(FolderNode *node, QList<AddNewTree *> children, const FolderNode::AddNewInformation &info);
+
+ QVariant data(int column, int role) const;
+ Qt::ItemFlags flags(int column) const;
+
+ QString displayName() const { return m_displayName; }
+ FolderNode *node() const { return m_node; }
+ int priority() const { return m_priority; }
+
+private:
+ QString m_displayName;
+ QString m_toolTip;
+ FolderNode *m_node;
+ bool m_canAdd;
+ int m_priority;
+};
+
+AddNewTree::AddNewTree(const QString &displayName)
+ : m_displayName(displayName),
+ m_node(0),
+ m_canAdd(true),
+ m_priority(-1)
+{
+}
+
+// FIXME: potentially merge the following two functions.
+// Note the different handling of 'node' and m_canAdd.
+AddNewTree::AddNewTree(FolderNode *node, QList<AddNewTree *> children, const QString &displayName)
+ : m_displayName(displayName),
+ m_node(0),
+ m_canAdd(false),
+ m_priority(-1)
+{
+ if (node)
+ m_toolTip = ProjectExplorerPlugin::directoryFor(node);
+ foreach (AddNewTree *child, children)
+ appendChild(child);
+}
+
+AddNewTree::AddNewTree(FolderNode *node, QList<AddNewTree *> children, const FolderNode::AddNewInformation &info)
+ : m_displayName(info.displayName),
+ m_node(node),
+ m_canAdd(true),
+ m_priority(info.priority)
+{
+ if (node)
+ m_toolTip = ProjectExplorerPlugin::directoryFor(node);
+ foreach (AddNewTree *child, children)
+ appendChild(child);
+}
+
+
+QVariant AddNewTree::data(int, int role) const
+{
+ if (role == Qt::DisplayRole)
+ return m_displayName;
+ if (role == Qt::ToolTipRole)
+ return m_toolTip;
+ return QVariant();
+}
+
+Qt::ItemFlags AddNewTree::flags(int) const
+{
+ if (m_canAdd)
+ return Qt::ItemIsSelectable | Qt::ItemIsEnabled;
+ return Qt::NoItemFlags;
+}
+
// --------------------------------------------------------------------
// BestNodeSelector:
// --------------------------------------------------------------------
@@ -250,15 +323,15 @@ ProjectWizardPage::ProjectWizardPage(QWidget *parent) :
m_repositoryExists(false)
{
m_ui->setupUi(this);
- m_ui->vcsManageButton->setText(Core::ICore::msgShowOptionsDialog());
+ m_ui->vcsManageButton->setText(ICore::msgShowOptionsDialog());
connect(m_ui->projectComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(projectChanged(int)));
connect(m_ui->addToVersionControlComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &ProjectWizardPage::versionControlChanged);
connect(m_ui->vcsManageButton, &QAbstractButton::clicked, this, &ProjectWizardPage::manageVcs);
- setProperty(Utils::SHORT_TITLE_PROPERTY, tr("Summary"));
+ setProperty(SHORT_TITLE_PROPERTY, tr("Summary"));
- connect(Core::VcsManager::instance(), SIGNAL(configurationChanged(const IVersionControl*)),
+ connect(VcsManager::instance(), SIGNAL(configurationChanged(const IVersionControl*)),
this, SLOT(initializeVersionControls()));
}
@@ -268,7 +341,7 @@ ProjectWizardPage::~ProjectWizardPage()
delete m_model;
}
-void ProjectWizardPage::setModel(AddNewModel *model)
+void ProjectWizardPage::setModel(TreeModel *model)
{
delete m_model;
m_model = model;
@@ -310,7 +383,7 @@ bool ProjectWizardPage::expandTree(const QModelIndex &root)
void ProjectWizardPage::setBestNode(AddNewTree *tree)
{
- QModelIndex index = m_model->indexForTree(tree);
+ QModelIndex index = tree ? m_model->indexFromItem(tree) : QModelIndex();
m_ui->projectComboBox->setCurrentIndex(index);
while (index.isValid()) {
@@ -322,7 +395,8 @@ void ProjectWizardPage::setBestNode(AddNewTree *tree)
FolderNode *ProjectWizardPage::currentNode() const
{
QModelIndex index = m_ui->projectComboBox->view()->currentIndex();
- return m_model->nodeForIndex(index);
+ TreeItem *item = m_model->itemFromIndex(index);
+ return item ? static_cast<AddNewTree *>(item)->node() : 0;
}
void ProjectWizardPage::setAddingSubProject(bool addingSubProject)
@@ -358,7 +432,7 @@ void ProjectWizardPage::initializeVersionControls()
}
} else {
// Create
- foreach (IVersionControl *vc, ExtensionSystem::PluginManager::getObjects<IVersionControl>()) {
+ foreach (IVersionControl *vc, VcsManager::versionControls()) {
if (vc->supportsOperation(IVersionControl::CreateRepositoryOperation)) {
versionControlChoices.append(vc->displayName());
m_activeVersionControls.append(vc);
@@ -416,7 +490,7 @@ void ProjectWizardPage::initializeProjectTree(Node *context, const QStringList &
setAdditionalInfo(selector.deployingProjects());
- AddNewModel *model = new AddNewModel(tree);
+ TreeModel *model = new TreeModel(tree);
setModel(model);
setBestNode(selector.bestChoice());
setAddingSubProject(action == AddSubProject);
@@ -482,7 +556,7 @@ void ProjectWizardPage::setFiles(const QStringList &fileNames)
const bool filePath2HasDir = filePath2.contains(QLatin1Char('/'));
if (filePath1HasDir == filePath2HasDir)
- return Utils::FileName::fromString(filePath1) < Utils::FileName::fromString(filePath2);
+ return FileName::fromString(filePath1) < FileName::fromString(filePath2);
return filePath1HasDir;
}
);
@@ -510,7 +584,7 @@ void ProjectWizardPage::projectChanged(int index)
void ProjectWizardPage::manageVcs()
{
- Core::ICore::showOptionsDialog(VcsBase::Constants::VCS_SETTINGS_CATEGORY,
+ ICore::showOptionsDialog(VcsBase::Constants::VCS_SETTINGS_CATEGORY,
VcsBase::Constants::VCS_COMMON_SETTINGS_ID,
this);
}
diff --git a/src/plugins/projectexplorer/projectwizardpage.h b/src/plugins/projectexplorer/projectwizardpage.h
index c133f2cfedd..2f406012056 100644
--- a/src/plugins/projectexplorer/projectwizardpage.h
+++ b/src/plugins/projectexplorer/projectwizardpage.h
@@ -44,10 +44,11 @@ class QModelIndex;
QT_END_NAMESPACE
namespace Core { class IVersionControl; }
+namespace Utils { class TreeModel; }
namespace ProjectExplorer {
namespace Internal {
-class AddNewModel;
+
class AddNewTree;
namespace Ui { class WizardPage; }
@@ -92,7 +93,7 @@ private slots:
private:
void setAdditionalInfo(const QString &text);
void setAddingSubProject(bool addingSubProject);
- void setModel(AddNewModel *model);
+ void setModel(Utils::TreeModel *model);
void setBestNode(ProjectExplorer::Internal::AddNewTree *tree);
void setVersionControls(const QStringList &);
void setProjectToolTip(const QString &);
@@ -100,7 +101,7 @@ private:
Ui::WizardPage *m_ui;
QStringList m_projectToolTips;
- AddNewModel *m_model;
+ Utils::TreeModel *m_model;
QList<Core::IVersionControl*> m_activeVersionControls;
QString m_commonDirectory;
diff --git a/src/plugins/projectexplorer/runconfiguration.cpp b/src/plugins/projectexplorer/runconfiguration.cpp
index ad52406a71e..12f044677e4 100644
--- a/src/plugins/projectexplorer/runconfiguration.cpp
+++ b/src/plugins/projectexplorer/runconfiguration.cpp
@@ -115,13 +115,12 @@ ISettingsAspect *ISettingsAspect::clone() const
//
///////////////////////////////////////////////////////////////////////
-IRunConfigurationAspect::IRunConfigurationAspect(RunConfiguration *parent)
+IRunConfigurationAspect::IRunConfigurationAspect(RunConfiguration *runConfig)
{
- m_runConfiguration = parent;
+ m_runConfiguration = runConfig;
m_projectSettings = 0;
m_globalSettings = 0;
m_useGlobalSettings = false;
- connect(this, SIGNAL(requestRunActionsUpdate()), parent, SIGNAL(requestRunActionsUpdate()));
}
IRunConfigurationAspect::~IRunConfigurationAspect()
@@ -171,9 +170,9 @@ void IRunConfigurationAspect::toMap(QVariantMap &map) const
map.insert(m_id.toString() + QLatin1String(".UseGlobalSettings"), m_useGlobalSettings);
}
-IRunConfigurationAspect *IRunConfigurationAspect::clone(RunConfiguration *parent) const
+IRunConfigurationAspect *IRunConfigurationAspect::clone(RunConfiguration *runConfig) const
{
- IRunConfigurationAspect *other = create(parent);
+ IRunConfigurationAspect *other = create(runConfig);
if (m_projectSettings)
other->m_projectSettings = m_projectSettings->clone();
other->m_globalSettings = m_globalSettings;
@@ -314,7 +313,7 @@ QVariantMap RunConfiguration::toMap() const
return map;
}
-ProjectExplorer::Abi RunConfiguration::abi() const
+Abi RunConfiguration::abi() const
{
BuildConfiguration *bc = target()->activeBuildConfiguration();
if (!bc)
diff --git a/src/plugins/projectexplorer/runconfiguration.h b/src/plugins/projectexplorer/runconfiguration.h
index 533d86fb5c8..67bcae61569 100644
--- a/src/plugins/projectexplorer/runconfiguration.h
+++ b/src/plugins/projectexplorer/runconfiguration.h
@@ -113,11 +113,11 @@ class PROJECTEXPLORER_EXPORT IRunConfigurationAspect : public QObject
Q_OBJECT
public:
- explicit IRunConfigurationAspect(RunConfiguration *parent);
+ explicit IRunConfigurationAspect(RunConfiguration *runConfig);
~IRunConfigurationAspect();
- virtual IRunConfigurationAspect *create(RunConfiguration *parent) const = 0;
- virtual IRunConfigurationAspect *clone(RunConfiguration *parent) const;
+ virtual IRunConfigurationAspect *create(RunConfiguration *runConfig) const = 0;
+ virtual IRunConfigurationAspect *clone(RunConfiguration *runConfig) const;
virtual RunConfigWidget *createConfigurationWidget();
void setId(Core::Id id) { m_id = id; }
@@ -136,9 +136,6 @@ public:
ISettingsAspect *currentSettings() const;
RunConfiguration *runConfiguration() const { return m_runConfiguration; }
-signals:
- void requestRunActionsUpdate();
-
protected:
friend class RunConfiguration;
virtual void fromMap(const QVariantMap &map);
diff --git a/src/plugins/projectexplorer/runsettingspropertiespage.cpp b/src/plugins/projectexplorer/runsettingspropertiespage.cpp
index df7ed0cb62e..78888c0be01 100644
--- a/src/plugins/projectexplorer/runsettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/runsettingspropertiespage.cpp
@@ -61,7 +61,7 @@ namespace Internal {
struct FactoryAndId
{
- ProjectExplorer::IRunConfigurationFactory *factory;
+ IRunConfigurationFactory *factory;
Core::Id id;
};
diff --git a/src/plugins/projectexplorer/session.cpp b/src/plugins/projectexplorer/session.cpp
index cfcfcc4285d..5c364ab36e1 100644
--- a/src/plugins/projectexplorer/session.cpp
+++ b/src/plugins/projectexplorer/session.cpp
@@ -130,7 +130,7 @@ SessionManager::SessionManager(QObject *parent)
m_instance = this;
d = new SessionManagerPrivate;
- d->m_sessionNode = new SessionNode(this);
+ d->m_sessionNode = new SessionNode;
connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
this, SLOT(saveActiveMode(Core::IMode*)));
@@ -155,6 +155,7 @@ SessionManager::~SessionManager()
{
emit m_instance->aboutToUnloadSession(d->m_sessionName);
delete d->m_writer;
+ delete d->m_sessionNode;
delete d;
}
@@ -174,7 +175,7 @@ bool SessionManager::isDefaultSession(const QString &session)
}
-void SessionManager::saveActiveMode(Core::IMode *mode)
+void SessionManager::saveActiveMode(IMode *mode)
{
setValue(QLatin1String("ActiveMode"), mode->id().toString());
}
@@ -410,7 +411,7 @@ bool SessionManager::save()
data.insert(QLatin1String("valueKeys"), keys);
- bool result = d->m_writer->save(data, Core::ICore::mainWindow());
+ bool result = d->m_writer->save(data, ICore::mainWindow());
if (!result) {
QMessageBox::warning(ICore::dialogParent(), tr("Error while saving session"),
tr("Could not save session to file %1").arg(d->m_writer->fileName().toUserOutput()));
@@ -536,12 +537,32 @@ QList<Project *> SessionManager::projectOrder(Project *project)
return result;
}
+QList<Node *> SessionManager::nodesForFile(const QString &fileName)
+{
+ FindNodesForFileVisitor findNodes(fileName);
+ sessionNode()->accept(&findNodes);
+ return findNodes.nodes();
+}
+
+// node for file returns a randomly selected node if there are multiple
+// prefer to use nodesForFile and figure out which node you want
+Node *SessionManager::nodeForFile(const QString &fileName)
+{
+ Node *node = 0;
+ foreach (Node *n, nodesForFile(fileName)) {
+ // prefer file nodes
+ if (!node || (node->nodeType() != FileNodeType && n->nodeType() == FileNodeType))
+ node = n;
+ }
+ return node;
+}
+
Project *SessionManager::projectForNode(Node *node)
{
if (!node)
return 0;
- FolderNode *rootProjectNode = qobject_cast<FolderNode*>(node);
+ FolderNode *rootProjectNode = dynamic_cast<FolderNode*>(node);
if (!rootProjectNode)
rootProjectNode = node->parentFolderNode();
@@ -553,47 +574,14 @@ Project *SessionManager::projectForNode(Node *node)
return Utils::findOrDefault(d->m_projects, Utils::equal(&Project::rootProjectNode, rootProjectNode));
}
-QList<Node *> SessionManager::nodesForFile(const QString &fileName, Project *project)
-{
- if (!project)
- project = projectForFile(fileName);
-
- if (project) {
- FindNodesForFileVisitor findNodes(fileName);
- project->rootProjectNode()->accept(&findNodes);
- return findNodes.nodes();
- }
-
- return QList<Node *>();
-}
-
-// node for file returns a randomly selected node if there are multiple
-// prefer to use nodesForFile and figure out which node you want
-Node *SessionManager::nodeForFile(const QString &fileName, Project *project)
-{
- Node *node = 0;
- foreach (Node *n, nodesForFile(fileName, project)) {
- // prefer file nodes
- if (!node || (node->nodeType() != FileNodeType && n->nodeType() == FileNodeType))
- node = n;
- }
- return node;
-}
-
Project *SessionManager::projectForFile(const QString &fileName)
{
if (debug)
qDebug() << "SessionManager::projectForFile(" << fileName << ")";
const QList<Project *> &projectList = projects();
-
- // Check current project first
- Project *currentProject = ProjectExplorerPlugin::currentProject();
- if (currentProject && d->projectContainsFile(currentProject, fileName))
- return currentProject;
-
foreach (Project *p, projectList)
- if (p != currentProject && d->projectContainsFile(p, fileName))
+ if (d->projectContainsFile(p, fileName))
return p;
return 0;
@@ -607,7 +595,7 @@ bool SessionManagerPrivate::projectContainsFile(Project *p, const QString &fileN
return m_projectFileCache.value(p).contains(fileName);
}
-void SessionManager::configureEditor(Core::IEditor *editor, const QString &fileName)
+void SessionManager::configureEditor(IEditor *editor, const QString &fileName)
{
if (TextEditor::BaseTextEditor *textEditor = qobject_cast<TextEditor::BaseTextEditor*>(editor)) {
Project *project = projectForFile(fileName);
@@ -620,7 +608,7 @@ void SessionManager::configureEditor(Core::IEditor *editor, const QString &fileN
void SessionManager::configureEditors(Project *project)
{
foreach (IDocument *document, DocumentModel::openedDocuments()) {
- if (d->projectContainsFile(project, document->filePath())) {
+ if (d->projectContainsFile(project, document->filePath().toString())) {
foreach (IEditor *editor, DocumentModel::editorsForDocument(document)) {
if (TextEditor::BaseTextEditor *textEditor = qobject_cast<TextEditor::BaseTextEditor*>(editor)) {
project->editorConfiguration()->configureEditor(textEditor);
@@ -714,7 +702,7 @@ QStringList SessionManager::sessions()
{
if (d->m_sessions.isEmpty()) {
// We are not initialized yet, so do that now
- QDir sessionDir(Core::ICore::userResourcePath());
+ QDir sessionDir(ICore::userResourcePath());
QList<QFileInfo> sessionFiles = sessionDir.entryInfoList(QStringList() << QLatin1String("*.qws"), QDir::NoFilter, QDir::Time);
foreach (const QFileInfo &fileInfo, sessionFiles) {
if (fileInfo.completeBaseName() != QLatin1String("default"))
@@ -758,7 +746,7 @@ bool SessionManager::renameSession(const QString &original, const QString &newNa
*/
bool SessionManager::confirmSessionDelete(const QString &session)
{
- return QMessageBox::question(Core::ICore::mainWindow(),
+ return QMessageBox::question(ICore::mainWindow(),
tr("Delete Session"),
tr("Delete session %1?").arg(session),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes;
@@ -882,7 +870,7 @@ void SessionManagerPrivate::restoreProjects(const QStringList &fileList)
QString errors;
QList<Project *> projects = ProjectExplorerPlugin::openProjects(fileList, &errors);
if (!errors.isEmpty())
- QMessageBox::critical(Core::ICore::mainWindow(), SessionManager::tr("Failed to open project"), errors);
+ QMessageBox::critical(ICore::mainWindow(), SessionManager::tr("Failed to open project"), errors);
foreach (Project *p, projects)
m_failedProjects.removeAll(p->projectFilePath().toString());
}
@@ -1023,15 +1011,7 @@ void SessionManager::projectDisplayNameChanged()
{
Project *pro = qobject_cast<Project*>(m_instance->sender());
if (pro) {
- Node *currentNode = 0;
- if (ProjectExplorerPlugin::currentProject() == pro)
- currentNode = ProjectExplorerPlugin::currentNode();
-
d->m_sessionNode->projectDisplayNameChanged(pro->rootProjectNode());
-
- if (currentNode)
- ProjectExplorerPlugin::setCurrentNode(currentNode);
-
emit m_instance->projectDisplayNameChanged(pro);
}
}
diff --git a/src/plugins/projectexplorer/session.h b/src/plugins/projectexplorer/session.h
index f79ab80113e..535bee5acaa 100644
--- a/src/plugins/projectexplorer/session.h
+++ b/src/plugins/projectexplorer/session.h
@@ -117,8 +117,8 @@ public:
static SessionNode *sessionNode();
static Project *projectForNode(Node *node);
- static QList<Node *> nodesForFile(const QString &fileName, Project *project = 0);
- static Node *nodeForFile(const QString &fileName, Project *project = 0);
+ static QList<Node *> nodesForFile(const QString &fileName);
+ static Node *nodeForFile(const QString &fileName);
static Project *projectForFile(const QString &fileName);
static QStringList projectsForSessionName(const QString &session);
diff --git a/src/plugins/projectexplorer/settingsaccessor.cpp b/src/plugins/projectexplorer/settingsaccessor.cpp
index 2f7378f5b56..802e5c424a1 100644
--- a/src/plugins/projectexplorer/settingsaccessor.cpp
+++ b/src/plugins/projectexplorer/settingsaccessor.cpp
@@ -47,6 +47,7 @@
#include <utils/qtcprocess.h>
#include <QApplication>
+#include <QDir>
using namespace Utils;
@@ -500,7 +501,7 @@ public:
bool isValid() const;
QVariantMap map;
- Utils::FileName path;
+ FileName path;
};
int firstVersion() const { return m_upgraders.isEmpty() ? -1 : m_upgraders.first()->version(); }
@@ -513,11 +514,85 @@ public:
return m_upgraders.at(pos);
return 0;
}
- Settings bestSettings(const SettingsAccessor *accessor, const QList<Utils::FileName> &pathList);
+ Settings bestSettings(const SettingsAccessor *accessor, const QList<FileName> &pathList);
QList<VersionUpgrader *> m_upgraders;
- Utils::PersistentSettingsWriter *m_writer;
+ PersistentSettingsWriter *m_writer;
};
+
+// Return path to shared directory for .user files, create if necessary.
+static inline QString determineSharedUserFileDir()
+{
+ const char userFilePathVariable[] = "QTC_USER_FILE_PATH";
+ if (!qEnvironmentVariableIsSet(userFilePathVariable))
+ return QString();
+ const QFileInfo fi(QFile::decodeName(qgetenv(userFilePathVariable)));
+ const QString path = fi.absoluteFilePath();
+ if (fi.isDir() || fi.isSymLink())
+ return path;
+ if (fi.exists()) {
+ qWarning() << userFilePathVariable << '=' << QDir::toNativeSeparators(path)
+ << " points to an existing file";
+ return QString();
+ }
+ QDir dir;
+ if (!dir.mkpath(path)) {
+ qWarning() << "Cannot create: " << QDir::toNativeSeparators(path);
+ return QString();
+ }
+ return path;
+}
+
+static QString sharedUserFileDir()
+{
+ static const QString sharedDir = determineSharedUserFileDir();
+ return sharedDir;
+}
+
+// Return a suitable relative path to be created under the shared .user directory.
+static QString makeRelative(QString path)
+{
+ const QChar slash(QLatin1Char('/'));
+ // Windows network shares: "//server.domain-a.com/foo' -> 'serverdomainacom/foo'
+ if (path.startsWith(QLatin1String("//"))) {
+ path.remove(0, 2);
+ const int nextSlash = path.indexOf(slash);
+ if (nextSlash > 0) {
+ for (int p = nextSlash; p >= 0; --p) {
+ if (!path.at(p).isLetterOrNumber())
+ path.remove(p, 1);
+ }
+ }
+ return path;
+ }
+ // Windows drives: "C:/foo' -> 'c/foo'
+ if (path.size() > 3 && path.at(1) == QLatin1Char(':')) {
+ path.remove(1, 1);
+ path[0] = path.at(0).toLower();
+ return path;
+ }
+ if (path.startsWith(slash)) // Standard UNIX paths: '/foo' -> 'foo'
+ path.remove(0, 1);
+ return path;
+}
+
+// Return complete file path of the .user file.
+static FileName userFilePath(const Project *project, const QString &suffix)
+{
+ FileName result;
+ const FileName projectFilePath = project->projectFilePath();
+ if (sharedUserFileDir().isEmpty()) {
+ result = projectFilePath;
+ } else {
+ // Recreate the relative project file hierarchy under the shared directory.
+ // PersistentSettingsWriter::write() takes care of creating the path.
+ result = FileName::fromString(sharedUserFileDir());
+ result.appendString(QLatin1Char('/') + makeRelative(projectFilePath.toString()));
+ }
+ result.appendString(suffix);
+ return result;
+}
+
} // end namespace
SettingsAccessor::SettingsAccessor(Project *project) :
@@ -713,7 +788,7 @@ QVariantMap SettingsAccessor::upgradeSettings(const QVariantMap &data) const
* Returns \c true if the settings are not usable anymore and \c false otherwise.
*/
SettingsAccessor::ProceedInfo SettingsAccessor::reportIssues(const QVariantMap &data,
- const Utils::FileName &path,
+ const FileName &path,
QWidget *parent) const
{
IssueInfo issue = findIssues(data, path);
@@ -744,12 +819,11 @@ SettingsAccessor::ProceedInfo SettingsAccessor::reportIssues(const QVariantMap &
*
* Returns a IssueInfo object which is then used by reportIssues.
*/
-SettingsAccessor::IssueInfo SettingsAccessor::findIssues(const QVariantMap &data, const Utils::FileName &path) const
+SettingsAccessor::IssueInfo SettingsAccessor::findIssues(const QVariantMap &data, const FileName &path) const
{
SettingsAccessor::IssueInfo result;
- Utils::FileName defaultSettingsPath = project()->projectFilePath();
- defaultSettingsPath.appendString(m_userSuffix);
+ const FileName defaultSettingsPath = userFilePath(project(), m_userSuffix);
int version = versionFromMap(data);
if (!path.exists()) {
@@ -879,7 +953,7 @@ bool SettingsAccessor::saveSettings(const QVariantMap &map, QWidget *parent) con
QVariantMap data = prepareToSaveSettings(map);
- Utils::FileName path = FileName::fromString(defaultFileName(m_userSuffix));
+ FileName path = FileName::fromString(defaultFileName(m_userSuffix));
if (!d->m_writer || d->m_writer->fileName() != path) {
delete d->m_writer;
d->m_writer = new PersistentSettingsWriter(path, QLatin1String("QtCreatorProject"));
@@ -907,17 +981,21 @@ bool SettingsAccessor::addVersionUpgrader(VersionUpgrader *upgrader)
/* Will always return the default name first (if applicable) */
QList<FileName> SettingsAccessor::settingsFiles(const QString &suffix) const
{
- QList<Utils::FileName> result;
+ QList<FileName> result;
- const Utils::FileName baseName = project()->projectFilePath();
- QFileInfo fi = baseName.toFileInfo();
- QDir dir = QDir(fi.absolutePath());
- QString filter = fi.fileName() + suffix + QLatin1Char('*');
+ QFileInfoList list;
+ const QFileInfo pfi = project()->projectFilePath().toFileInfo();
+ const QStringList filter(pfi.fileName() + suffix + QLatin1Char('*'));
- QFileInfoList list = dir.entryInfoList(QStringList() << filter, QDir::Files);
+ if (!sharedUserFileDir().isEmpty()) {
+ const QString sharedPath = sharedUserFileDir() + QLatin1Char('/')
+ + makeRelative(pfi.absolutePath());
+ list.append(QDir(sharedPath).entryInfoList(filter, QDir::Files));
+ }
+ list.append(QDir(pfi.dir()).entryInfoList(filter, QDir::Files));
foreach (const QFileInfo &fi, list) {
- const Utils::FileName path = Utils::FileName::fromString(fi.absoluteFilePath());
+ const FileName path = FileName::fromString(fi.absoluteFilePath());
if (!result.contains(path)) {
if (path.endsWith(suffix))
result.prepend(path);
@@ -936,7 +1014,7 @@ QByteArray SettingsAccessor::creatorId()
QString SettingsAccessor::defaultFileName(const QString &suffix) const
{
- return project()->projectFilePath().toString() + suffix;
+ return userFilePath(project(), suffix).toString();
}
int SettingsAccessor::currentVersion() const
@@ -949,7 +1027,7 @@ int SettingsAccessor::firstSupportedVersion() const
return d->firstVersion();
}
-Utils::FileName SettingsAccessor::backupName(const QVariantMap &data) const
+FileName SettingsAccessor::backupName(const QVariantMap &data) const
{
QString backupName = defaultFileName(m_userSuffix);
const QByteArray oldEnvironmentId = environmentIdFromMap(data);
@@ -963,7 +1041,7 @@ Utils::FileName SettingsAccessor::backupName(const QVariantMap &data) const
else
backupName += QLatin1Char('.') + QString::number(oldVersion);
}
- return Utils::FileName::fromString(backupName);
+ return FileName::fromString(backupName);
}
void SettingsAccessor::backupUserFile() const
@@ -984,7 +1062,7 @@ void SettingsAccessor::backupUserFile() const
QVariantMap SettingsAccessor::readUserSettings(QWidget *parent) const
{
SettingsAccessorPrivate::Settings result;
- QList<Utils::FileName> fileList = settingsFiles(m_userSuffix);
+ QList<FileName> fileList = settingsFiles(m_userSuffix);
if (fileList.isEmpty()) // No settings found at all.
return result.map;
@@ -1034,10 +1112,10 @@ QVariantMap SettingsAccessor::readSharedSettings(QWidget *parent) const
}
SettingsAccessorPrivate::Settings SettingsAccessorPrivate::bestSettings(const SettingsAccessor *accessor,
- const QList<Utils::FileName> &pathList)
+ const QList<FileName> &pathList)
{
Settings bestMatch;
- foreach (const Utils::FileName &path, pathList) {
+ foreach (const FileName &path, pathList) {
QVariantMap tmp = accessor->readFile(path);
int version = SettingsAccessor::versionFromMap(tmp);
@@ -1082,9 +1160,9 @@ bool SettingsAccessorPrivate::Settings::isValid() const
return SettingsAccessor::versionFromMap(map) > -1 && !path.isEmpty();
}
-QVariantMap SettingsAccessor::readFile(const Utils::FileName &path) const
+QVariantMap SettingsAccessor::readFile(const FileName &path) const
{
- Utils::PersistentSettingsReader reader;
+ PersistentSettingsReader reader;
if (!reader.load(path))
return QVariantMap();
@@ -2284,7 +2362,7 @@ void UserFileVersion11Upgrader::parseQtversionFile()
{
PersistentSettingsReader reader;
QFileInfo settingsLocation = QFileInfo(Core::ICore::settings()->fileName());
- reader.load(Utils::FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/qtversion.xml")));
+ reader.load(FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/qtversion.xml")));
QVariantMap data = reader.restoreValues();
int count = data.value(QLatin1String("QtVersion.Count"), 0).toInt();
@@ -2323,7 +2401,7 @@ void UserFileVersion11Upgrader::parseToolChainFile()
{
PersistentSettingsReader reader;
QFileInfo settingsLocation(Core::ICore::settings()->fileName());
- reader.load(Utils::FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/toolChains.xml")));
+ reader.load(FileName::fromString(settingsLocation.absolutePath() + QLatin1String("/toolChains.xml")));
QVariantMap data = reader.restoreValues();
int count = data.value(QLatin1String("ToolChain.Count"), 0).toInt();
for (int i = 0; i < count; ++i) {
diff --git a/src/plugins/projectexplorer/targetsettingspanel.cpp b/src/plugins/projectexplorer/targetsettingspanel.cpp
index 23b34210378..376a8ef0aa2 100644
--- a/src/plugins/projectexplorer/targetsettingspanel.cpp
+++ b/src/plugins/projectexplorer/targetsettingspanel.cpp
@@ -301,7 +301,7 @@ void TargetSettingsPanelWidget::menuShown(int targetIndex)
void TargetSettingsPanelWidget::changeActionTriggered(QAction *action)
{
- Kit *k = KitManager::find(action->data().value<Core::Id>());
+ Kit *k = KitManager::find(action->data().value<Id>());
Target *sourceTarget = m_targets.at(m_menuTargetIndex);
Target *newTarget = cloneTarget(sourceTarget, k);
@@ -314,7 +314,7 @@ void TargetSettingsPanelWidget::changeActionTriggered(QAction *action)
void TargetSettingsPanelWidget::duplicateActionTriggered(QAction *action)
{
- Kit *k = KitManager::find(action->data().value<Core::Id>());
+ Kit *k = KitManager::find(action->data().value<Id>());
Target *newTarget = cloneTarget(m_targets.at(m_menuTargetIndex), k);
if (newTarget) {
@@ -326,8 +326,8 @@ void TargetSettingsPanelWidget::duplicateActionTriggered(QAction *action)
void TargetSettingsPanelWidget::addActionTriggered(QAction *action)
{
const QVariant data = action->data();
- if (data.canConvert<Core::Id>()) { // id of kit
- Kit *k = KitManager::find(action->data().value<Core::Id>());
+ if (data.canConvert<Id>()) { // id of kit
+ Kit *k = KitManager::find(action->data().value<Id>());
QTC_ASSERT(!m_project->target(k), return);
Target *target = m_project->createTarget(k);
@@ -427,7 +427,7 @@ Target *TargetSettingsPanelWidget::cloneTarget(Target *sourceTarget, Kit *k)
if (fatalError) {
// That could be a more granular error message
- QMessageBox::critical(Core::ICore::mainWindow(),
+ QMessageBox::critical(ICore::mainWindow(),
tr("Incompatible Kit"),
tr("Kit %1 is incompatible with kit %2.")
.arg(sourceTarget->kit()->displayName())
@@ -460,7 +460,7 @@ Target *TargetSettingsPanelWidget::cloneTarget(Target *sourceTarget, Kit *k)
+ runconfigurationError.join(QLatin1Char('\n'));
}
- QMessageBox msgBox(Core::ICore::mainWindow());
+ QMessageBox msgBox(ICore::mainWindow());
msgBox.setIcon(QMessageBox::Warning);
msgBox.setWindowTitle(tr("Partially Incompatible Kit"));
msgBox.setText(tr("Some configurations could not be copied."));
diff --git a/src/plugins/projectexplorer/targetsetuppage.cpp b/src/plugins/projectexplorer/targetsetuppage.cpp
index ad5981a147c..528224184ea 100644
--- a/src/plugins/projectexplorer/targetsetuppage.cpp
+++ b/src/plugins/projectexplorer/targetsetuppage.cpp
@@ -149,7 +149,7 @@ TargetSetupPage::TargetSetupPage(QWidget *parent) :
m_baseLayout(0),
m_firstWidget(0),
m_ui(new TargetSetupPageUi),
- m_importWidget(new Internal::ImportWidget(this)),
+ m_importWidget(new ImportWidget(this)),
m_spacer(new QSpacerItem(0,0, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding)),
m_forceOptionHint(false)
{
@@ -213,7 +213,7 @@ void TargetSetupPage::setRequiredKitMatcher(const KitMatcher &matcher)
QList<Core::Id> TargetSetupPage::selectedKits() const
{
QList<Core::Id> result;
- QMap<Core::Id, Internal::TargetSetupWidget *>::const_iterator it, end;
+ QMap<Core::Id, TargetSetupWidget *>::const_iterator it, end;
it = m_widgets.constBegin();
end = m_widgets.constEnd();
diff --git a/src/plugins/projectexplorer/taskmodel.cpp b/src/plugins/projectexplorer/taskmodel.cpp
index 7a3ab4d9c9a..d3605c03471 100644
--- a/src/plugins/projectexplorer/taskmodel.cpp
+++ b/src/plugins/projectexplorer/taskmodel.cpp
@@ -238,7 +238,8 @@ int TaskModel::columnCount(const QModelIndex &parent) const
QVariant TaskModel::data(const QModelIndex &index, int role) const
{
- if (!index.isValid() || index.row() >= m_tasks.count() || index.column() != 0)
+ int row = index.row();
+ if (!index.isValid() || row < 0 || row >= m_tasks.count() || index.column() != 0)
return QVariant();
if (role == TaskModel::File)
@@ -264,9 +265,10 @@ QVariant TaskModel::data(const QModelIndex &index, int role) const
Task TaskModel::task(const QModelIndex &index) const
{
- if (!index.isValid())
+ int row = index.row();
+ if (!index.isValid() || row < 0 || row >= m_tasks.count())
return Task();
- return m_tasks.at(index.row());
+ return m_tasks.at(row);
}
QList<Core::Id> TaskModel::categoryIds() const
@@ -317,10 +319,11 @@ int TaskModel::sizeOfLineNumber(const QFont &font)
void TaskModel::setFileNotFound(const QModelIndex &idx, bool b)
{
- if (idx.isValid() && idx.row() < m_tasks.count()) {
- m_fileNotFound.insert(m_tasks[idx.row()].file.toUserOutput(), b);
- emit dataChanged(idx, idx);
- }
+ int row = idx.row();
+ if (!idx.isValid() || row < 0 || row >= m_tasks.count())
+ return;
+ m_fileNotFound.insert(m_tasks[row].file.toUserOutput(), b);
+ emit dataChanged(idx, idx);
}
/////
diff --git a/src/plugins/projectexplorer/toolchainmanager.cpp b/src/plugins/projectexplorer/toolchainmanager.cpp
index 8f1a84cff80..f9282497438 100644
--- a/src/plugins/projectexplorer/toolchainmanager.cpp
+++ b/src/plugins/projectexplorer/toolchainmanager.cpp
@@ -121,7 +121,7 @@ ToolChainManager::~ToolChainManager()
m_instance = 0;
}
-QObject *ToolChainManager::instance()
+ToolChainManager *ToolChainManager::instance()
{
return m_instance;
}
diff --git a/src/plugins/projectexplorer/toolchainmanager.h b/src/plugins/projectexplorer/toolchainmanager.h
index 704899bcfde..bbfcd000405 100644
--- a/src/plugins/projectexplorer/toolchainmanager.h
+++ b/src/plugins/projectexplorer/toolchainmanager.h
@@ -54,7 +54,7 @@ class PROJECTEXPLORER_EXPORT ToolChainManager : public QObject
Q_OBJECT
public:
- static QObject *instance();
+ static ToolChainManager *instance();
~ToolChainManager();
static QList<ToolChain *> toolChains();
diff --git a/src/plugins/projectexplorer/toolchainoptionspage.cpp b/src/plugins/projectexplorer/toolchainoptionspage.cpp
index 5ff54a0cbe8..24e9a02c09a 100644
--- a/src/plugins/projectexplorer/toolchainoptionspage.cpp
+++ b/src/plugins/projectexplorer/toolchainoptionspage.cpp
@@ -38,9 +38,10 @@
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
+#include <utils/algorithm.h>
#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
-#include <utils/algorithm.h>
+#include <utils/treemodel.h>
#include <QAction>
#include <QApplication>
@@ -50,262 +51,268 @@
#include <QMenu>
#include <QMessageBox>
#include <QPushButton>
-#include <QSignalMapper>
#include <QSpacerItem>
#include <QTextStream>
#include <QTreeView>
#include <QVBoxLayout>
+using namespace Utils;
+
namespace ProjectExplorer {
namespace Internal {
-class ToolChainNode
+class ToolChainTreeItem : public TreeItem
{
public:
- explicit ToolChainNode(ToolChainNode *p, ToolChain *tc = 0, bool c = false) :
- parent(p), toolChain(tc), changed(c)
+ ToolChainTreeItem(ToolChain *tc, bool c) :
+ toolChain(tc), changed(c)
{
- if (p)
- p->childNodes.append(this);
- widget = tc ? tc->configurationWidget() : 0;
- if (widget && tc->isAutoDetected())
- widget->makeReadOnly();
+ widget = tc->configurationWidget();
+ if (widget) {
+ if (tc->isAutoDetected())
+ widget->makeReadOnly();
+ QObject::connect(widget, &ToolChainConfigWidget::dirty, [this] {
+ changed = true;
+ update();
+ });
+ }
}
- ~ToolChainNode()
+ QVariant data(int column, int role) const
{
- // Do not delete tool chain, we do not own it.
-
- for (int i = childNodes.size(); --i >= 0; ) {
- ToolChainNode *child = childNodes.at(i);
- child->parent = 0;
- delete child;
+ switch (role) {
+ case Qt::DisplayRole:
+ if (column == 0)
+ return toolChain->displayName();
+ return toolChain->typeDisplayName();
+
+ case Qt::FontRole: {
+ QFont font;
+ font.setBold(changed);
+ return font;
+ }
+
+ case Qt::ToolTipRole:
+ return ToolChainOptionsPage::tr("<nobr><b>ABI:</b> %1").arg(
+ changed ? ToolChainOptionsPage::tr("not up-to-date")
+ : toolChain->targetAbi().toString());
}
-
- if (parent)
- parent->childNodes.removeOne(this);
+ return QVariant();
}
- ToolChainNode *parent;
- QList<ToolChainNode *> childNodes;
ToolChain *toolChain;
ToolChainConfigWidget *widget;
bool changed;
};
// --------------------------------------------------------------------------
-// ToolChainModel
+// ToolChainOptionsWidget
// --------------------------------------------------------------------------
-ToolChainModel::ToolChainModel(QObject *parent) :
- QAbstractItemModel(parent)
+class ToolChainOptionsWidget : public QWidget
{
- connect(ToolChainManager::instance(), SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
- this, SLOT(addToolChain(ProjectExplorer::ToolChain*)));
- connect(ToolChainManager::instance(), SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)),
- this, SLOT(removeToolChain(ProjectExplorer::ToolChain*)));
+public:
+ ToolChainOptionsWidget()
+ {
+ m_factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>(
+ [](ToolChainFactory *factory) { return factory->canCreate();});
- m_root = new ToolChainNode(0);
- m_autoRoot = new ToolChainNode(m_root);
- m_manualRoot = new ToolChainNode(m_root);
+ m_model.setHeader(QStringList() << tr("Name") << tr("Type"));
+ m_autoRoot = new TreeItem(QStringList() << tr("Auto-detected") << QString());
+ m_manualRoot = new TreeItem(QStringList() << tr("Manual") << QString());
+ m_model.rootItem()->appendChild(m_autoRoot);
+ m_model.rootItem()->appendChild(m_manualRoot);
+ foreach (ToolChain *tc, ToolChainManager::toolChains()) {
+ TreeItem *parent = tc->isAutoDetected() ? m_autoRoot : m_manualRoot;
+ parent->appendChild(new ToolChainTreeItem(tc, false));
+ }
- foreach (ToolChain *tc, ToolChainManager::toolChains())
- addToolChain(tc);
-}
+ m_toolChainView = new QTreeView(this);
+ m_toolChainView->setUniformRowHeights(true);
+ m_toolChainView->setSelectionMode(QAbstractItemView::SingleSelection);
+ m_toolChainView->setSelectionBehavior(QAbstractItemView::SelectRows);
+ m_toolChainView->setModel(&m_model);
+ m_toolChainView->header()->setStretchLastSection(false);
+ m_toolChainView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
+ m_toolChainView->header()->setSectionResizeMode(1, QHeaderView::Stretch);
+ m_toolChainView->expandAll();
-ToolChainModel::~ToolChainModel()
-{
- delete m_root;
-}
+ m_addButton = new QPushButton(tr("Add"), this);
+ auto addMenu = new QMenu;
+ foreach (ToolChainFactory *factory, m_factories) {
+ QAction *action = new QAction(addMenu);
+ action->setText(factory->displayName());
+ connect(action, &QAction::triggered, [this, factory] { createToolChain(factory); });
+ addMenu->addAction(action);
+ }
+ m_addButton->setMenu(addMenu);
-QModelIndex ToolChainModel::index(int row, int column, const QModelIndex &parent) const
-{
- if (!parent.isValid()) {
- if (row >= 0 && row < m_root->childNodes.count())
- return createIndex(row, column, m_root->childNodes.at(row));
- }
- ToolChainNode *node = static_cast<ToolChainNode *>(parent.internalPointer());
- if (row < node->childNodes.count() && column < 2)
- return createIndex(row, column, static_cast<void *>(node->childNodes.at(row)));
- else
- return QModelIndex();
-}
+ m_cloneButton = new QPushButton(tr("Clone"), this);
+ connect(m_cloneButton, &QAbstractButton::clicked, [this] { createToolChain(0); });
-QModelIndex ToolChainModel::index(const QModelIndex &topIdx, ToolChain *tc) const
-{
- ToolChainNode *current = m_root;
- if (topIdx.isValid())
- current = static_cast<ToolChainNode *>(topIdx.internalPointer());
- QTC_ASSERT(current, return QModelIndex());
-
- if (current->toolChain == tc)
- return topIdx;
-
- for (int i = 0; i < current->childNodes.count(); ++i) {
- QModelIndex result = index(index(current->childNodes.at(i)), tc);
- if (result.isValid())
- return result;
- }
- return QModelIndex();
-}
+ m_delButton = new QPushButton(tr("Remove"), this);
-QModelIndex ToolChainModel::parent(const QModelIndex &idx) const
-{
- ToolChainNode *node = static_cast<ToolChainNode *>(idx.internalPointer());
- if (node->parent == m_root)
- return QModelIndex();
- return index(node->parent);
-}
+ m_container = new DetailsWidget(this);
+ m_container->setState(DetailsWidget::NoSummary);
+ m_container->setVisible(false);
-int ToolChainModel::rowCount(const QModelIndex &parent) const
-{
- if (!parent.isValid())
- return m_root->childNodes.count();
- ToolChainNode *node = static_cast<ToolChainNode *>(parent.internalPointer());
- return node->childNodes.count();
-}
+ auto 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));
-int ToolChainModel::columnCount(const QModelIndex &parent) const
-{
- Q_UNUSED(parent);
- return 2;
-}
+ auto verticalLayout = new QVBoxLayout;
+ verticalLayout->addWidget(m_toolChainView);
+ verticalLayout->addWidget(m_container);
-QVariant ToolChainModel::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid())
- return QVariant();
+ auto horizontalLayout = new QHBoxLayout(this);
+ horizontalLayout->addLayout(verticalLayout);
+ horizontalLayout->addLayout(buttonLayout);
- ToolChainNode *node = static_cast<ToolChainNode *>(index.internalPointer());
- QTC_ASSERT(node, return QVariant());
- if (node == m_autoRoot && index.column() == 0 && role == Qt::DisplayRole)
- return tr("Auto-detected");
- if (node == m_manualRoot && index.column() == 0 && role == Qt::DisplayRole)
- return tr("Manual");
- if (node->toolChain) {
- if (role == Qt::FontRole) {
- QFont f = QApplication::font();
- if (node->changed)
- f.setBold(true);
- return f;
- }
- if (role == Qt::DisplayRole) {
- if (index.column() == 0)
- return node->toolChain->displayName();
- return node->toolChain->typeDisplayName();
- }
- if (role == Qt::ToolTipRole) {
- return tr("<nobr><b>ABI:</b> %1")
- .arg(node->changed ? tr("not up-to-date") : node->toolChain->targetAbi().toString());
- }
+ connect(ToolChainManager::instance(), &ToolChainManager::toolChainAdded,
+ this, &ToolChainOptionsWidget::addToolChain);
+ connect(ToolChainManager::instance(), &ToolChainManager::toolChainRemoved,
+ this, &ToolChainOptionsWidget::removeToolChain);
+
+ connect(m_toolChainView->selectionModel(), &QItemSelectionModel::currentChanged,
+ this, &ToolChainOptionsWidget::toolChainSelectionChanged);
+ connect(ToolChainManager::instance(), &ToolChainManager::toolChainsChanged,
+ this, &ToolChainOptionsWidget::toolChainSelectionChanged);
+
+ connect(m_delButton, &QAbstractButton::clicked, [this] {
+ if (ToolChainTreeItem *item = currentTreeItem())
+ markForRemoval(item);
+ });
+
+ updateState();
}
- return QVariant();
-}
-Qt::ItemFlags ToolChainModel::flags(const QModelIndex &index) const
-{
- if (!index.isValid())
- return 0;
+ void toolChainSelectionChanged();
+ void updateState();
+ void createToolChain(ToolChainFactory *factory);
+ ToolChainTreeItem *currentTreeItem();
- ToolChainNode *node = static_cast<ToolChainNode *>(index.internalPointer());
- Q_ASSERT(node);
- if (!node->toolChain)
- return Qt::ItemIsEnabled;
+ void markForRemoval(ToolChainTreeItem *item);
+ void addToolChain(ProjectExplorer::ToolChain *);
+ void removeToolChain(ProjectExplorer::ToolChain *);
- return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
-}
+ void apply();
-QVariant ToolChainModel::headerData(int section, Qt::Orientation orientation, int role) const
-{
- if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
- return section == 0 ? tr("Name") : tr("Type");
- return QVariant();
-}
+ public:
+ TreeModel m_model;
+ QList<ToolChainFactory *> m_factories;
+ QTreeView *m_toolChainView;
+ DetailsWidget *m_container;
+ QPushButton *m_addButton;
+ QPushButton *m_cloneButton;
+ QPushButton *m_delButton;
-ToolChain *ToolChainModel::toolChain(const QModelIndex &index)
-{
- if (!index.isValid())
- return 0;
- ToolChainNode *node = static_cast<ToolChainNode *>(index.internalPointer());
- Q_ASSERT(node);
- return node->toolChain;
-}
+ TreeItem *m_autoRoot;
+ TreeItem *m_manualRoot;
-int ToolChainModel::manualToolChains() const
-{
- return m_manualRoot->childNodes.count();
-}
+ QList<ToolChainTreeItem *> m_toAddList;
+ QList<ToolChainTreeItem *> m_toRemoveList;
+};
-ToolChainConfigWidget *ToolChainModel::widget(const QModelIndex &index)
+void ToolChainOptionsWidget::markForRemoval(ToolChainTreeItem *item)
{
- if (!index.isValid())
- return 0;
- ToolChainNode *node = static_cast<ToolChainNode *>(index.internalPointer());
- Q_ASSERT(node);
- return node->widget;
+ m_model.removeItem(item);
+ if (m_toAddList.contains(item)) {
+ delete item->toolChain;
+ item->toolChain = 0;
+ m_toAddList.removeOne(item);
+ delete item;
+ } else {
+ m_toRemoveList.append(item);
+ }
}
-bool ToolChainModel::isDirty() const
+void ToolChainOptionsWidget::addToolChain(ToolChain *tc)
{
- return Utils::anyOf(m_manualRoot->childNodes,
- [](ToolChainNode *n) {
- return n->changed;
- });
-}
+ foreach (ToolChainTreeItem *n, m_toAddList) {
+ if (n->toolChain == tc) {
+ // do not delete n: Still used elsewhere!
+ m_toAddList.removeOne(n);
+ return;
+ }
+ }
-bool ToolChainModel::isDirty(ToolChain *tc) const
-{
- return Utils::anyOf(m_manualRoot->childNodes,
- [tc](ToolChainNode *n) {
- return n->toolChain == tc && n->changed;
- });
+ TreeItem *parent = m_model.rootItem()->child(tc->isAutoDetected() ? 0 : 1);
+ parent->appendChild(new ToolChainTreeItem(tc, false));
+
+ updateState();
}
-void ToolChainModel::setDirty()
+void ToolChainOptionsWidget::removeToolChain(ToolChain *tc)
{
- ToolChainConfigWidget *w = qobject_cast<ToolChainConfigWidget *>(sender());
- foreach (ToolChainNode *n, m_manualRoot->childNodes) {
- if (n->widget == w) {
- n->changed = true;
- emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
+ foreach (ToolChainTreeItem *n, m_toRemoveList) {
+ if (n->toolChain == tc) {
+ m_toRemoveList.removeOne(n);
+ delete n;
+ return;
}
}
+
+ TreeItem *parent = m_model.rootItem()->child(tc->isAutoDetected() ? 0 : 1);
+ foreach (ToolChainTreeItem *item, m_model.treeLevelItems<ToolChainTreeItem *>(1, parent)) {
+ if (item->toolChain == tc) {
+ m_model.removeItem(item);
+ delete item;
+ break;
+ }
+ }
+
+ updateState();
+}
+
+void ToolChainOptionsWidget::toolChainSelectionChanged()
+{
+ ToolChainTreeItem *item = currentTreeItem();
+ QWidget *oldWidget = m_container->takeWidget(); // Prevent deletion.
+ if (oldWidget)
+ oldWidget->setVisible(false);
+
+ QWidget *currentTcWidget = item ? item->widget : 0;
+
+ m_container->setWidget(currentTcWidget);
+ m_container->setVisible(currentTcWidget != 0);
+ updateState();
}
-void ToolChainModel::apply()
+void ToolChainOptionsWidget::apply()
{
// Remove unused tool chains:
- QList<ToolChainNode *> nodes = m_toRemoveList;
- foreach (ToolChainNode *n, nodes) {
- Q_ASSERT(!n->parent);
+ QList<ToolChainTreeItem *> nodes = m_toRemoveList;
+ foreach (ToolChainTreeItem *n, nodes)
ToolChainManager::deregisterToolChain(n->toolChain);
- }
+
Q_ASSERT(m_toRemoveList.isEmpty());
// Update tool chains:
- foreach (ToolChainNode *n, m_manualRoot->childNodes) {
- Q_ASSERT(n);
- if (n->changed) {
- Q_ASSERT(n->toolChain);
- if (n->widget)
- n->widget->apply();
- n->changed = false;
-
- emit dataChanged(index(n, 0), index(n, columnCount(QModelIndex())));
+ foreach (ToolChainTreeItem *item, m_model.treeLevelItems<ToolChainTreeItem *>(1, m_manualRoot)) {
+ if (item->changed) {
+ Q_ASSERT(item->toolChain);
+ if (item->widget)
+ item->widget->apply();
+ item->changed = false;
+ item->update();
}
}
// Add new (and already updated) tool chains
QStringList removedTcs;
nodes = m_toAddList;
- foreach (ToolChainNode *n, nodes) {
+ foreach (ToolChainTreeItem *n, nodes) {
if (!ToolChainManager::registerToolChain(n->toolChain))
removedTcs << n->toolChain->displayName();
}
//
- foreach (ToolChainNode *n, m_toAddList) {
- markForRemoval(n->toolChain);
- }
+ foreach (ToolChainTreeItem *n, m_toAddList)
+ markForRemoval(n);
+
qDeleteAll(m_toAddList);
if (removedTcs.count() == 1) {
@@ -326,120 +333,59 @@ void ToolChainModel::apply()
}
}
-void ToolChainModel::markForRemoval(ToolChain *tc)
-{
- ToolChainNode *node = findToolChain(m_manualRoot->childNodes, tc);
- if (node) {
- emit beginRemoveRows(index(m_manualRoot), m_manualRoot->childNodes.indexOf(node), m_manualRoot->childNodes.indexOf(node));
- m_manualRoot->childNodes.removeOne(node);
- node->parent = 0;
- if (m_toAddList.contains(node)) {
- delete node->toolChain;
- node->toolChain = 0;
- m_toAddList.removeOne(node);
- delete node;
- } else {
- m_toRemoveList.append(node);
- }
- emit endRemoveRows();
- }
-}
-
-void ToolChainModel::markForAddition(ToolChain *tc)
+void ToolChainOptionsWidget::createToolChain(ToolChainFactory *factory)
{
- int pos = m_manualRoot->childNodes.size();
- emit beginInsertRows(index(m_manualRoot), pos, pos);
+ ToolChain *tc = 0;
- ToolChainNode *node = createNode(m_manualRoot, tc, true);
- m_toAddList.append(node);
+ if (factory) {
+ // Clone.
+ QTC_CHECK(factory->canCreate());
+ tc = factory->create();
+ } else {
+ // Copy.
+ ToolChainTreeItem *current = currentTreeItem();
+ if (!current)
+ return;
+ tc = current->toolChain->clone();
+ }
- emit endInsertRows();
-}
+ if (!tc)
+ return;
-QModelIndex ToolChainModel::index(ToolChainNode *node, int column) const
-{
- if (node == m_root)
- return QModelIndex();
- if (node->parent == m_root)
- return index(m_root->childNodes.indexOf(node), column, QModelIndex());
- else
- return index(node->parent->childNodes.indexOf(node), column, index(node->parent));
-}
+ ToolChainTreeItem *item = new ToolChainTreeItem(tc, true);
+ m_toAddList.append(item);
-ToolChainNode *ToolChainModel::createNode(ToolChainNode *parent, ToolChain *tc, bool changed)
-{
- ToolChainNode *node = new ToolChainNode(parent, tc, changed);
- if (node->widget)
- connect(node->widget, SIGNAL(dirty()), this, SLOT(setDirty()));
- return node;
-}
+ m_manualRoot->appendChild(item);
-ToolChainNode *ToolChainModel::findToolChain(const QList<ToolChainNode *> &container, ToolChain *tc)
-{
- return Utils::findOrDefault(container, [tc](ToolChainNode *n) {
- return n->toolChain == tc;
- });
+ m_toolChainView->setCurrentIndex(m_model.indexFromItem(item));
}
-void ToolChainModel::addToolChain(ToolChain *tc)
+void ToolChainOptionsWidget::updateState()
{
- ToolChainNode *n = findToolChain(m_toAddList, tc);
- if (n) {
- m_toAddList.removeOne(n);
- // do not delete n: Still used elsewhere!
- return;
+ bool canCopy = false;
+ bool canDelete = false;
+ if (ToolChainTreeItem *item = currentTreeItem()) {
+ ToolChain *tc = item->toolChain;
+ canCopy = tc->isValid() && tc->canClone();
+ canDelete = tc->detection() != ToolChain::AutoDetection;
}
-
- ToolChainNode *parent = m_manualRoot;
- if (tc->isAutoDetected())
- parent = m_autoRoot;
- int row = parent->childNodes.count();
-
- beginInsertRows(index(parent), row, row);
- createNode(parent, tc, false);
- endInsertRows();
-
- emit toolChainStateChanged();
+ m_cloneButton->setEnabled(canCopy);
+ m_delButton->setEnabled(canDelete);
}
-void ToolChainModel::removeToolChain(ToolChain *tc)
+ToolChainTreeItem *ToolChainOptionsWidget::currentTreeItem()
{
- ToolChainNode *n = findToolChain(m_toRemoveList, tc);
- if (n) {
- m_toRemoveList.removeOne(n);
- delete n;
- return;
- }
-
- ToolChainNode *parent = m_manualRoot;
- if (tc->isAutoDetected())
- parent = m_autoRoot;
- int row = 0;
- ToolChainNode *node = 0;
- foreach (ToolChainNode *current, parent->childNodes) {
- if (current->toolChain == tc) {
- node = current;
- break;
- }
- ++row;
- }
-
- beginRemoveRows(index(parent), row, row);
- parent->childNodes.removeAt(row);
- delete node;
- endRemoveRows();
-
- emit toolChainStateChanged();
+ QModelIndex index = m_toolChainView->currentIndex();
+ TreeItem *item = m_model.itemFromIndex(index);
+ return item && item->level() == 2 ? static_cast<ToolChainTreeItem *>(item) : 0;
}
// --------------------------------------------------------------------------
// ToolChainOptionsPage
// --------------------------------------------------------------------------
-ToolChainOptionsPage::ToolChainOptionsPage() :
- m_model(0), m_selectionModel(0), m_toolChainView(0), m_container(0),
- m_addButton(0), m_cloneButton(0), m_delButton(0)
+ToolChainOptionsPage::ToolChainOptionsPage()
{
setId(Constants::TOOLCHAIN_SETTINGS_PAGE_ID);
setDisplayName(tr("Compilers"));
@@ -451,177 +397,21 @@ ToolChainOptionsPage::ToolChainOptionsPage() :
QWidget *ToolChainOptionsPage::widget()
{
- if (!m_configWidget) {
- // Actual page setup:
- m_configWidget = new QWidget;
-
- m_toolChainView = new QTreeView(m_configWidget);
- m_toolChainView->setUniformRowHeights(true);
- m_toolChainView->header()->setStretchLastSection(false);
-
- 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 Utils::DetailsWidget(m_configWidget);
- m_container->setState(Utils::DetailsWidget::NoSummary);
- m_container->setVisible(false);
-
- 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_toolChainView);
- verticalLayout->addWidget(m_container);
-
- QHBoxLayout *horizontalLayout = new QHBoxLayout(m_configWidget);
- horizontalLayout->addLayout(verticalLayout);
- horizontalLayout->addLayout(buttonLayout);
- Q_ASSERT(!m_model);
- m_model = new ToolChainModel(m_configWidget);
-
- connect(m_model, SIGNAL(toolChainStateChanged()), this, SLOT(updateState()));
-
- m_toolChainView->setModel(m_model);
- m_toolChainView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
- m_toolChainView->header()->setSectionResizeMode(1, QHeaderView::Stretch);
- m_toolChainView->expandAll();
-
- m_selectionModel = m_toolChainView->selectionModel();
- connect(m_selectionModel, SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(toolChainSelectionChanged()));
- connect(ToolChainManager::instance(), SIGNAL(toolChainsChanged()),
- this, SLOT(toolChainSelectionChanged()));
-
- // Get toolchainfactories:
- m_factories = ExtensionSystem::PluginManager::getObjects<ToolChainFactory>(
- [](ToolChainFactory *factory) { return factory->canCreate();});
-
- // Set up add menu:
- QMenu *addMenu = new QMenu(m_addButton);
- QSignalMapper *mapper = new QSignalMapper(addMenu);
- connect(mapper, SIGNAL(mapped(QObject*)), this, SLOT(createToolChain(QObject*)));
-
- foreach (ToolChainFactory *factory, m_factories) {
- QAction *action = new QAction(addMenu);
- action->setText(factory->displayName());
- connect(action, SIGNAL(triggered()), mapper, SLOT(map()));
- mapper->setMapping(action, static_cast<QObject *>(factory));
-
- addMenu->addAction(action);
- }
- connect(m_cloneButton, SIGNAL(clicked()), mapper, SLOT(map()));
- mapper->setMapping(m_cloneButton, static_cast<QObject *>(0));
-
- m_addButton->setMenu(addMenu);
-
- connect(m_delButton, SIGNAL(clicked()), this, SLOT(removeToolChain()));
- updateState();
- }
- return m_configWidget;
+ if (!m_widget)
+ m_widget = new ToolChainOptionsWidget;
+ return m_widget;
}
void ToolChainOptionsPage::apply()
{
- if (m_model)
- m_model->apply();
+ if (m_widget)
+ m_widget->apply();
}
void ToolChainOptionsPage::finish()
{
- disconnect(ToolChainManager::instance(), SIGNAL(toolChainsChanged()),
- this, SLOT(toolChainSelectionChanged()));
-
- delete m_configWidget;
-
- // children of m_configWidget
- m_model = 0;
- m_container = 0;
- m_selectionModel = 0;
- m_toolChainView = 0;
- m_addButton = 0;
- m_cloneButton = 0;
- m_delButton = 0;
-}
-
-void ToolChainOptionsPage::toolChainSelectionChanged()
-{
- if (!m_container)
- return;
- QModelIndex current = currentIndex();
- QWidget *oldWidget = m_container->takeWidget(); // Prevent deletion.
- if (oldWidget)
- oldWidget->setVisible(false);
- QWidget *currentTcWidget = current.isValid() ? m_model->widget(current) : 0;
- m_container->setWidget(currentTcWidget);
- m_container->setVisible(currentTcWidget != 0);
- updateState();
-}
-
-void ToolChainOptionsPage::createToolChain(QObject *factoryObject)
-{
- ToolChain *tc = 0;
-
- ToolChainFactory *factory = static_cast<ToolChainFactory *>(factoryObject);
- if (!factory) {
- // Copy current item!
- ToolChain *oldTc = m_model->toolChain(currentIndex());
- if (!oldTc)
- return;
- tc = oldTc->clone();
- } else {
- QTC_CHECK(factory->canCreate());
- tc = factory->create();
- } if (!tc)
- return;
- m_model->markForAddition(tc);
-
- QModelIndex newIdx = m_model->index(QModelIndex(), tc);
- m_selectionModel->select(newIdx,
- QItemSelectionModel::Clear
- | QItemSelectionModel::SelectCurrent
- | QItemSelectionModel::Rows);
-}
-
-void ToolChainOptionsPage::removeToolChain()
-{
- ToolChain *tc = m_model->toolChain(currentIndex());
- if (!tc)
- return;
- m_model->markForRemoval(tc);
-}
-
-void ToolChainOptionsPage::updateState()
-{
- if (!m_cloneButton)
- return;
-
- bool canCopy = false;
- bool canDelete = false;
- ToolChain *tc = m_model->toolChain(currentIndex());
- if (tc) {
- canCopy = tc->isValid() && tc->canClone();
- canDelete = tc->detection() != ToolChain::AutoDetection;
- }
-
- m_cloneButton->setEnabled(canCopy);
- m_delButton->setEnabled(canDelete);
-}
-
-QModelIndex ToolChainOptionsPage::currentIndex() const
-{
- if (!m_selectionModel)
- return QModelIndex();
-
- QModelIndexList idxs = m_selectionModel->selectedRows();
- if (idxs.count() != 1)
- return QModelIndex();
- return idxs.at(0);
+ delete m_widget;
+ m_widget = 0;
}
} // namespace Internal
diff --git a/src/plugins/projectexplorer/toolchainoptionspage.h b/src/plugins/projectexplorer/toolchainoptionspage.h
index 8ec910ae1d0..dcb37137349 100644
--- a/src/plugins/projectexplorer/toolchainoptionspage.h
+++ b/src/plugins/projectexplorer/toolchainoptionspage.h
@@ -33,82 +33,12 @@
#include <coreplugin/dialogs/ioptionspage.h>
-#include <QAbstractItemModel>
#include <QPointer>
-QT_BEGIN_NAMESPACE
-class QItemSelectionModel;
-class QPushButton;
-class QTreeView;
-QT_END_NAMESPACE
-
-namespace Utils { class DetailsWidget; }
-
namespace ProjectExplorer {
-
-class ToolChain;
-class ToolChainConfigWidget;
-class ToolChainFactory;
-
namespace Internal {
-class ToolChainNode;
-// --------------------------------------------------------------------------
-// ToolChainModel
-// --------------------------------------------------------------------------
-
-class ToolChainModel : public QAbstractItemModel
-{
- Q_OBJECT
-
-public:
- explicit ToolChainModel(QObject *parent = 0);
- ~ToolChainModel();
-
- QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
- QModelIndex index(const QModelIndex &topIdx, ToolChain *) const;
- QModelIndex parent(const QModelIndex &index) const;
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- int columnCount(const QModelIndex &parent = QModelIndex()) const;
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
- QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
-
- ToolChain *toolChain(const QModelIndex &);
- int manualToolChains() const;
-
- ToolChainConfigWidget *widget(const QModelIndex &);
-
- bool isDirty() const;
- bool isDirty(ToolChain *) const;
-
- void apply();
-
- void markForRemoval(ToolChain *);
- void markForAddition(ToolChain *);
-
-signals:
- void toolChainStateChanged();
-
-private slots:
- void addToolChain(ProjectExplorer::ToolChain *);
- void removeToolChain(ProjectExplorer::ToolChain *);
- void setDirty();
-
-private:
- QModelIndex index(ToolChainNode *, int column = 0) const;
- ToolChainNode *createNode(ToolChainNode *parent, ToolChain *tc, bool changed);
- static ToolChainNode *findToolChain(const QList<ToolChainNode *> &container, ToolChain *tc);
-
-
- ToolChainNode *m_root;
- ToolChainNode *m_autoRoot;
- ToolChainNode *m_manualRoot;
-
- QList<ToolChainNode *> m_toAddList;
- QList<ToolChainNode *> m_toRemoveList;
-};
+class ToolChainOptionsWidget;
// --------------------------------------------------------------------------
// ToolChainOptionsPage
@@ -125,25 +55,8 @@ public:
void apply();
void finish();
-private slots:
- void toolChainSelectionChanged();
- void createToolChain(QObject *);
- void removeToolChain();
- void updateState();
-
private:
- QModelIndex currentIndex() const;
-
- QPointer<QWidget> m_configWidget;
-
- ToolChainModel *m_model;
- QList<ToolChainFactory *> m_factories;
- QItemSelectionModel * m_selectionModel;
- QTreeView *m_toolChainView;
- Utils::DetailsWidget *m_container;
- QPushButton *m_addButton;
- QPushButton *m_cloneButton;
- QPushButton *m_delButton;
+ QPointer<ToolChainOptionsWidget> m_widget;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/windebuginterface.cpp b/src/plugins/projectexplorer/windebuginterface.cpp
index b795cd9fc24..e084aa4447b 100644
--- a/src/plugins/projectexplorer/windebuginterface.cpp
+++ b/src/plugins/projectexplorer/windebuginterface.cpp
@@ -56,20 +56,25 @@ WinDebugInterface *WinDebugInterface::instance()
return m_instance;
}
+bool WinDebugInterface::stop()
+{
+ if (!m_waitHandles[TerminateEventHandle])
+ return false;
+ SetEvent(m_waitHandles[TerminateEventHandle]);
+ return true;
+}
+
WinDebugInterface::WinDebugInterface(QObject *parent) :
QThread(parent)
{
m_instance = this;
setObjectName(QLatin1String("WinDebugInterfaceThread"));
- start();
}
WinDebugInterface::~WinDebugInterface()
{
- if (m_waitHandles[TerminateEventHandle]) {
- SetEvent(m_waitHandles[TerminateEventHandle]);
+ if (stop())
wait(500);
- }
m_instance = 0;
}
diff --git a/src/plugins/projectexplorer/windebuginterface.h b/src/plugins/projectexplorer/windebuginterface.h
index e902801c612..d8175a229cf 100644
--- a/src/plugins/projectexplorer/windebuginterface.h
+++ b/src/plugins/projectexplorer/windebuginterface.h
@@ -46,6 +46,8 @@ public:
static WinDebugInterface *instance();
+ bool stop();
+
signals:
void debugOutput(qint64 pid, const QString &message);
void cannotRetrieveDebugOutput();
diff --git a/src/plugins/qbsprojectmanager/customqbspropertiesdialog.cpp b/src/plugins/qbsprojectmanager/customqbspropertiesdialog.cpp
new file mode 100644
index 00000000000..253d1fd9b11
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/customqbspropertiesdialog.cpp
@@ -0,0 +1,104 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "customqbspropertiesdialog.h"
+#include "ui_customqbspropertiesdialog.h"
+
+#include <utils/algorithm.h>
+#include <utils/qtcassert.h>
+
+#include <QTableWidgetItem>
+
+namespace QbsProjectManager {
+namespace Internal {
+
+CustomQbsPropertiesDialog::CustomQbsPropertiesDialog(const QVariantMap &properties, QWidget *parent)
+ : QDialog(parent), m_ui(new Ui::CustomQbsPropertiesDialog)
+{
+ m_ui->setupUi(this);
+ m_ui->propertiesTable->setRowCount(properties.count());
+ m_ui->propertiesTable->setHorizontalHeaderLabels(QStringList() << tr("Key") << tr("Value"));
+ int currentRow = 0;
+ for (QVariantMap::ConstIterator it = properties.constBegin(); it != properties.constEnd();
+ ++it) {
+ QTableWidgetItem * const nameItem = new QTableWidgetItem;
+ nameItem->setData(Qt::DisplayRole, it.key());
+ m_ui->propertiesTable->setItem(currentRow, 0, nameItem);
+ QTableWidgetItem * const valueItem = new QTableWidgetItem;
+ valueItem->setData(Qt::DisplayRole, it.value());
+ m_ui->propertiesTable->setItem(currentRow, 1, valueItem);
+ ++currentRow;
+ }
+ connect(m_ui->addButton, SIGNAL(clicked()), SLOT(addProperty()));
+ connect(m_ui->removeButton, SIGNAL(clicked()), SLOT(removeSelectedProperty()));
+ connect(m_ui->propertiesTable, SIGNAL(currentItemChanged(QTableWidgetItem*,QTableWidgetItem*)),
+ SLOT(handleCurrentItemChanged()));
+ handleCurrentItemChanged();
+}
+
+QVariantMap CustomQbsPropertiesDialog::properties() const
+{
+ QVariantMap properties;
+ for (int row = 0; row < m_ui->propertiesTable->rowCount(); ++row) {
+ const QTableWidgetItem * const nameItem = m_ui->propertiesTable->item(row, 0);
+ const QString name = nameItem->text();
+ if (name.isEmpty())
+ continue;
+ properties.insert(name, m_ui->propertiesTable->item(row, 1)->text());
+ }
+ return properties;
+}
+
+CustomQbsPropertiesDialog::~CustomQbsPropertiesDialog()
+{
+ delete m_ui;
+}
+
+void CustomQbsPropertiesDialog::addProperty()
+{
+ const int row = m_ui->propertiesTable->rowCount();
+ m_ui->propertiesTable->insertRow(row);
+ m_ui->propertiesTable->setItem(row, 0, new QTableWidgetItem);
+ m_ui->propertiesTable->setItem(row, 1, new QTableWidgetItem);
+}
+
+void CustomQbsPropertiesDialog::removeSelectedProperty()
+{
+ const QTableWidgetItem * const currentItem = m_ui->propertiesTable->currentItem();
+ QTC_ASSERT(currentItem, return);
+ m_ui->propertiesTable->removeRow(currentItem->row());
+}
+
+void CustomQbsPropertiesDialog::handleCurrentItemChanged()
+{
+ m_ui->removeButton->setEnabled(m_ui->propertiesTable->currentItem());
+}
+
+} // namespace Internal
+} // namespace QbsProjectManager
diff --git a/src/plugins/qbsprojectmanager/customqbspropertiesdialog.h b/src/plugins/qbsprojectmanager/customqbspropertiesdialog.h
new file mode 100644
index 00000000000..b9d9a772cd2
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/customqbspropertiesdialog.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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_CUSTOMQBSPROPERTIESDIALOG_H
+#define QTC_CUSTOMQBSPROPERTIESDIALOG_H
+
+#include <QVariantMap>
+#include <QDialog>
+
+namespace QbsProjectManager {
+namespace Internal {
+namespace Ui { class CustomQbsPropertiesDialog; }
+
+class CustomQbsPropertiesDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit CustomQbsPropertiesDialog(const QVariantMap &properties, QWidget *parent = 0);
+
+ QVariantMap properties() const;
+ ~CustomQbsPropertiesDialog();
+
+private slots:
+ void addProperty();
+ void removeSelectedProperty();
+ void handleCurrentItemChanged();
+
+private:
+ Ui::CustomQbsPropertiesDialog * const m_ui;
+};
+
+} // namespace Internal
+} // namespace QbsProjectManager
+
+#endif // Include guard.
diff --git a/src/plugins/qbsprojectmanager/customqbspropertiesdialog.ui b/src/plugins/qbsprojectmanager/customqbspropertiesdialog.ui
new file mode 100644
index 00000000000..b18a460ab0f
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/customqbspropertiesdialog.ui
@@ -0,0 +1,120 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>QbsProjectManager::Internal::CustomQbsPropertiesDialog</class>
+ <widget class="QDialog" name="QbsProjectManager::Internal::CustomQbsPropertiesDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Custom Properties</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QTableWidget" name="propertiesTable">
+ <property name="selectionMode">
+ <enum>QAbstractItemView::SingleSelection</enum>
+ </property>
+ <property name="selectionBehavior">
+ <enum>QAbstractItemView::SelectItems</enum>
+ </property>
+ <property name="columnCount">
+ <number>2</number>
+ </property>
+ <attribute name="horizontalHeaderStretchLastSection">
+ <bool>true</bool>
+ </attribute>
+ <attribute name="verticalHeaderVisible">
+ <bool>false</bool>
+ </attribute>
+ <column/>
+ <column/>
+ </widget>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QPushButton" name="addButton">
+ <property name="text">
+ <string>&amp;Add</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="removeButton">
+ <property name="text">
+ <string>&amp;Remove</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <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>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>QbsProjectManager::Internal::CustomQbsPropertiesDialog</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>QbsProjectManager::Internal::CustomQbsPropertiesDialog</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/qbsprojectmanager/defaultpropertyprovider.cpp b/src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp
index 5d24d2b1f4b..536ce0fdf5a 100644
--- a/src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp
+++ b/src/plugins/qbsprojectmanager/defaultpropertyprovider.cpp
@@ -46,9 +46,12 @@
#include <QDir>
#include <QFileInfo>
+#include <QSettings>
namespace QbsProjectManager {
using namespace Constants;
+
+namespace Internal {
using namespace ProjectExplorer::Constants;
using namespace Ios::Constants;
using namespace Qnx::Constants;
@@ -140,9 +143,22 @@ static QStringList toolchainList(const ProjectExplorer::ToolChain *tc)
return list;
}
-QVariantMap DefaultPropertyProvider::properties(const ProjectExplorer::Kit *k, const QVariantMap &defaultData) const
+QVariantMap DefaultPropertyProvider::properties(const ProjectExplorer::Kit *k,
+ const QVariantMap &defaultData) const
{
QTC_ASSERT(k, return defaultData);
+ QVariantMap data = autoGeneratedProperties(k, defaultData);
+ const QVariantMap customProperties = k->value(Core::Id(QBS_PROPERTIES_KEY_FOR_KITS)).toMap();
+ for (QVariantMap::ConstIterator it = customProperties.constBegin();
+ it != customProperties.constEnd(); ++it) {
+ data.insert(it.key(), it.value());
+ }
+ return data;
+}
+
+QVariantMap DefaultPropertyProvider::autoGeneratedProperties(const ProjectExplorer::Kit *k,
+ const QVariantMap &defaultData) const
+{
QVariantMap data = defaultData;
const QString sysroot = ProjectExplorer::SysRootKitInformation::sysRoot(k).toUserOutput();
@@ -188,10 +204,18 @@ QVariantMap DefaultPropertyProvider::properties(const ProjectExplorer::Kit *k, c
if (targetAbi.os() == ProjectExplorer::Abi::MacOS) {
// Set Xcode SDK name and version - required by Qbs if a sysroot is present
// Ideally this would be done in a better way...
- QRegExp re(QLatin1String("(MacOSX|iPhoneOS|iPhoneSimulator)([0-9]+\\.[0-9]+)\\.sdk"));
- if (re.exactMatch(QDir(sysroot).dirName())) {
- data.insert(QLatin1String(CPP_XCODESDKNAME), QString(re.cap(1).toLower() + re.cap(2)));
- data.insert(QLatin1String(CPP_XCODESDKVERSION), re.cap(2));
+ const QRegExp sdkNameRe(QLatin1String("(macosx|iphoneos|iphonesimulator)([0-9]+\\.[0-9]+)"));
+ const QRegExp sdkVersionRe(QLatin1String("([0-9]+\\.[0-9]+)"));
+ QDir sysrootdir(sysroot);
+ const QSettings sdkSettings(sysrootdir.absoluteFilePath(QLatin1String("SDKSettings.plist")), QSettings::NativeFormat);
+ const QString sdkName(sdkSettings.value(QLatin1String("CanonicalName")).toString());
+ const QString sdkVersion(sdkSettings.value(QLatin1String("Version")).toString());
+ if (sdkNameRe.exactMatch(sdkName) && sdkVersionRe.exactMatch(sdkVersion)) {
+ for (int i = 3; i > 0; --i)
+ sysrootdir.cdUp();
+ data.insert(QLatin1String(CPP_PLATFORMPATH), sysrootdir.absolutePath());
+ data.insert(QLatin1String(CPP_XCODESDKNAME), sdkName);
+ data.insert(QLatin1String(CPP_XCODESDKVERSION), sdkVersion);
}
}
@@ -215,4 +239,5 @@ QVariantMap DefaultPropertyProvider::properties(const ProjectExplorer::Kit *k, c
return data;
}
+} // namespace Internal
} // namespace QbsProjectManager
diff --git a/src/plugins/qbsprojectmanager/defaultpropertyprovider.h b/src/plugins/qbsprojectmanager/defaultpropertyprovider.h
index 81e9c78cd0f..5263413711c 100644
--- a/src/plugins/qbsprojectmanager/defaultpropertyprovider.h
+++ b/src/plugins/qbsprojectmanager/defaultpropertyprovider.h
@@ -34,6 +34,7 @@
#include "propertyprovider.h"
namespace QbsProjectManager {
+namespace Internal {
class DefaultPropertyProvider : public PropertyProvider
{
@@ -42,8 +43,13 @@ class DefaultPropertyProvider : public PropertyProvider
public:
bool canHandle(const ProjectExplorer::Kit *k) const { return k; }
QVariantMap properties(const ProjectExplorer::Kit *k, const QVariantMap &defaultData) const;
+
+private:
+ QVariantMap autoGeneratedProperties(const ProjectExplorer::Kit *k,
+ const QVariantMap &defaultData) const;
};
+} // namespace Internal
} // namespace QbsProjectManager
#endif // DEFAULTPROPERTYPROVIDER_H
diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp
index c125aa41625..713b9bf813a 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp
+++ b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp
@@ -34,6 +34,7 @@
#include "qbsbuildinfo.h"
#include "qbsbuildstep.h"
#include "qbscleanstep.h"
+#include "qbsinstallstep.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
@@ -48,7 +49,9 @@
#include <projectexplorer/projectmacroexpander.h>
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
+#include <utils/qtcprocess.h>
+#include <QCoreApplication>
#include <QInputDialog>
using namespace ProjectExplorer;
@@ -205,6 +208,127 @@ void QbsBuildConfiguration::emitBuildTypeChanged()
emit buildTypeChanged();
}
+class StepProxy
+{
+public:
+ StepProxy(const BuildStep *buildStep)
+ : m_qbsBuildStep(qobject_cast<const QbsBuildStep *>(buildStep))
+ , m_qbsCleanStep(qobject_cast<const QbsCleanStep *>(buildStep))
+ , m_qbsInstallStep(qobject_cast<const QbsInstallStep *>(buildStep))
+ {
+ }
+
+ QString command() const {
+ if (m_qbsBuildStep)
+ return QLatin1String("build");
+ if (m_qbsCleanStep)
+ return QLatin1String("clean");
+ return QLatin1String("install");
+ }
+
+ bool dryRun() const {
+ if (m_qbsBuildStep)
+ return m_qbsBuildStep->dryRun();
+ if (m_qbsCleanStep)
+ return m_qbsCleanStep->dryRun();
+ return m_qbsInstallStep->dryRun();
+ }
+
+ bool keepGoing() const {
+ if (m_qbsBuildStep)
+ return m_qbsBuildStep->keepGoing();
+ if (m_qbsCleanStep)
+ return m_qbsCleanStep->keepGoing();
+ return m_qbsInstallStep->keepGoing();
+ }
+
+ bool showCommandLines() const {
+ return m_qbsBuildStep ? m_qbsBuildStep->showCommandLines() : false;
+ }
+
+ bool noInstall() const {
+ return m_qbsBuildStep ? !m_qbsBuildStep->install() : false;
+ }
+
+ bool cleanInstallRoot() const {
+ if (m_qbsBuildStep)
+ return m_qbsBuildStep->cleanInstallRoot();
+ if (m_qbsInstallStep)
+ return m_qbsInstallStep->removeFirst();
+ return false;
+ }
+
+ int jobCount() const {
+ return m_qbsBuildStep ? m_qbsBuildStep->maxJobs() : 0;
+ }
+
+ bool allArtifacts() const {
+ return m_qbsCleanStep ? m_qbsCleanStep->cleanAll() : false;
+ }
+
+ QString installRoot() const {
+ return m_qbsInstallStep ? m_qbsInstallStep->absoluteInstallRoot() : QString();
+ }
+
+private:
+ const QbsBuildStep * const m_qbsBuildStep;
+ const QbsCleanStep * const m_qbsCleanStep;
+ const QbsInstallStep * const m_qbsInstallStep;
+};
+
+QString QbsBuildConfiguration::equivalentCommandLine(const BuildStep *buildStep)
+{
+ QString commandLine;
+ const QString qbsInstallDir = QString::fromLocal8Bit(qgetenv("QBS_INSTALL_DIR"));
+ const QString qbsFilePath = Utils::HostOsInfo::withExecutableSuffix(!qbsInstallDir.isEmpty()
+ ? qbsInstallDir + QLatin1String("/bin/qbs")
+ : QCoreApplication::applicationDirPath() + QLatin1String("/qbs"));
+ Utils::QtcProcess::addArg(&commandLine, qbsFilePath);
+ const StepProxy stepProxy(buildStep);
+ Utils::QtcProcess::addArg(&commandLine, stepProxy.command());
+ const QbsBuildConfiguration * const buildConfig = qobject_cast<QbsBuildConfiguration *>(
+ buildStep->project()->activeTarget()->activeBuildConfiguration());
+ if (buildConfig) {
+ const QString buildDir = buildConfig->buildDirectory().toUserOutput();
+ Utils::QtcProcess::addArgs(&commandLine, QStringList() << QLatin1String("-d") << buildDir);
+ }
+ Utils::QtcProcess::addArgs(&commandLine, QStringList() << QLatin1String("-f")
+ << buildStep->project()->projectFilePath().toUserOutput());
+ Utils::QtcProcess::addArgs(&commandLine, QStringList() << QLatin1String("--settings-dir")
+ << QDir::toNativeSeparators(Core::ICore::userResourcePath()));
+ if (stepProxy.dryRun())
+ Utils::QtcProcess::addArg(&commandLine, QLatin1String("--dry-run"));
+ if (stepProxy.keepGoing())
+ Utils::QtcProcess::addArg(&commandLine, QLatin1String("--keep-going"));
+ if (stepProxy.showCommandLines())
+ Utils::QtcProcess::addArg(&commandLine, QLatin1String("--show-command-lines"));
+ if (stepProxy.noInstall())
+ Utils::QtcProcess::addArg(&commandLine, QLatin1String("--no-install"));
+ if (stepProxy.cleanInstallRoot())
+ Utils::QtcProcess::addArg(&commandLine, QLatin1String("--clean-install-root"));
+ const int jobCount = stepProxy.jobCount();
+ if (jobCount > 0) {
+ Utils::QtcProcess::addArgs(&commandLine, QStringList() << QLatin1String("--jobs")
+ << QString::number(jobCount));
+ }
+ if (stepProxy.allArtifacts())
+ Utils::QtcProcess::addArg(&commandLine, QLatin1String("--all-artifacts"));
+ const QString installRoot = stepProxy.installRoot();
+ if (!installRoot.isEmpty()) {
+ Utils::QtcProcess::addArgs(&commandLine, QStringList() << QLatin1String("--install-root")
+ << installRoot);
+ }
+
+ if (buildConfig) {
+ Utils::QtcProcess::addArg(&commandLine, buildConfig->qbsConfiguration()
+ .value(QLatin1String(Constants::QBS_CONFIG_VARIANT_KEY)).toString());
+ }
+ Utils::QtcProcess::addArg(&commandLine, QLatin1String("profile:")
+ + QbsManager::instance()->profileForKit(buildStep->target()->kit()));
+
+ return commandLine;
+}
+
QbsBuildConfiguration *QbsBuildConfiguration::setup(Target *t,
const QString &defaultDisplayName,
const QString &displayName,
diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h
index 3e89443ff2a..953664fbda4 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h
+++ b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.h
@@ -36,7 +36,10 @@
#include <projectexplorer/buildconfiguration.h>
#include <qtsupport/baseqtversion.h>
-namespace ProjectExplorer { class FileNode; }
+namespace ProjectExplorer {
+class BuildStep;
+class FileNode;
+}
namespace QbsProjectManager {
@@ -79,6 +82,8 @@ public:
void emitBuildTypeChanged();
+ static QString equivalentCommandLine(const ProjectExplorer::BuildStep *buildStep);
+
signals:
void qbsConfigurationChanged();
diff --git a/src/plugins/qbsprojectmanager/qbsbuildstep.cpp b/src/plugins/qbsprojectmanager/qbsbuildstep.cpp
index bcc8bfed3ed..b08019dd4ed 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildstep.cpp
+++ b/src/plugins/qbsprojectmanager/qbsbuildstep.cpp
@@ -53,6 +53,9 @@ static const char QBS_CONFIG[] = "Qbs.Configuration";
static const char QBS_DRY_RUN[] = "Qbs.DryRun";
static const char QBS_KEEP_GOING[] = "Qbs.DryKeepGoing";
static const char QBS_MAXJOBCOUNT[] = "Qbs.MaxJobs";
+static const char QBS_SHOWCOMMANDLINES[] = "Qbs.ShowCommandLines";
+static const char QBS_INSTALL[] = "Qbs.Install";
+static const char QBS_CLEAN_INSTALL_ROOT[] = "Qbs.CleanInstallRoot";
// --------------------------------------------------------------------
// Constants:
@@ -181,6 +184,21 @@ bool QbsBuildStep::keepGoing() const
return m_qbsBuildOptions.keepGoing();
}
+bool QbsBuildStep::showCommandLines() const
+{
+ return m_qbsBuildOptions.showCommandLines();
+}
+
+bool QbsBuildStep::install() const
+{
+ return m_qbsBuildOptions.install();
+}
+
+bool QbsBuildStep::cleanInstallRoot() const
+{
+ return m_qbsBuildOptions.removeExistingInstallation();
+}
+
int QbsBuildStep::maxJobs() const
{
if (m_qbsBuildOptions.maxJobCount() > 0)
@@ -197,6 +215,10 @@ bool QbsBuildStep::fromMap(const QVariantMap &map)
m_qbsBuildOptions.setDryRun(map.value(QLatin1String(QBS_DRY_RUN)).toBool());
m_qbsBuildOptions.setKeepGoing(map.value(QLatin1String(QBS_KEEP_GOING)).toBool());
m_qbsBuildOptions.setMaxJobCount(map.value(QLatin1String(QBS_MAXJOBCOUNT)).toInt());
+ m_qbsBuildOptions.setShowCommandLines(map.value(QLatin1String(QBS_SHOWCOMMANDLINES)).toBool());
+ m_qbsBuildOptions.setInstall(map.value(QLatin1String(QBS_INSTALL), true).toBool());
+ m_qbsBuildOptions.setRemoveExistingInstallation(map.value(QLatin1String(QBS_CLEAN_INSTALL_ROOT))
+ .toBool());
return true;
}
@@ -207,6 +229,10 @@ QVariantMap QbsBuildStep::toMap() const
map.insert(QLatin1String(QBS_DRY_RUN), m_qbsBuildOptions.dryRun());
map.insert(QLatin1String(QBS_KEEP_GOING), m_qbsBuildOptions.keepGoing());
map.insert(QLatin1String(QBS_MAXJOBCOUNT), m_qbsBuildOptions.maxJobCount());
+ map.insert(QLatin1String(QBS_SHOWCOMMANDLINES), m_qbsBuildOptions.showCommandLines());
+ map.insert(QLatin1String(QBS_INSTALL), m_qbsBuildOptions.install());
+ map.insert(QLatin1String(QBS_CLEAN_INSTALL_ROOT),
+ m_qbsBuildOptions.removeExistingInstallation());
return map;
}
@@ -216,7 +242,7 @@ void QbsBuildStep::buildingDone(bool success)
// Report errors:
foreach (const qbs::ErrorItem &item, m_job->error().items())
createTaskAndOutput(ProjectExplorer::Task::Error, item.description(),
- item.codeLocation().fileName(), item.codeLocation().line());
+ item.codeLocation().filePath(), item.codeLocation().line());
QbsProject *pro = static_cast<QbsProject *>(project());
@@ -351,6 +377,30 @@ void QbsBuildStep::setMaxJobs(int jobcount)
emit qbsBuildOptionsChanged();
}
+void QbsBuildStep::setShowCommandLines(bool show)
+{
+ if (m_qbsBuildOptions.showCommandLines() == show)
+ return;
+ m_qbsBuildOptions.setShowCommandLines(show);
+ emit qbsBuildOptionsChanged();
+}
+
+void QbsBuildStep::setInstall(bool install)
+{
+ if (m_qbsBuildOptions.install() == install)
+ return;
+ m_qbsBuildOptions.setInstall(install);
+ emit qbsBuildOptionsChanged();
+}
+
+void QbsBuildStep::setCleanInstallRoot(bool clean)
+{
+ if (m_qbsBuildOptions.removeExistingInstallation() == clean)
+ return;
+ m_qbsBuildOptions.setRemoveExistingInstallation(clean);
+ emit qbsBuildOptionsChanged();
+}
+
void QbsBuildStep::parseProject()
{
m_parsingProject = true;
@@ -428,6 +478,12 @@ QbsBuildStepConfigWidget::QbsBuildStepConfigWidget(QbsBuildStep *step) :
connect(m_ui->dryRunCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeDryRun(bool)));
connect(m_ui->keepGoingCheckBox, SIGNAL(toggled(bool)), this, SLOT(changeKeepGoing(bool)));
connect(m_ui->jobSpinBox, SIGNAL(valueChanged(int)), this, SLOT(changeJobCount(int)));
+ connect(m_ui->showCommandLinesCheckBox, &QCheckBox::toggled, this,
+ &QbsBuildStepConfigWidget::changeShowCommandLines);
+ connect(m_ui->installCheckBox, &QCheckBox::toggled, this,
+ &QbsBuildStepConfigWidget::changeInstall);
+ connect(m_ui->cleanInstallRootCheckBox, &QCheckBox::toggled, this,
+ &QbsBuildStepConfigWidget::changeCleanInstallRoot);
connect(m_ui->propertyEdit, SIGNAL(propertiesChanged()), this, SLOT(changeProperties()));
connect(m_ui->qmlDebuggingLibraryCheckBox, SIGNAL(toggled(bool)),
this, SLOT(linkQmlDebuggingLibraryChecked(bool)));
@@ -457,6 +513,9 @@ void QbsBuildStepConfigWidget::updateState()
m_ui->dryRunCheckBox->setChecked(m_step->dryRun());
m_ui->keepGoingCheckBox->setChecked(m_step->keepGoing());
m_ui->jobSpinBox->setValue(m_step->maxJobs());
+ m_ui->showCommandLinesCheckBox->setChecked(m_step->showCommandLines());
+ m_ui->installCheckBox->setChecked(m_step->install());
+ m_ui->cleanInstallRootCheckBox->setChecked(m_step->cleanInstallRoot());
updatePropertyEdit(m_step->qbsConfiguration());
m_ui->qmlDebuggingLibraryCheckBox->setChecked(m_step->isQmlDebuggingEnabled());
}
@@ -466,16 +525,7 @@ void QbsBuildStepConfigWidget::updateState()
const QString buildVariant = m_step->buildVariant();
const int idx = (buildVariant == QLatin1String(Constants::QBS_VARIANT_DEBUG)) ? 0 : 1;
m_ui->buildVariantComboBox->setCurrentIndex(idx);
-
- QString command = QLatin1String("qbs build ");
- command += QString::fromLatin1("--settings-dir ")
- + QDir::toNativeSeparators(Core::ICore::userResourcePath()) + QLatin1Char(' ');
- if (m_step->dryRun())
- command += QLatin1String("--dry-run ");
- if (m_step->keepGoing())
- command += QLatin1String("--keep-going ");
- command += QString::fromLatin1("--jobs %1 ").arg(m_step->maxJobs());
- command += QString::fromLatin1("%1 profile:%2").arg(buildVariant, m_step->profile());
+ QString command = QbsBuildConfiguration::equivalentCommandLine(m_step);
QList<QPair<QString, QString> > propertyList = m_ui->propertyEdit->properties();
for (int i = 0; i < propertyList.count(); ++i) {
@@ -545,6 +595,13 @@ void QbsBuildStepConfigWidget::changeDryRun(bool dr)
m_ignoreChange = false;
}
+void QbsBuildStepConfigWidget::changeShowCommandLines(bool show)
+{
+ m_ignoreChange = true;
+ m_step->setShowCommandLines(show);
+ m_ignoreChange = false;
+}
+
void QbsBuildStepConfigWidget::changeKeepGoing(bool kg)
{
m_ignoreChange = true;
@@ -559,6 +616,20 @@ void QbsBuildStepConfigWidget::changeJobCount(int count)
m_ignoreChange = false;
}
+void QbsBuildStepConfigWidget::changeInstall(bool install)
+{
+ m_ignoreChange = true;
+ m_step->setInstall(install);
+ m_ignoreChange = false;
+}
+
+void QbsBuildStepConfigWidget::changeCleanInstallRoot(bool clean)
+{
+ m_ignoreChange = true;
+ m_step->setCleanInstallRoot(clean);
+ m_ignoreChange = false;
+}
+
void QbsBuildStepConfigWidget::changeProperties()
{
QVariantMap data;
diff --git a/src/plugins/qbsprojectmanager/qbsbuildstep.h b/src/plugins/qbsprojectmanager/qbsbuildstep.h
index 6da66452a2c..2351c60c2e6 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildstep.h
+++ b/src/plugins/qbsprojectmanager/qbsbuildstep.h
@@ -67,6 +67,9 @@ public:
bool dryRun() const;
bool keepGoing() const;
+ bool showCommandLines() const;
+ bool install() const;
+ bool cleanInstallRoot() const;
int maxJobs() const;
QString buildVariant() const;
@@ -97,6 +100,9 @@ private:
void setDryRun(bool dr);
void setKeepGoing(bool kg);
void setMaxJobs(int jobcount);
+ void setShowCommandLines(bool show);
+ void setInstall(bool install);
+ void setCleanInstallRoot(bool clean);
void parseProject();
void build();
@@ -140,8 +146,11 @@ private slots:
void changeBuildVariant(int);
void changeDryRun(bool dr);
+ void changeShowCommandLines(bool show);
void changeKeepGoing(bool kg);
void changeJobCount(int count);
+ void changeInstall(bool install);
+ void changeCleanInstallRoot(bool clean);
void changeProperties();
// QML debugging:
diff --git a/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui b/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui
index ed725043927..6c9709c26ef 100644
--- a/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui
+++ b/src/plugins/qbsprojectmanager/qbsbuildstepconfigwidget.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>557</width>
- <height>233</height>
+ <width>723</width>
+ <height>247</height>
</rect>
</property>
<layout class="QFormLayout" name="formLayout">
@@ -181,6 +181,27 @@
</widget>
</item>
<item>
+ <widget class="QCheckBox" name="showCommandLinesCheckBox">
+ <property name="text">
+ <string>Show command lines</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="installCheckBox">
+ <property name="text">
+ <string>Install</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="cleanInstallRootCheckBox">
+ <property name="text">
+ <string>Clean install root</string>
+ </property>
+ </widget>
+ </item>
+ <item>
<spacer name="checkBoxSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
diff --git a/src/plugins/qbsprojectmanager/qbscleanstep.cpp b/src/plugins/qbsprojectmanager/qbscleanstep.cpp
index 8db333246ba..a93572130a7 100644
--- a/src/plugins/qbsprojectmanager/qbscleanstep.cpp
+++ b/src/plugins/qbsprojectmanager/qbscleanstep.cpp
@@ -183,7 +183,7 @@ void QbsCleanStep::cleaningDone(bool success)
// Report errors:
foreach (const qbs::ErrorItem &item, m_job->error().items()) {
createTaskAndOutput(ProjectExplorer::Task::Error, item.description(),
- item.codeLocation().fileName(), item.codeLocation().line());
+ item.codeLocation().filePath(), item.codeLocation().line());
}
QTC_ASSERT(m_fi, return);
@@ -293,13 +293,7 @@ void QbsCleanStepConfigWidget::updateState()
m_ui->dryRunCheckBox->setChecked(m_step->dryRun());
m_ui->keepGoingCheckBox->setChecked(m_step->keepGoing());
- QString command = QLatin1String("qbs clean ");
- if (m_step->dryRun())
- command += QLatin1String("--dry-run ");
- if (m_step->keepGoing())
- command += QLatin1String("--keep-going ");
- if (m_step->cleanAll())
- command += QLatin1String(" --all-artifacts");
+ QString command = QbsBuildConfiguration::equivalentCommandLine(m_step);
m_ui->commandLineTextEdit->setPlainText(command);
QString summary = tr("<b>Qbs:</b> %1").arg(command);
diff --git a/src/plugins/qbsprojectmanager/qbsconstants.h b/src/plugins/qbsprojectmanager/qbsconstants.h
index 4c89c448ad0..64aea581997 100644
--- a/src/plugins/qbsprojectmanager/qbsconstants.h
+++ b/src/plugins/qbsprojectmanager/qbsconstants.h
@@ -46,9 +46,17 @@ const char CPP_COMPILERNAME[] = "cpp.compilerName";
const char CPP_LINKERNAME[] = "cpp.linkerName";
const char CPP_PLATFORMCFLAGS[] = "cpp.platformCFlags";
const char CPP_PLATFORMCXXFLAGS[] = "cpp.platformCxxFlags";
+const char CPP_PLATFORMPATH[] = "cpp.platformPath";
const char CPP_XCODESDKNAME[] = "cpp.xcodeSdkName";
const char CPP_XCODESDKVERSION[] = "cpp.xcodeSdkVersion";
+// Settings page
+const char QBS_SETTINGS_CATEGORY[] = "YM.qbs";
+const char QBS_SETTINGS_TR_CATEGORY[] = QT_TRANSLATE_NOOP("QbsProjectManager", "qbs");
+const char QBS_SETTINGS_CATEGORY_ICON[] = ":/projectexplorer/images/build.png";
+
+const char QBS_PROPERTIES_KEY_FOR_KITS[] = "QbsProjectManager.qbs-properties";
+
} // namespace Constants
} // namespace QbsProjectManager
diff --git a/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp b/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp
index e44d4cfa018..f0d167f1aba 100644
--- a/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp
+++ b/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.cpp
@@ -119,7 +119,6 @@ ProjectExplorer::DeployConfiguration
QbsDeployConfiguration *dc = new QbsDeployConfiguration(parent, id);
dc->setDisplayName(genericQbsDisplayName());
- dc->stepList()->insertStep(0, new QbsInstallStep(dc->stepList()));
return dc;
}
@@ -143,6 +142,11 @@ ProjectExplorer::DeployConfiguration
return dc;
}
+bool QbsDeployConfigurationFactory::canClone(ProjectExplorer::Target *parent, ProjectExplorer::DeployConfiguration *product) const
+{
+ return canCreate(parent, product->id());
+}
+
ProjectExplorer::DeployConfiguration
*QbsDeployConfigurationFactory::clone(ProjectExplorer::Target *parent,
ProjectExplorer::DeployConfiguration *product)
diff --git a/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.h b/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.h
index a62c6a8a0c2..7d409a31ead 100644
--- a/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.h
+++ b/src/plugins/qbsprojectmanager/qbsdeployconfigurationfactory.h
@@ -69,6 +69,7 @@ public:
ProjectExplorer::DeployConfiguration *create(ProjectExplorer::Target *parent, Core::Id id);
bool canRestore(ProjectExplorer::Target *parent, const QVariantMap &map) const;
ProjectExplorer::DeployConfiguration *restore(ProjectExplorer::Target *parent, const QVariantMap &map);
+ bool canClone(ProjectExplorer::Target *parent, ProjectExplorer::DeployConfiguration *product) const;
ProjectExplorer::DeployConfiguration *clone(ProjectExplorer::Target *parent,
ProjectExplorer::DeployConfiguration *product);
};
diff --git a/src/plugins/qbsprojectmanager/qbsinstallstep.cpp b/src/plugins/qbsprojectmanager/qbsinstallstep.cpp
index 85ca3a0329b..98712f1a8c7 100644
--- a/src/plugins/qbsprojectmanager/qbsinstallstep.cpp
+++ b/src/plugins/qbsprojectmanager/qbsinstallstep.cpp
@@ -193,7 +193,7 @@ void QbsInstallStep::installDone(bool success)
// Report errors:
foreach (const qbs::ErrorItem &item, m_job->error().items()) {
createTaskAndOutput(ProjectExplorer::Task::Error, item.description(),
- item.codeLocation().fileName(), item.codeLocation().line());
+ item.codeLocation().filePath(), item.codeLocation().line());
}
QTC_ASSERT(m_fi, return);
@@ -317,16 +317,7 @@ void QbsInstallStepConfigWidget::updateState()
m_ui->installRootChooser->setBaseFileName(m_step->target()->activeBuildConfiguration()->buildDirectory());
- QString command = QLatin1String("qbs install ");
- command += QString::fromLatin1("--settings-dir ")
- + QDir::toNativeSeparators(Core::ICore::userResourcePath()) + QLatin1Char(' ');
- if (m_step->dryRun())
- command += QLatin1String("--dry-run ");
- if (m_step->keepGoing())
- command += QLatin1String("--keep-going ");
- if (m_step->removeFirst())
- command += QLatin1String("--remove-first ");
- command += QString::fromLatin1("--install-root \"%1\"").arg(m_step->absoluteInstallRoot());
+ QString command = QbsBuildConfiguration::equivalentCommandLine(m_step);
m_ui->commandLineTextEdit->setPlainText(command);
QString summary = tr("<b>Qbs:</b> %1").arg(command);
diff --git a/src/plugins/qbsprojectmanager/qbslogsink.cpp b/src/plugins/qbsprojectmanager/qbslogsink.cpp
index ba6da698e4c..07bb729f8f7 100644
--- a/src/plugins/qbsprojectmanager/qbslogsink.cpp
+++ b/src/plugins/qbsprojectmanager/qbslogsink.cpp
@@ -73,7 +73,7 @@ void QbsLogSink::doPrintWarning(const qbs::ErrorInfo &warning)
foreach (const qbs::ErrorItem &item, warning.items())
emit newTask(ProjectExplorer::Task(ProjectExplorer::Task::Warning,
item.description(),
- Utils::FileName::fromString(item.codeLocation().fileName()),
+ Utils::FileName::fromString(item.codeLocation().filePath()),
item.codeLocation().line(),
ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
}
diff --git a/src/plugins/qbsprojectmanager/qbsnodes.cpp b/src/plugins/qbsprojectmanager/qbsnodes.cpp
index a5400f05ae5..6732b72548b 100644
--- a/src/plugins/qbsprojectmanager/qbsnodes.cpp
+++ b/src/plugins/qbsprojectmanager/qbsnodes.cpp
@@ -90,7 +90,7 @@ QIcon QbsProductNode::m_productIcon;
static QbsProjectNode *parentQbsProjectNode(ProjectExplorer::Node *node)
{
for (ProjectExplorer::FolderNode *pn = node->projectNode(); pn; pn = pn->parentFolderNode()) {
- QbsProjectNode *prjNode = qobject_cast<QbsProjectNode *>(pn);
+ QbsProjectNode *prjNode = dynamic_cast<QbsProjectNode *>(pn);
if (prjNode)
return prjNode;
}
@@ -100,7 +100,7 @@ static QbsProjectNode *parentQbsProjectNode(ProjectExplorer::Node *node)
static QbsProductNode *parentQbsProductNode(ProjectExplorer::Node *node)
{
for (; node; node = node->parentFolderNode()) {
- QbsProductNode *prdNode = qobject_cast<QbsProductNode *>(node);
+ QbsProductNode *prdNode = dynamic_cast<QbsProductNode *>(node);
if (prdNode)
return prdNode;
}
@@ -353,7 +353,7 @@ QbsGroupNode::QbsGroupNode(const qbs::GroupData &grp, const QString &productPath
setIcon(m_groupIcon);
- QbsFileNode *idx = new QbsFileNode(grp.location().fileName(),
+ QbsFileNode *idx = new QbsFileNode(grp.location().filePath(),
ProjectExplorer::ProjectFileType, false,
grp.location().line());
addFileNodes(QList<ProjectExplorer::FileNode *>() << idx);
@@ -447,17 +447,17 @@ void QbsGroupNode::updateQbsGroupData(const qbs::GroupData &grp, const QString &
m_productPath = productPath;
m_qbsGroupData = grp;
- setPath(grp.location().fileName());
+ setPath(grp.location().filePath());
setDisplayName(grp.name());
QbsFileNode *idx = 0;
foreach (ProjectExplorer::FileNode *fn, fileNodes()) {
- idx = qobject_cast<QbsFileNode *>(fn);
+ idx = dynamic_cast<QbsFileNode *>(fn);
if (idx)
break;
}
QTC_ASSERT(idx, return);
- idx->setPathAndLine(grp.location().fileName(), grp.location().line());
+ idx->setPathAndLine(grp.location().filePath(), grp.location().line());
setupFiles(this, grp.allFilePaths(), productPath, updateExisting);
@@ -498,7 +498,7 @@ void QbsGroupNode::setupFolder(ProjectExplorer::FolderNode *root,
QList<ProjectExplorer::FileNode *> filesToRemove;
foreach (ProjectExplorer::FileNode *fn, root->fileNodes()) {
- if (!qobject_cast<QbsFileNode *>(fn))
+ if (!dynamic_cast<QbsFileNode *>(fn))
filesToRemove << fn;
}
QList<ProjectExplorer::FileNode *> filesToAdd;
@@ -565,14 +565,14 @@ void QbsGroupNode::setupFolder(ProjectExplorer::FolderNode *root,
// --------------------------------------------------------------------
QbsProductNode::QbsProductNode(const qbs::Project &project, const qbs::ProductData &prd) :
- QbsBaseProjectNode(prd.location().fileName())
+ QbsBaseProjectNode(prd.location().filePath())
{
if (m_productIcon.isNull())
m_productIcon = generateIcon(QString::fromLatin1(Constants::QBS_PRODUCT_OVERLAY_ICON));
setIcon(m_productIcon);
- ProjectExplorer::FileNode *idx = new QbsFileNode(prd.location().fileName(),
+ ProjectExplorer::FileNode *idx = new QbsFileNode(prd.location().filePath(),
ProjectExplorer::ProjectFileType, false,
prd.location().line());
addFileNodes(QList<ProjectExplorer::FileNode *>() << idx);
@@ -658,18 +658,18 @@ void QbsProductNode::setQbsProductData(const qbs::Project &project, const qbs::P
bool updateExisting = productWasEnabled != productIsEnabled;
setDisplayName(QbsProject::productDisplayName(project, prd));
- setPath(prd.location().fileName());
- const QString &productPath = QFileInfo(prd.location().fileName()).absolutePath();
+ setPath(prd.location().filePath());
+ const QString &productPath = QFileInfo(prd.location().filePath()).absolutePath();
// Find the QbsFileNode we added earlier:
QbsFileNode *idx = 0;
foreach (ProjectExplorer::FileNode *fn, fileNodes()) {
- idx = qobject_cast<QbsFileNode *>(fn);
+ idx = dynamic_cast<QbsFileNode *>(fn);
if (idx)
break;
}
QTC_ASSERT(idx, return);
- idx->setPathAndLine(prd.location().fileName(), prd.location().line());
+ idx->setPathAndLine(prd.location().filePath(), prd.location().line());
QList<ProjectExplorer::ProjectNode *> toAdd;
QList<ProjectExplorer::ProjectNode *> toRemove = subProjectNodes();
@@ -701,7 +701,7 @@ void QbsProductNode::setQbsProductData(const qbs::Project &project, const qbs::P
QList<ProjectExplorer::RunConfiguration *> QbsProductNode::runConfigurations() const
{
QList<ProjectExplorer::RunConfiguration *> result;
- QbsProjectNode *pn = qobject_cast<QbsProjectNode *>(projectNode());
+ QbsProjectNode *pn = dynamic_cast<QbsProjectNode *>(projectNode());
if (!isEnabled() || !pn || !pn->qbsProject().isValid()
|| pn->qbsProject().targetExecutable(m_qbsProductData, qbs::InstallOptions()).isEmpty()) {
return result;
@@ -751,7 +751,7 @@ void QbsProjectNode::update(const qbs::Project &qbsProject, const qbs::ProjectDa
foreach (const qbs::ProjectData &subData, prjData.subProjects()) {
QbsProjectNode *qn = findProjectNode(subData.name());
if (!qn) {
- QbsProjectNode *subProject = new QbsProjectNode(subData.location().fileName());
+ QbsProjectNode *subProject = new QbsProjectNode(subData.location().filePath());
subProject->update(qbsProject, subData);
toAdd << subProject;
} else {
@@ -808,7 +808,7 @@ void QbsProjectNode::ctor()
QbsProductNode *QbsProjectNode::findProductNode(const QString &uniqueName)
{
foreach (ProjectExplorer::ProjectNode *n, subProjectNodes()) {
- QbsProductNode *qn = qobject_cast<QbsProductNode *>(n);
+ QbsProductNode *qn = dynamic_cast<QbsProductNode *>(n);
if (qn && QbsProject::uniqueProductName(qn->qbsProductData()) == uniqueName)
return qn;
}
@@ -818,7 +818,7 @@ QbsProductNode *QbsProjectNode::findProductNode(const QString &uniqueName)
QbsProjectNode *QbsProjectNode::findProjectNode(const QString &name)
{
foreach (ProjectExplorer::ProjectNode *n, subProjectNodes()) {
- QbsProjectNode *qn = qobject_cast<QbsProjectNode *>(n);
+ QbsProjectNode *qn = dynamic_cast<QbsProjectNode *>(n);
if (qn && qn->qbsProjectData().name() == name)
return qn;
}
@@ -833,7 +833,8 @@ QbsRootProjectNode::QbsRootProjectNode(QbsProject *project) :
QbsProjectNode(project->projectFilePath().toString()),
m_project(project),
m_buildSystemFiles(new ProjectExplorer::FolderNode(project->projectDirectory().toString(),
- ProjectExplorer::FolderNodeType, tr("Qbs files")))
+ ProjectExplorer::FolderNodeType,
+ QCoreApplication::translate("QbsRootProjectNode", "Qbs files")))
{
addFolderNodes(QList<FolderNode *>() << m_buildSystemFiles);
}
@@ -856,13 +857,13 @@ void QbsRootProjectNode::update()
static QSet<QString> referencedBuildSystemFiles(const qbs::ProjectData &data)
{
QSet<QString> result;
- result.insert(data.location().fileName());
+ result.insert(data.location().filePath());
foreach (const qbs::ProjectData &subProject, data.subProjects())
result.unite(referencedBuildSystemFiles(subProject));
foreach (const qbs::ProductData &product, data.products()) {
- result.insert(product.location().fileName());
+ result.insert(product.location().filePath());
foreach (const qbs::GroupData &group, product.groups())
- result.insert(group.location().fileName());
+ result.insert(group.location().filePath());
}
return result;
diff --git a/src/plugins/qbsprojectmanager/qbsnodes.h b/src/plugins/qbsprojectmanager/qbsnodes.h
index ed1ea5a5b6d..7903bb2f7fb 100644
--- a/src/plugins/qbsprojectmanager/qbsnodes.h
+++ b/src/plugins/qbsprojectmanager/qbsnodes.h
@@ -50,7 +50,6 @@ class QbsProjectFile;
class QbsFileNode : public ProjectExplorer::FileNode
{
- Q_OBJECT
public:
QbsFileNode(const QString &filePath, const ProjectExplorer::FileType fileType, bool generated,
int line);
@@ -66,8 +65,6 @@ class QbsGroupNode;
class QbsBaseProjectNode : public ProjectExplorer::ProjectNode
{
- Q_OBJECT
-
public:
explicit QbsBaseProjectNode(const QString &path);
@@ -96,8 +93,6 @@ private:
class QbsGroupNode : public QbsBaseProjectNode
{
- Q_OBJECT
-
public:
QbsGroupNode(const qbs::GroupData &grp, const QString &productPath);
@@ -131,8 +126,6 @@ private:
class QbsProductNode : public QbsBaseProjectNode
{
- Q_OBJECT
-
public:
explicit QbsProductNode(const qbs::Project &project, const qbs::ProductData &prd);
@@ -161,8 +154,6 @@ private:
class QbsProjectNode : public QbsBaseProjectNode
{
- Q_OBJECT
-
public:
explicit QbsProjectNode(const QString &path);
~QbsProjectNode();
@@ -192,8 +183,6 @@ private:
class QbsRootProjectNode : public QbsProjectNode
{
- Q_OBJECT
-
public:
explicit QbsRootProjectNode(QbsProject *project);
diff --git a/src/plugins/qbsprojectmanager/qbsprofilessettingspage.cpp b/src/plugins/qbsprojectmanager/qbsprofilessettingspage.cpp
new file mode 100644
index 00000000000..2e939fcffb6
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/qbsprofilessettingspage.cpp
@@ -0,0 +1,242 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "qbsprofilessettingspage.h"
+#include "ui_qbsprofilessettingswidget.h"
+
+#include "customqbspropertiesdialog.h"
+#include "qbsconstants.h"
+#include "qbsprojectmanager.h"
+
+#include <coreplugin/icore.h>
+#include <projectexplorer/kit.h>
+#include <projectexplorer/kitmanager.h>
+#include <utils/algorithm.h>
+#include <utils/qtcassert.h>
+
+#include <qbs.h>
+
+#include <QCoreApplication>
+#include <QHash>
+#include <QWidget>
+
+namespace QbsProjectManager {
+namespace Internal {
+
+class QbsProfilesSettingsWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ QbsProfilesSettingsWidget(QWidget *parent = 0);
+
+ void applyCustomProperties();
+
+private slots:
+ void refreshKitsList();
+ void displayCurrentProfile();
+ void editProfile();
+
+private:
+ void setupCustomProperties(const ProjectExplorer::Kit *kit);
+ void mergeCustomPropertiesIntoModel();
+
+ Ui::QbsProfilesSettingsWidget m_ui;
+ qbs::SettingsModel m_model;
+
+ typedef QHash<Core::Id, QVariantMap> CustomProperties;
+ CustomProperties m_customProperties;
+ bool m_applyingProperties;
+};
+
+QbsProfilesSettingsPage::QbsProfilesSettingsPage(QObject *parent)
+ : Core::IOptionsPage(parent), m_widget(0)
+{
+ setId("AA.QbsProfiles");
+ setDisplayName(tr("Profiles"));
+ setCategory(Constants::QBS_SETTINGS_CATEGORY);
+ setDisplayCategory(QCoreApplication::translate("QbsProjectManager",
+ Constants::QBS_SETTINGS_TR_CATEGORY));
+ setCategoryIcon(QLatin1String(Constants::QBS_SETTINGS_CATEGORY_ICON));
+}
+
+QWidget *QbsProfilesSettingsPage::widget()
+{
+ if (!m_widget)
+ m_widget = new QbsProfilesSettingsWidget;
+ return m_widget;
+}
+
+void QbsProfilesSettingsPage::apply()
+{
+ if (m_widget)
+ m_widget->applyCustomProperties();
+}
+
+void QbsProfilesSettingsPage::finish()
+{
+ delete m_widget;
+ m_widget = 0;
+}
+
+
+QbsProfilesSettingsWidget::QbsProfilesSettingsWidget(QWidget *parent)
+ : QWidget(parent)
+ , m_model(Core::ICore::userResourcePath())
+ , m_applyingProperties(false)
+{
+ m_model.setEditable(false);
+ m_ui.setupUi(this);
+ connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitsChanged,
+ this, &QbsProfilesSettingsWidget::refreshKitsList);
+ connect(m_ui.expandButton, SIGNAL(clicked()), m_ui.propertiesView, SLOT(expandAll()));
+ connect(m_ui.collapseButton, SIGNAL(clicked()), m_ui.propertiesView, SLOT(collapseAll()));
+ connect(m_ui.editButton, SIGNAL(clicked()), SLOT(editProfile()));
+ refreshKitsList();
+}
+
+void QbsProfilesSettingsWidget::applyCustomProperties()
+{
+ QTC_ASSERT(!m_applyingProperties, return);
+ m_applyingProperties = true; // The following will cause kitsChanged() to be emitted.
+ for (CustomProperties::ConstIterator it = m_customProperties.constBegin();
+ it != m_customProperties.constEnd(); ++it) {
+ ProjectExplorer::Kit * const kit = ProjectExplorer::KitManager::find(it.key());
+ QTC_ASSERT(kit, continue);
+ kit->setValue(Core::Id(Constants::QBS_PROPERTIES_KEY_FOR_KITS), it.value());
+ }
+ m_applyingProperties = false;
+ m_model.reload();
+ displayCurrentProfile();
+}
+
+void QbsProfilesSettingsWidget::refreshKitsList()
+{
+ if (m_applyingProperties)
+ return;
+
+ m_ui.kitsComboBox->disconnect(this);
+ m_ui.propertiesView->setModel(0);
+ m_model.reload();
+ m_ui.profileValueLabel->clear();
+ Core::Id currentId;
+ if (m_ui.kitsComboBox->count() > 0)
+ currentId = Core::Id::fromSetting(m_ui.kitsComboBox->currentData());
+ m_ui.kitsComboBox->clear();
+ int newCurrentIndex = -1;
+ QList<ProjectExplorer::Kit *> validKits = ProjectExplorer::KitManager::kits();
+ Utils::erase(validKits, [](const ProjectExplorer::Kit *k) { return !k->isValid(); });
+ const bool hasKits = !validKits.isEmpty();
+ m_customProperties.clear();
+ foreach (const ProjectExplorer::Kit * const kit, validKits) {
+ if (kit->id() == currentId)
+ newCurrentIndex = m_ui.kitsComboBox->count();
+ m_ui.kitsComboBox->addItem(kit->displayName(), kit->id().toSetting());
+ setupCustomProperties(kit);
+ }
+ mergeCustomPropertiesIntoModel();
+ m_ui.editButton->setEnabled(hasKits);
+ if (newCurrentIndex != -1)
+ m_ui.kitsComboBox->setCurrentIndex(newCurrentIndex);
+ else if (hasKits)
+ m_ui.kitsComboBox->setCurrentIndex(0);
+ displayCurrentProfile();
+ connect(m_ui.kitsComboBox, SIGNAL(currentIndexChanged(int)), SLOT(displayCurrentProfile()));
+}
+
+void QbsProfilesSettingsWidget::displayCurrentProfile()
+{
+ m_ui.propertiesView->setModel(0);
+ if (m_ui.kitsComboBox->currentIndex() == -1)
+ return;
+ const Core::Id kitId = Core::Id::fromSetting(m_ui.kitsComboBox->currentData());
+ const ProjectExplorer::Kit * const kit = ProjectExplorer::KitManager::find(kitId);
+ QTC_ASSERT(kit, return);
+ const QString profileName = QbsManager::instance()->profileForKit(kit);
+ m_ui.profileValueLabel->setText(profileName);
+ for (int i = 0; i < m_model.rowCount(); ++i) {
+ const QModelIndex profilesIndex = m_model.index(i, 0);
+ if (m_model.data(profilesIndex).toString() != QLatin1String("profiles"))
+ continue;
+ for (int i = 0; i < m_model.rowCount(profilesIndex); ++i) {
+ const QModelIndex currentProfileIndex = m_model.index(i, 0, profilesIndex);
+ if (m_model.data(currentProfileIndex).toString() != profileName)
+ continue;
+ m_ui.propertiesView->setModel(&m_model);
+ m_ui.propertiesView->header()->setSectionResizeMode(m_model.keyColumn(),
+ QHeaderView::ResizeToContents);
+ m_ui.propertiesView->setRootIndex(currentProfileIndex);
+ return;
+ }
+ }
+}
+
+void QbsProfilesSettingsWidget::editProfile()
+{
+ QTC_ASSERT(m_ui.kitsComboBox->currentIndex() != -1, return);
+
+ const Core::Id kitId = Core::Id::fromSetting(m_ui.kitsComboBox->currentData());
+ CustomQbsPropertiesDialog dlg(m_customProperties.value(kitId), this);
+ if (dlg.exec() != QDialog::Accepted)
+ return;
+
+ m_customProperties.insert(kitId, dlg.properties());
+ mergeCustomPropertiesIntoModel();
+ displayCurrentProfile();
+}
+
+void QbsProfilesSettingsWidget::setupCustomProperties(const ProjectExplorer::Kit *kit)
+{
+ const QVariantMap &properties
+ = kit->value(Core::Id(Constants::QBS_PROPERTIES_KEY_FOR_KITS)).toMap();
+ m_customProperties.insert(kit->id(), properties);
+}
+
+void QbsProfilesSettingsWidget::mergeCustomPropertiesIntoModel()
+{
+ QVariantMap customProperties;
+ for (CustomProperties::ConstIterator it = m_customProperties.constBegin();
+ it != m_customProperties.constEnd(); ++it) {
+ const Core::Id kitId = it.key();
+ const ProjectExplorer::Kit * const kit = ProjectExplorer::KitManager::find(kitId);
+ QTC_ASSERT(kit, continue);
+ const QString keyPrefix = QLatin1String("profiles.")
+ + QbsManager::instance()->profileForKit(kit) + QLatin1Char('.');
+ for (QVariantMap::ConstIterator it2 = it.value().constBegin(); it2 != it.value().constEnd();
+ ++it2) {
+ customProperties.insert(keyPrefix + it2.key(), it2.value());
+ }
+ }
+ m_model.setAdditionalProperties(customProperties);
+}
+
+} // namespace Internal
+} // namespace QbsProjectManager
+
+#include "qbsprofilessettingspage.moc"
diff --git a/src/plugins/qbsprojectmanager/qbsprofilessettingspage.h b/src/plugins/qbsprojectmanager/qbsprofilessettingspage.h
new file mode 100644
index 00000000000..5f0af3a7a96
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/qbsprofilessettingspage.h
@@ -0,0 +1,56 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 QBSPROFILESSETTINGSPAGE_H
+#define QBSPROFILESSETTINGSPAGE_H
+
+#include <coreplugin/dialogs/ioptionspage.h>
+
+namespace QbsProjectManager {
+namespace Internal {
+class QbsProfilesSettingsWidget;
+
+class QbsProfilesSettingsPage : public Core::IOptionsPage
+{
+public:
+ QbsProfilesSettingsPage(QObject *parent = 0);
+
+private:
+ QWidget *widget() Q_DECL_OVERRIDE;
+ void apply() Q_DECL_OVERRIDE;
+ void finish() Q_DECL_OVERRIDE;
+
+ QbsProfilesSettingsWidget *m_widget;
+};
+
+} // namespace Internal
+} // namespace QbsProjectManager
+
+#endif // Include guard.
diff --git a/src/plugins/qbsprojectmanager/qbsprofilessettingswidget.ui b/src/plugins/qbsprojectmanager/qbsprofilessettingswidget.ui
new file mode 100644
index 00000000000..38a90165767
--- /dev/null
+++ b/src/plugins/qbsprojectmanager/qbsprofilessettingswidget.ui
@@ -0,0 +1,125 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>QbsProjectManager::Internal::QbsProfilesSettingsWidget</class>
+ <widget class="QWidget" name="QbsProjectManager::Internal::QbsProfilesSettingsWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>421</width>
+ <height>315</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <layout class="QFormLayout" name="formLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="kitLabel">
+ <property name="text">
+ <string>Kit:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QComboBox" name="kitsComboBox"/>
+ </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="1" column="0">
+ <widget class="QLabel" name="profileKeyLabel">
+ <property name="text">
+ <string>Associated profile:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLabel" name="profileValueLabel">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="Line" name="line">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="propertiesLabel">
+ <property name="text">
+ <string>Profile properties:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QTreeView" name="propertiesView"/>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QPushButton" name="expandButton">
+ <property name="text">
+ <string>E&amp;xpand All</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="collapseButton">
+ <property name="text">
+ <string>&amp;Collapse All</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="editButton">
+ <property name="text">
+ <string>&amp;Edit...</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/qbsprojectmanager/qbsproject.cpp b/src/plugins/qbsprojectmanager/qbsproject.cpp
index a28373952cf..59eabb936b2 100644
--- a/src/plugins/qbsprojectmanager/qbsproject.cpp
+++ b/src/plugins/qbsprojectmanager/qbsproject.cpp
@@ -48,7 +48,6 @@
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/mimedatabase.h>
#include <cpptools/cppmodelmanager.h>
-#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/buildenvironmentwidget.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/buildtargetinfo.h>
@@ -110,7 +109,6 @@ QbsProject::QbsProject(QbsManager *manager, const QString &fileName) :
m_qbsUpdateFutureInterface(0),
m_parsingScheduled(false),
m_cancelStatus(CancelStatusNone),
- m_codeModelProjectInfo(this),
m_currentBc(0)
{
m_parsingDelay.setInterval(1000); // delay parsing by 1s.
@@ -159,7 +157,7 @@ QString QbsProject::displayName() const
IDocument *QbsProject::document() const
{
foreach (IDocument *doc, m_qbsDocuments) {
- if (doc->filePath() == m_fileName)
+ if (doc->filePath().toString() == m_fileName)
return doc;
}
QTC_ASSERT(false, return 0);
@@ -177,14 +175,14 @@ ProjectNode *QbsProject::rootProjectNode() const
static void collectFilesForProject(const qbs::ProjectData &project, QSet<QString> &result)
{
- result.insert(project.location().fileName());
+ result.insert(project.location().filePath());
foreach (const qbs::ProductData &prd, project.products()) {
foreach (const qbs::GroupData &grp, prd.groups()) {
foreach (const QString &file, grp.allFilePaths())
result.insert(file);
- result.insert(grp.location().fileName());
+ result.insert(grp.location().filePath());
}
- result.insert(prd.location().fileName());
+ result.insert(prd.location().filePath());
}
foreach (const qbs::ProjectData &subProject, project.subProjects())
collectFilesForProject(subProject, result);
@@ -203,36 +201,36 @@ QStringList QbsProject::files(Project::FilesMode fileMode) const
bool QbsProject::isProjectEditable() const
{
- return m_qbsProject.isValid() && !isParsing() && !ProjectExplorer::BuildManager::isBuilding();
+ return m_qbsProject.isValid() && !isParsing() && !BuildManager::isBuilding();
}
class ChangeExpector
{
public:
- ChangeExpector(const QString &filePath, const QSet<Core::IDocument *> &documents)
+ ChangeExpector(const QString &filePath, const QSet<IDocument *> &documents)
: m_document(0)
{
- foreach (Core::IDocument * const doc, documents) {
- if (doc->filePath() == filePath) {
+ foreach (IDocument * const doc, documents) {
+ if (doc->filePath().toString() == filePath) {
m_document = doc;
break;
}
}
QTC_ASSERT(m_document, return);
- Core::DocumentManager::expectFileChange(filePath);
- m_wasInDocumentManager = Core::DocumentManager::removeDocument(m_document);
+ DocumentManager::expectFileChange(filePath);
+ m_wasInDocumentManager = DocumentManager::removeDocument(m_document);
QTC_CHECK(m_wasInDocumentManager);
}
~ChangeExpector()
{
QTC_ASSERT(m_document, return);
- Core::DocumentManager::addDocument(m_document);
- Core::DocumentManager::unexpectFileChange(m_document->filePath());
+ DocumentManager::addDocument(m_document);
+ DocumentManager::unexpectFileChange(m_document->filePath().toString());
}
private:
- Core::IDocument *m_document;
+ IDocument *m_document;
bool m_wasInDocumentManager;
};
@@ -242,12 +240,12 @@ bool QbsProject::ensureWriteableQbsFile(const QString &file)
QFileInfo fi(file);
if (!fi.isWritable()) {
// Try via vcs manager
- Core::IVersionControl *versionControl =
- Core::VcsManager::findVersionControlForDirectory(fi.absolutePath());
+ IVersionControl *versionControl =
+ VcsManager::findVersionControlForDirectory(fi.absolutePath());
if (!versionControl || !versionControl->vcsOpen(file)) {
bool makeWritable = QFile::setPermissions(file, fi.permissions() | QFile::WriteUser);
if (!makeWritable) {
- QMessageBox::warning(Core::ICore::mainWindow(),
+ QMessageBox::warning(ICore::mainWindow(),
tr("Failed!"),
tr("Could not write project file %1.").arg(file));
return false;
@@ -262,13 +260,13 @@ bool QbsProject::addFilesToProduct(QbsBaseProjectNode *node, const QStringList &
{
QTC_ASSERT(m_qbsProject.isValid(), return false);
QStringList allPaths = groupData.allFilePaths();
- const QString productFilePath = productData.location().fileName();
+ const QString productFilePath = productData.location().filePath();
ChangeExpector expector(productFilePath, m_qbsDocuments);
ensureWriteableQbsFile(productFilePath);
foreach (const QString &path, filePaths) {
qbs::ErrorInfo err = m_qbsProject.addFiles(productData, groupData, QStringList() << path);
if (err.hasError()) {
- Core::MessageManager::write(err.toString());
+ MessageManager::write(err.toString());
*notAdded += path;
} else {
allPaths += path;
@@ -288,14 +286,14 @@ bool QbsProject::removeFilesFromProduct(QbsBaseProjectNode *node, const QStringL
{
QTC_ASSERT(m_qbsProject.isValid(), return false);
QStringList allPaths = groupData.allFilePaths();
- const QString productFilePath = productData.location().fileName();
+ const QString productFilePath = productData.location().filePath();
ChangeExpector expector(productFilePath, m_qbsDocuments);
ensureWriteableQbsFile(productFilePath);
foreach (const QString &path, filePaths) {
qbs::ErrorInfo err
= m_qbsProject.removeFiles(productData, groupData, QStringList() << path);
if (err.hasError()) {
- Core::MessageManager::write(err.toString());
+ MessageManager::write(err.toString());
*notRemoved += path;
} else {
allPaths.removeOne(path);
@@ -365,7 +363,7 @@ qbs::BuildJob *QbsProject::build(const qbs::BuildOptions &opts, QStringList prod
}
}
if (!found) {
- error = QLatin1String("Cannot build: Selected products do not exist anymore."); // TODO: Use tr() in 3.4
+ error = tr("Cannot build: Selected products do not exist anymore.");
return 0;
}
}
@@ -491,7 +489,7 @@ void QbsProject::startParsing()
{
// Qbs does update the build graph during the build. So we cannot
// start to parse while a build is running or we will lose information.
- if (ProjectExplorer::BuildManager::isBuilding(this)) {
+ if (BuildManager::isBuilding(this)) {
scheduleParsing();
return;
}
@@ -605,7 +603,7 @@ void QbsProject::generateErrors(const qbs::ErrorInfo &e)
foreach (const qbs::ErrorItem &item, e.items())
TaskHub::addTask(Task::Error, item.description(),
ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM,
- FileName::fromString(item.codeLocation().fileName()),
+ FileName::fromString(item.codeLocation().filePath()),
item.codeLocation().line());
}
@@ -631,9 +629,7 @@ void QbsProject::parse(const QVariantMap &config, const Environment &env, const
registerQbsProjectParser(new QbsProjectParser(this, m_qbsUpdateFutureInterface));
- QbsManager * const qbsManager = ExtensionSystem::PluginManager::getObject<QbsManager>();
- QTC_ASSERT(qbsManager, return);
- qbsManager->updateProfileIfNecessary(activeTarget()->kit());
+ QbsManager::instance()->updateProfileIfNecessary(activeTarget()->kit());
m_qbsProjectParser->parse(config, env, dir);
emit projectParsingStarted();
}
@@ -662,7 +658,7 @@ void QbsProject::updateDocuments(const QSet<QString> &files)
QTC_ASSERT(!newFiles.isEmpty(), newFiles << m_fileName);
QSet<QString> oldFiles;
foreach (IDocument *doc, m_qbsDocuments)
- oldFiles.insert(doc->filePath());
+ oldFiles.insert(doc->filePath().toString());
QSet<QString> filesToAdd = newFiles;
filesToAdd.subtract(oldFiles);
@@ -671,7 +667,7 @@ void QbsProject::updateDocuments(const QSet<QString> &files)
QSet<IDocument *> currentDocuments = m_qbsDocuments;
foreach (IDocument *doc, currentDocuments) {
- if (filesToRemove.contains(doc->filePath())) {
+ if (filesToRemove.contains(doc->filePath().toString())) {
m_qbsDocuments.remove(doc);
delete doc;
}
@@ -696,9 +692,7 @@ void QbsProject::updateCppCodeModel()
if (!modelmanager)
return;
- CppTools::ProjectInfo pinfo = modelmanager->projectInfo(this);
- pinfo.clearProjectParts();
-
+ CppTools::ProjectInfo pinfo = CppTools::ProjectInfo(this);
CppTools::ProjectPartBuilder ppBuilder(pinfo);
if (qtVersion) {
@@ -764,7 +758,7 @@ void QbsProject::updateCppCodeModel()
ppBuilder.setDisplayName(grp.name());
ppBuilder.setProjectFile(QString::fromLatin1("%1:%2:%3")
- .arg(grp.location().fileName())
+ .arg(grp.location().filePath())
.arg(grp.location().line())
.arg(grp.location().column()));
@@ -777,9 +771,9 @@ void QbsProject::updateCppCodeModel()
}
}
- const QList<Core::Id> languages =
+ const QList<Id> languages =
ppBuilder.createProjectPartsForFiles(grp.allFilePaths());
- foreach (Core::Id language, languages)
+ foreach (Id language, languages)
setProjectLanguage(language, true);
}
}
@@ -794,6 +788,7 @@ void QbsProject::updateCppCodeModel()
m_codeModelFuture.cancel();
m_codeModelFuture = modelmanager->updateProjectInfo(pinfo);
m_codeModelProjectInfo = modelmanager->projectInfo(this);
+ QTC_CHECK(m_codeModelProjectInfo == pinfo);
}
void QbsProject::updateCppCompilerCallData()
@@ -852,24 +847,24 @@ void QbsProject::updateQmlJsCodeModel()
void QbsProject::updateApplicationTargets()
{
- ProjectExplorer::BuildTargetInfoList applications;
+ BuildTargetInfoList applications;
foreach (const qbs::ProductData &productData, m_projectData.allProducts()) {
if (!productData.isEnabled() || !productData.isRunnable())
continue;
const QString displayName = productDisplayName(m_qbsProject, productData);
if (productData.targetArtifacts().isEmpty()) { // No build yet.
- applications.list << ProjectExplorer::BuildTargetInfo(displayName,
- Utils::FileName(),
- Utils::FileName::fromString(productData.location().fileName()));
+ applications.list << BuildTargetInfo(displayName,
+ FileName(),
+ FileName::fromString(productData.location().filePath()));
continue;
}
foreach (const qbs::TargetArtifact &ta, productData.targetArtifacts()) {
QTC_ASSERT(ta.isValid(), continue);
if (!ta.isExecutable())
continue;
- applications.list << ProjectExplorer::BuildTargetInfo(displayName,
- Utils::FileName::fromString(ta.filePath()),
- Utils::FileName::fromString(productData.location().fileName()));
+ applications.list << BuildTargetInfo(displayName,
+ FileName::fromString(ta.filePath()),
+ FileName::fromString(productData.location().filePath()));
}
}
activeTarget()->setApplicationTargets(applications);
@@ -877,15 +872,15 @@ void QbsProject::updateApplicationTargets()
void QbsProject::updateDeploymentInfo()
{
- ProjectExplorer::DeploymentData deploymentData;
+ DeploymentData deploymentData;
if (m_qbsProject.isValid()) {
qbs::InstallOptions installOptions;
installOptions.setInstallRoot(QLatin1String("/"));
foreach (const qbs::InstallableFile &f, m_qbsProject
.installableFilesForProject(m_projectData, installOptions)) {
deploymentData.addFile(f.sourceFilePath(), f.targetDirectory(), f.isExecutable()
- ? ProjectExplorer::DeployableFile::TypeExecutable
- : ProjectExplorer::DeployableFile::TypeNormal);
+ ? DeployableFile::TypeExecutable
+ : DeployableFile::TypeNormal);
}
}
activeTarget()->setDeploymentData(deploymentData);
diff --git a/src/plugins/qbsprojectmanager/qbsprojectfile.cpp b/src/plugins/qbsprojectmanager/qbsprojectfile.cpp
index 1a06b32b306..61842e2ad8a 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectfile.cpp
+++ b/src/plugins/qbsprojectmanager/qbsprojectfile.cpp
@@ -41,7 +41,7 @@ QbsProjectFile::QbsProjectFile(QbsProject *parent, QString fileName) : Core::IDo
{
setId("Qbs.ProjectFile");
setMimeType(QLatin1String(Constants::MIME_TYPE));
- setFilePath(fileName);
+ setFilePath(Utils::FileName::fromString(fileName));
}
QbsProjectFile::~QbsProjectFile()
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp b/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp
index 83f50538ab2..359f1397c7c 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.cpp
@@ -57,14 +57,17 @@ static QString qtcProfileGroup() { return QLatin1String("preferences.qtcreator.k
static QString qtcProfilePrefix() { return qtcProfileGroup() + sep; }
namespace QbsProjectManager {
+namespace Internal {
qbs::Settings *QbsManager::m_settings = 0;
Internal::QbsLogSink *QbsManager::m_logSink = 0;
+QbsManager *QbsManager::m_instance = 0;
QbsManager::QbsManager() :
m_defaultPropertyProvider(new DefaultPropertyProvider)
{
m_settings = new qbs::Settings(Core::ICore::userResourcePath());
+ m_instance = this;
setObjectName(QLatin1String("QbsProjectManager"));
connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitsLoaded, this,
@@ -76,7 +79,7 @@ QbsManager::QbsManager() :
connect(ProjectExplorer::KitManager::instance(), &ProjectExplorer::KitManager::kitRemoved, this,
&QbsManager::handleKitRemoval);
- m_logSink = new Internal::QbsLogSink(this);
+ m_logSink = new QbsLogSink(this);
int level = qbs::LoggerWarning;
const QString levelEnv = QString::fromLocal8Bit(qgetenv("QBS_LOG_LEVEL"));
if (!levelEnv.isEmpty()) {
@@ -97,6 +100,7 @@ QbsManager::~QbsManager()
{
delete m_defaultPropertyProvider;
delete m_settings;
+ m_instance = 0;
}
QString QbsManager::mimeType() const
@@ -113,10 +117,10 @@ ProjectExplorer::Project *QbsManager::openProject(const QString &fileName, QStri
return 0;
}
- return new Internal::QbsProject(this, fileName);
+ return new QbsProject(this, fileName);
}
-QString QbsManager::profileForKit(ProjectExplorer::Kit *k)
+QString QbsManager::profileForKit(const ProjectExplorer::Kit *k)
{
if (!k)
return QString();
@@ -129,9 +133,11 @@ void QbsManager::setProfileForKit(const QString &name, const ProjectExplorer::Ki
m_settings->setValue(qtcProfilePrefix() + k->id().toString(), name);
}
-void QbsManager::updateProfileIfNecessary(ProjectExplorer::Kit *kit)
+void QbsManager::updateProfileIfNecessary(const ProjectExplorer::Kit *kit)
{
- if (m_kitsToBeSetupForQbs.removeOne(kit)) // kit in list <=> yes, it is necessary
+ // kit in list <=> profile update is necessary
+ // Note that the const_cast is safe, as we do not call any non-const methods on the object.
+ if (m_kitsToBeSetupForQbs.removeOne(const_cast<ProjectExplorer::Kit *>(kit)))
addProfileFromKit(kit);
}
@@ -186,7 +192,8 @@ void QbsManager::addQtProfileFromKit(const QString &profileName, const ProjectEx
void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k)
{
- const QString name = QString::fromLatin1("qtc_") + k->fileSystemFriendlyName();
+ const QString name = QString::fromLatin1("qtc_%1_%2").arg(k->fileSystemFriendlyName().left(8),
+ QString::number(k->id().uniqueIdentifier(), 16));
setProfileForKit(name, k);
addQtProfileFromKit(name, k);
@@ -216,4 +223,5 @@ void QbsManager::handleKitRemoval(ProjectExplorer::Kit *kit)
qbs::Profile(profileName, m_settings).removeProfile();
}
+} // namespace Internal
} // namespace QbsProjectManager
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.h b/src/plugins/qbsprojectmanager/qbsprojectmanager.h
index 4833247d8ce..194d23775e1 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.h
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.h
@@ -52,13 +52,10 @@ class ProjectExplorerPlugin;
} // namespace ProjectExplorer
namespace QbsProjectManager {
-
namespace Internal {
+class DefaultPropertyProvider;
class QbsLogSink;
class QbsProject;
-} // namespace Internal
-
-class DefaultPropertyProvider;
class QbsManager : public ProjectExplorer::IProjectManager
{
@@ -72,13 +69,14 @@ public:
ProjectExplorer::Project *openProject(const QString &fileName, QString *errorString);
// QBS profiles management:
- QString profileForKit(ProjectExplorer::Kit *k);
+ QString profileForKit(const ProjectExplorer::Kit *k);
void setProfileForKit(const QString &name, const ProjectExplorer::Kit *k);
- void updateProfileIfNecessary(ProjectExplorer::Kit *kit);
+ void updateProfileIfNecessary(const ProjectExplorer::Kit *kit);
static qbs::Settings *settings() { return m_settings; }
static Internal::QbsLogSink *logSink() { return m_logSink; }
+ static QbsManager *instance() { return m_instance; }
private:
void addProfile(const QString &name, const QVariantMap &data);
@@ -88,13 +86,15 @@ private:
void handleKitUpdate(ProjectExplorer::Kit *kit);
void handleKitRemoval(ProjectExplorer::Kit *kit);
- static Internal::QbsLogSink *m_logSink;
+ static QbsLogSink *m_logSink;
static qbs::Settings *m_settings;
DefaultPropertyProvider *m_defaultPropertyProvider;
QList<ProjectExplorer::Kit *> m_kitsToBeSetupForQbs;
+ static QbsManager *m_instance;
};
+} // namespace Internal
} // namespace QbsProjectManager
#endif // QBSPROJECTMANAGER_H
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.pro b/src/plugins/qbsprojectmanager/qbsprojectmanager.pro
index 65f21669db7..9262c5317b2 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.pro
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.pro
@@ -18,6 +18,7 @@ DEFINES += \
QBSPROJECTMANAGER_LIBRARY
HEADERS = \
+ customqbspropertiesdialog.h \
defaultpropertyprovider.h \
propertyprovider.h \
qbsbuildconfiguration.h \
@@ -30,6 +31,7 @@ HEADERS = \
qbslogsink.h \
qbsnodes.h \
qbsparser.h \
+ qbsprofilessettingspage.h \
qbsproject.h \
qbsprojectfile.h \
qbsprojectmanager.h \
@@ -42,6 +44,7 @@ HEADERS = \
qbsconstants.h
SOURCES = \
+ customqbspropertiesdialog.cpp \
defaultpropertyprovider.cpp \
qbsbuildconfiguration.cpp \
qbsbuildconfigurationwidget.cpp \
@@ -52,6 +55,7 @@ SOURCES = \
qbslogsink.cpp \
qbsnodes.cpp \
qbsparser.cpp \
+ qbsprofilessettingspage.cpp \
qbsproject.cpp \
qbsprojectfile.cpp \
qbsprojectmanager.cpp \
@@ -61,9 +65,11 @@ SOURCES = \
qbsrunconfiguration.cpp
FORMS = \
+ customqbspropertiesdialog.ui \
qbsbuildstepconfigwidget.ui \
qbscleanstepconfigwidget.ui \
- qbsinstallstepconfigwidget.ui
+ qbsinstallstepconfigwidget.ui \
+ qbsprofilessettingswidget.ui
RESOURCES += \
qbsprojectmanager.qrc
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs b/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs
index e9be220f3e0..a33ad0da968 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanager.qbs
@@ -59,7 +59,9 @@ QtcPlugin {
cpp.dynamicLibraries: base.concat(externalQbsDynamicLibraries)
files: [
- "qbsprojectmanager.qrc",
+ "customqbspropertiesdialog.h",
+ "customqbspropertiesdialog.cpp",
+ "customqbspropertiesdialog.ui",
"defaultpropertyprovider.cpp",
"defaultpropertyprovider.h",
"propertyprovider.h",
@@ -86,12 +88,16 @@ QtcPlugin {
"qbsnodes.h",
"qbsparser.cpp",
"qbsparser.h",
+ "qbsprofilessettingspage.cpp",
+ "qbsprofilessettingspage.h",
+ "qbsprofilessettingswidget.ui",
"qbsproject.cpp",
"qbsproject.h",
"qbsprojectfile.cpp",
"qbsprojectfile.h",
"qbsprojectmanager.cpp",
"qbsprojectmanager.h",
+ "qbsprojectmanager.qrc",
"qbsprojectmanager_global.h",
"qbsprojectmanagerconstants.h",
"qbsprojectmanagerplugin.cpp",
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp
index 4f2df12382e..b27f9dc2cc3 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.cpp
@@ -36,6 +36,7 @@
#include "qbsdeployconfigurationfactory.h"
#include "qbsinstallstep.h"
#include "qbsnodes.h"
+#include "qbsprofilessettingspage.h"
#include "qbsproject.h"
#include "qbsprojectmanager.h"
#include "qbsprojectmanagerconstants.h"
@@ -52,10 +53,13 @@
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <qtsupport/qtsupportconstants.h>
+
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QAction>
@@ -69,13 +73,13 @@ namespace Internal {
static Node *currentEditorNode()
{
Core::IDocument *doc = Core::EditorManager::currentDocument();
- return doc ? SessionManager::nodeForFile(doc->filePath()) : 0;
+ return doc ? SessionManager::nodeForFile(doc->filePath().toString()) : 0;
}
static QbsProject *currentEditorProject()
{
Core::IDocument *doc = Core::EditorManager::currentDocument();
- return doc ? qobject_cast<QbsProject *>(SessionManager::projectForFile(doc->filePath())) : 0;
+ return doc ? qobject_cast<QbsProject *>(SessionManager::projectForFile(doc->filePath().toString())) : 0;
}
QbsProjectManagerPlugin::QbsProjectManagerPlugin() :
@@ -104,6 +108,7 @@ bool QbsProjectManagerPlugin::initialize(const QStringList &arguments, QString *
addAutoReleasedObject(new QbsInstallStepFactory);
addAutoReleasedObject(new QbsDeployConfigurationFactory);
addAutoReleasedObject(new QbsRunConfigurationFactory);
+ addAutoReleasedObject(new QbsProfilesSettingsPage);
//menus
// Build Menu:
@@ -182,9 +187,8 @@ bool QbsProjectManagerPlugin::initialize(const QStringList &arguments, QString *
connect(m_buildSubproject, SIGNAL(triggered()), this, SLOT(buildSubproject()));
// Connect
- connect(ProjectExplorer::ProjectExplorerPlugin::instance(),
- SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),
- this, SLOT(nodeSelectionChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)));
+ connect(ProjectTree::instance(), &ProjectTree::currentNodeChanged,
+ this, &QbsProjectManagerPlugin::nodeSelectionChanged);
connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
this, SLOT(buildStateChanged(ProjectExplorer::Project*)));
@@ -250,9 +254,9 @@ void QbsProjectManagerPlugin::updateContextActions()
&& m_selectedProject && !m_selectedProject->isParsing()
&& m_selectedNode && m_selectedNode->isEnabled();
- bool isFile = m_selectedProject && m_selectedNode && (m_selectedNode->nodeType() == ProjectExplorer::FileNodeType);
- bool isProduct = m_selectedProject && m_selectedNode && qobject_cast<QbsProductNode *>(m_selectedNode->projectNode());
- QbsProjectNode *subproject = qobject_cast<QbsProjectNode *>(m_selectedNode);
+ bool isFile = m_selectedProject && m_selectedNode && (m_selectedNode->nodeType() == FileNodeType);
+ bool isProduct = m_selectedProject && m_selectedNode && dynamic_cast<QbsProductNode *>(m_selectedNode->projectNode());
+ QbsProjectNode *subproject = dynamic_cast<QbsProjectNode *>(m_selectedNode);
bool isSubproject = m_selectedProject && subproject && subproject != m_selectedProject->rootProjectNode();
m_reparseQbsCtx->setEnabled(isEnabled);
@@ -284,18 +288,18 @@ void QbsProjectManagerPlugin::updateBuildActions()
&& !BuildManager::isBuilding(m_editorProject)
&& !m_editorProject->isParsing();
- fileName = QFileInfo(m_editorNode->path()).fileName();
- fileVisible = m_editorProject && m_editorNode && qobject_cast<QbsBaseProjectNode *>(m_editorNode->projectNode());
+ fileName = Utils::FileName::fromString(m_editorNode->path()).fileName();
+ fileVisible = m_editorProject && m_editorNode && dynamic_cast<QbsBaseProjectNode *>(m_editorNode->projectNode());
QbsProductNode *productNode
- = qobject_cast<QbsProductNode *>(m_editorNode ? m_editorNode->projectNode() : 0);
+ = dynamic_cast<QbsProductNode *>(m_editorNode ? m_editorNode->projectNode() : 0);
if (productNode) {
productVisible = true;
productName = productNode->displayName();
}
QbsProjectNode *subprojectNode
- = qobject_cast<QbsProjectNode *>(productNode ? productNode->parentFolderNode() : 0);
- if (subprojectNode && subprojectNode != m_editorProject->rootProjectNode()) {
+ = dynamic_cast<QbsProjectNode *>(productNode ? productNode->parentFolderNode() : 0);
+ if (subprojectNode && m_editorProject && subprojectNode != m_editorProject->rootProjectNode()) {
subprojectVisible = true;
subprojectName = subprojectNode->displayName();
}
@@ -314,7 +318,7 @@ void QbsProjectManagerPlugin::updateBuildActions()
m_buildSubproject->setParameter(subprojectName);
}
-void QbsProjectManagerPlugin::buildStateChanged(ProjectExplorer::Project *project)
+void QbsProjectManagerPlugin::buildStateChanged(Project *project)
{
if (project == m_currentProject)
updateReparseQbsAction();
@@ -373,7 +377,7 @@ void QbsProjectManagerPlugin::buildProductContextMenu()
QTC_ASSERT(m_selectedNode, return);
QTC_ASSERT(m_selectedProject, return);
- const QbsProductNode * const productNode = qobject_cast<QbsProductNode *>(m_selectedNode);
+ const QbsProductNode * const productNode = dynamic_cast<QbsProductNode *>(m_selectedNode);
QTC_ASSERT(productNode, return);
buildProducts(m_selectedProject,
@@ -385,7 +389,7 @@ void QbsProjectManagerPlugin::buildProduct()
if (!m_editorProject || !m_editorNode)
return;
- QbsProductNode *product = qobject_cast<QbsProductNode *>(m_editorNode->projectNode());
+ QbsProductNode *product = dynamic_cast<QbsProductNode *>(m_editorNode->projectNode());
if (!product)
return;
@@ -399,7 +403,7 @@ void QbsProjectManagerPlugin::buildSubprojectContextMenu()
QTC_ASSERT(m_selectedNode, return);
QTC_ASSERT(m_selectedProject, return);
- QbsProjectNode *subProject = qobject_cast<QbsProjectNode *>(m_selectedNode);
+ QbsProjectNode *subProject = dynamic_cast<QbsProjectNode *>(m_selectedNode);
QTC_ASSERT(subProject, return);
QStringList toBuild;
@@ -415,14 +419,14 @@ void QbsProjectManagerPlugin::buildSubproject()
return;
QbsProjectNode *subproject = 0;
- QbsBaseProjectNode *start = qobject_cast<QbsBaseProjectNode *>(m_editorNode->projectNode());
+ QbsBaseProjectNode *start = dynamic_cast<QbsBaseProjectNode *>(m_editorNode->projectNode());
while (start && start != m_editorProject->rootProjectNode()) {
- QbsProjectNode *tmp = qobject_cast<QbsProjectNode *>(start);
+ QbsProjectNode *tmp = dynamic_cast<QbsProjectNode *>(start);
if (tmp) {
subproject = tmp;
break;
}
- start = qobject_cast<QbsProjectNode *>(start->parentFolderNode());
+ start = dynamic_cast<QbsProjectNode *>(start->parentFolderNode());
}
if (!subproject)
@@ -441,7 +445,7 @@ void QbsProjectManagerPlugin::buildFiles(QbsProject *project, const QStringList
QTC_ASSERT(project, return);
QTC_ASSERT(!files.isEmpty(), return);
- ProjectExplorer::Target *t = project->activeTarget();
+ Target *t = project->activeTarget();
if (!t)
return;
QbsBuildConfiguration *bc = qobject_cast<QbsBuildConfiguration *>(t->activeBuildConfiguration());
@@ -457,7 +461,7 @@ void QbsProjectManagerPlugin::buildFiles(QbsProject *project, const QStringList
const Core::Id buildStep = ProjectExplorer::Constants::BUILDSTEPS_BUILD;
- const QString name = ProjectExplorer::ProjectExplorerPlugin::displayNameForStepId(buildStep);
+ const QString name = ProjectExplorerPlugin::displayNameForStepId(buildStep);
BuildManager::buildList(bc->stepList(buildStep), name);
bc->setChangedFiles(QStringList());
@@ -475,7 +479,7 @@ void QbsProjectManagerPlugin::buildProducts(QbsProject *project, const QStringLi
QTC_ASSERT(project, return);
QTC_ASSERT(!products.isEmpty(), return);
- ProjectExplorer::Target *t = project->activeTarget();
+ Target *t = project->activeTarget();
if (!t)
return;
QbsBuildConfiguration *bc = qobject_cast<QbsBuildConfiguration *>(t->activeBuildConfiguration());
diff --git a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h
index bf5d301d832..719a8b379fd 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h
+++ b/src/plugins/qbsprojectmanager/qbsprojectmanagerplugin.h
@@ -48,8 +48,6 @@ class Target;
} // namespace ProjectExplorer
namespace QbsProjectManager {
-class QbsManager;
-
namespace Internal {
class QbsProject;
diff --git a/src/plugins/qbsprojectmanager/qbsprojectparser.cpp b/src/plugins/qbsprojectmanager/qbsprojectparser.cpp
index 8adbf921ad4..33de434ef91 100644
--- a/src/plugins/qbsprojectmanager/qbsprojectparser.cpp
+++ b/src/plugins/qbsprojectmanager/qbsprojectparser.cpp
@@ -168,7 +168,7 @@ QString QbsProjectParser::pluginsBaseDirectory() const
const QString qbsInstallDir = QLatin1String(QBS_INSTALL_DIR);
if (!qbsInstallDir.isEmpty())
return qbsInstallDir + QLatin1String("/lib/");
- if (Utils::HostOsInfo::isMacHost())
+ if (HostOsInfo::isMacHost())
return QDir::cleanPath(QCoreApplication::applicationDirPath()
+ QLatin1String("/../PlugIns"));
else
diff --git a/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp b/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp
index 61c9d5b72bb..7496145e1cf 100644
--- a/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp
+++ b/src/plugins/qbsprojectmanager/qbsrunconfiguration.cpp
@@ -329,7 +329,6 @@ void QbsRunConfiguration::addToBaseEnvironment(Utils::Environment &env) const
const qbs::ProductData product = findProduct(project->qbsProjectData(), m_uniqueProductName);
if (product.isValid()) {
QProcessEnvironment procEnv = env.toProcessEnvironment();
- procEnv.insert(QLatin1String("QBS_INSTALL_ROOT"), installRoot());
procEnv.insert(QLatin1String("QBS_RUN_FILE_PATH"), executable());
qbs::RunEnvironment qbsRunEnv = project->qbsProject().getRunEnvironment(product, installOptions(),
procEnv, QbsManager::settings());
@@ -412,10 +411,10 @@ QbsRunConfigurationWidget::QbsRunConfigurationWidget(QbsRunConfiguration *rc, QW
toplayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
toplayout->setMargin(0);
- m_executableLineEdit = new QLineEdit(this);
- m_executableLineEdit->setEnabled(false);
- m_executableLineEdit->setPlaceholderText(tr("<unknown>"));
- toplayout->addRow(tr("Executable:"), m_executableLineEdit);
+ m_executableLineLabel = new QLabel(this);
+ m_executableLineLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ setExecutableLineText();
+ toplayout->addRow(tr("Executable:"), m_executableLineLabel);
QLabel *argumentsLabel = new QLabel(tr("Arguments:"), this);
m_argumentsLineEdit = new QLineEdit(m_rc->rawCommandLineArguments(), this);
@@ -527,13 +526,19 @@ void QbsRunConfigurationWidget::termToggled(bool on)
void QbsRunConfigurationWidget::targetInformationHasChanged()
{
m_ignoreChange = true;
- m_executableLineEdit->setText(m_rc->executable());
+ setExecutableLineText(m_rc->executable());
m_workingDirectoryEdit->setPath(m_rc->baseWorkingDirectory());
m_workingDirectoryEdit->setBaseFileName(m_rc->target()->project()->projectDirectory());
m_ignoreChange = false;
}
+void QbsRunConfigurationWidget::setExecutableLineText(const QString &text)
+{
+ const QString newText = text.isEmpty() ? tr("<unknown>") : text;
+ m_executableLineLabel->setText(newText);
+}
+
void QbsRunConfigurationWidget::workingDirectoryChanged(const QString &workingDirectory)
{
if (!m_ignoreChange)
diff --git a/src/plugins/qbsprojectmanager/qbsrunconfiguration.h b/src/plugins/qbsprojectmanager/qbsrunconfiguration.h
index 11be5a4edcd..b00d1cc89ed 100644
--- a/src/plugins/qbsprojectmanager/qbsrunconfiguration.h
+++ b/src/plugins/qbsprojectmanager/qbsrunconfiguration.h
@@ -157,11 +157,13 @@ private slots:
void targetInformationHasChanged();
private:
+ void setExecutableLineText(const QString &text = QString());
+
QbsRunConfiguration *m_rc;
bool m_ignoreChange;
QLabel *m_disabledIcon;
QLabel *m_disabledReason;
- QLineEdit *m_executableLineEdit;
+ QLabel *m_executableLineLabel;
Utils::PathChooser *m_workingDirectoryEdit;
QLineEdit *m_argumentsLineEdit;
QCheckBox *m_useTerminalCheck;
diff --git a/src/plugins/qmakeandroidsupport/androidpackageinstallationfactory.cpp b/src/plugins/qmakeandroidsupport/androidpackageinstallationfactory.cpp
index e4e2c50c5bf..48aa70ce895 100644
--- a/src/plugins/qmakeandroidsupport/androidpackageinstallationfactory.cpp
+++ b/src/plugins/qmakeandroidsupport/androidpackageinstallationfactory.cpp
@@ -99,7 +99,15 @@ BuildStep *AndroidPackageInstallationFactory::restore(BuildStepList *parent, con
bool AndroidPackageInstallationFactory::canClone(BuildStepList *parent, BuildStep *product) const
{
- return canCreate(parent, product->id());
+ if (parent->id() != ProjectExplorer::Constants::BUILDSTEPS_BUILD)
+ return false;
+ if (!Android::AndroidManager::supportsAndroid(parent->target()))
+ return false;
+ if (product->id() != AndroidPackageInstallationStep::Id)
+ return false;
+ if (parent->contains(AndroidPackageInstallationStep::Id))
+ return false;
+ return true;
}
BuildStep *AndroidPackageInstallationFactory::clone(BuildStepList *parent, BuildStep *product)
diff --git a/src/plugins/qmakeandroidsupport/androidqmakebuildconfigurationfactory.h b/src/plugins/qmakeandroidsupport/androidqmakebuildconfigurationfactory.h
index 247adf78c05..0b917e6c5af 100644
--- a/src/plugins/qmakeandroidsupport/androidqmakebuildconfigurationfactory.h
+++ b/src/plugins/qmakeandroidsupport/androidqmakebuildconfigurationfactory.h
@@ -53,7 +53,7 @@ public:
};
} // namespace Internal
-} // namespace QmakeProjectManager
+} // namespace QmakeAndroidSupport
#endif // ANDROIDQMAKEBUILDCONFIGURATIONFACTORY_H
diff --git a/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.cpp b/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.cpp
index dd4e13f07c8..b7e39bae844 100644
--- a/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.cpp
+++ b/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.cpp
@@ -29,6 +29,7 @@
****************************************************************************/
#include "createandroidmanifestwizard.h"
+#include "qmakeandroidrunconfiguration.h"
#include <android/androidconfigurations.h>
#include <android/androidmanager.h>
@@ -77,7 +78,7 @@ NoApplicationProFilePage::NoApplicationProFilePage(CreateAndroidManifestWizard *
//
// ChooseProFilePage
//
-ChooseProFilePage::ChooseProFilePage(CreateAndroidManifestWizard *wizard, const QList<QmakeProFileNode *> &nodes)
+ChooseProFilePage::ChooseProFilePage(CreateAndroidManifestWizard *wizard, const QList<QmakeProFileNode *> &nodes, const QmakeProFileNode *select)
: m_wizard(wizard)
{
QFormLayout *fl = new QFormLayout(this);
@@ -87,10 +88,13 @@ ChooseProFilePage::ChooseProFilePage(CreateAndroidManifestWizard *wizard, const
fl->addRow(label);
m_comboBox = new QComboBox(this);
- foreach (QmakeProFileNode *node, nodes)
+ foreach (QmakeProFileNode *node, nodes) {
m_comboBox->addItem(node->displayName(), QVariant::fromValue(static_cast<void *>(node))); // TODO something more?
+ if (node == select)
+ m_comboBox->setCurrentIndex(m_comboBox->count() - 1);
+ }
- nodeSelected(0);
+ nodeSelected(m_comboBox->currentIndex());
connect(m_comboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(nodeSelected(int)));
@@ -111,12 +115,14 @@ void ChooseProFilePage::nodeSelected(int index)
ChooseDirectoryPage::ChooseDirectoryPage(CreateAndroidManifestWizard *wizard)
: m_wizard(wizard), m_androidPackageSourceDir(0), m_complete(true)
{
- QString androidPackageDir = m_wizard->node()->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir);
+ m_layout = new QFormLayout(this);
+ m_label = new QLabel(this);
+ m_label->setWordWrap(true);
+ m_layout->addRow(m_label);
- QFormLayout *fl = new QFormLayout(this);
- QLabel *label = new QLabel(this);
- label->setWordWrap(true);
- fl->addRow(label);
+ m_androidPackageSourceDir = new PathChooser(this);
+ m_androidPackageSourceDir->setExpectedKind(PathChooser::Directory);
+ m_layout->addRow(tr("Android package source directory:"), m_androidPackageSourceDir);
m_sourceDirectoryWarning = new QLabel(this);
m_sourceDirectoryWarning->setVisible(false);
@@ -133,28 +139,7 @@ ChooseDirectoryPage::ChooseDirectoryPage(CreateAndroidManifestWizard *wizard)
hbox->addWidget(m_sourceDirectoryWarning);
hbox->setAlignment(m_warningIcon, Qt::AlignTop);
- fl->addRow(hbox);
-
- m_androidPackageSourceDir = new PathChooser(this);
- m_androidPackageSourceDir->setExpectedKind(PathChooser::Directory);
- fl->addRow(tr("Android package source directory:"), m_androidPackageSourceDir);
-
- if (androidPackageDir.isEmpty()) {
- label->setText(tr("Select the Android package source directory.\n\n"
- "The files in the Android package source directory are copied to the build directory's "
- "Android directory and the default files are overwritten."));
-
- m_androidPackageSourceDir->setPath(QFileInfo(m_wizard->node()->path()).absolutePath().append(QLatin1String("/android")));
- connect(m_androidPackageSourceDir, SIGNAL(changed(QString)),
- this, SLOT(checkPackageSourceDir()));
- } else {
- label->setText(tr("The Android template files will be created in the ANDROID_PACKAGE_SOURCE_DIR set in the .pro file."));
- m_androidPackageSourceDir->setPath(androidPackageDir);
- m_androidPackageSourceDir->setReadOnly(true);
- }
-
-
- m_wizard->setDirectory(m_androidPackageSourceDir->path());
+ m_layout->addRow(hbox);
connect(m_androidPackageSourceDir, SIGNAL(pathChanged(QString)),
m_wizard, SLOT(setDirectory(QString)));
@@ -164,8 +149,8 @@ ChooseDirectoryPage::ChooseDirectoryPage(CreateAndroidManifestWizard *wizard)
checkBox->setChecked(true);
connect(checkBox, &QCheckBox::toggled, wizard, &CreateAndroidManifestWizard::setCopyGradle);
checkBox->setText(tr("Copy the Gradle files to Android directory"));
- checkBox->setToolTip(tr("It is highly recommended if you are plannig to extend the Java part of your Qt application."));
- fl->addRow(checkBox);
+ checkBox->setToolTip(tr("It is highly recommended if you are planning to extend the Java part of your Qt application."));
+ m_layout->addRow(checkBox);
}
}
@@ -189,6 +174,27 @@ bool ChooseDirectoryPage::isComplete() const
return m_complete;
}
+void ChooseDirectoryPage::initializePage()
+{
+ QString androidPackageDir = m_wizard->node()->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir);
+ if (androidPackageDir.isEmpty()) {
+ m_label->setText(tr("Select the Android package source directory.\n\n"
+ "The files in the Android package source directory are copied to the build directory's "
+ "Android directory and the default files are overwritten."));
+
+ m_androidPackageSourceDir->setPath(QFileInfo(m_wizard->node()->path()).absolutePath().append(QLatin1String("/android")));
+ connect(m_androidPackageSourceDir, SIGNAL(changed(QString)),
+ this, SLOT(checkPackageSourceDir()));
+ } else {
+ m_label->setText(tr("The Android template files will be created in the ANDROID_PACKAGE_SOURCE_DIR set in the .pro file."));
+ m_androidPackageSourceDir->setPath(androidPackageDir);
+ m_androidPackageSourceDir->setReadOnly(true);
+ }
+
+
+ m_wizard->setDirectory(m_androidPackageSourceDir->path());
+}
+
//
// CreateAndroidManifestWizard
//
@@ -202,6 +208,11 @@ CreateAndroidManifestWizard::CreateAndroidManifestWizard(ProjectExplorer::Target
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
m_copyGradle = version && version->qtVersion() >= QtSupport::QtVersionNumber(5, 4, 0);
+ const QmakeProFileNode *currentRunNode = 0;
+ ProjectExplorer::RunConfiguration *rc = target->activeRunConfiguration();
+ if (auto qrc = qobject_cast<QmakeAndroidRunConfiguration *>(rc))
+ currentRunNode = project->rootQmakeProjectNode()->findProFileFor(qrc->proFilePath());
+
if (nodes.isEmpty()) {
// oh uhm can't create anything
addPage(new NoApplicationProFilePage(this));
@@ -209,7 +220,7 @@ CreateAndroidManifestWizard::CreateAndroidManifestWizard(ProjectExplorer::Target
setNode(nodes.first());
addPage(new ChooseDirectoryPage(this));
} else {
- addPage(new ChooseProFilePage(this, nodes));
+ addPage(new ChooseProFilePage(this, nodes, currentRunNode));
addPage(new ChooseDirectoryPage(this));
}
}
@@ -332,7 +343,7 @@ void CreateAndroidManifestWizard::createAndroidTemplateFiles()
if (m_node->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir).isEmpty()) {
// and now time for some magic
QString value = QLatin1String("$$PWD/")
- + QDir(m_target->project()->projectDirectory().toString()).relativeFilePath(m_directory);
+ + QDir(QFileInfo(m_node->path()).absolutePath()).relativeFilePath(m_directory);
bool result =
m_node->setProVariable(QLatin1String("ANDROID_PACKAGE_SOURCE_DIR"), QStringList(value));
@@ -347,5 +358,5 @@ void CreateAndroidManifestWizard::createAndroidTemplateFiles()
void CreateAndroidManifestWizard::accept()
{
createAndroidTemplateFiles();
- Utils::Wizard::accept();
+ Wizard::accept();
}
diff --git a/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.h b/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.h
index 960a4a21a2d..b1f5be694fe 100644
--- a/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.h
+++ b/src/plugins/qmakeandroidsupport/createandroidmanifestwizard.h
@@ -37,6 +37,7 @@
QT_BEGIN_NAMESPACE
class QComboBox;
class QLabel;
+class QFormLayout;
QT_END_NAMESPACE
namespace ProjectExplorer { class Target; }
@@ -60,7 +61,7 @@ class ChooseProFilePage : public QWizardPage
{
Q_OBJECT
public:
- ChooseProFilePage(CreateAndroidManifestWizard *wizard, const QList<QmakeProjectManager::QmakeProFileNode *> &nodes);
+ ChooseProFilePage(CreateAndroidManifestWizard *wizard, const QList<QmakeProjectManager::QmakeProFileNode *> &nodes, const QmakeProjectManager::QmakeProFileNode *select);
private slots:
void nodeSelected(int index);
private:
@@ -73,6 +74,7 @@ class ChooseDirectoryPage : public QWizardPage
Q_OBJECT
public:
ChooseDirectoryPage(CreateAndroidManifestWizard *wizard);
+ void initializePage();
protected:
bool isComplete() const;
private slots:
@@ -82,6 +84,8 @@ private:
Utils::PathChooser *m_androidPackageSourceDir;
QLabel *m_sourceDirectoryWarning;
QLabel *m_warningIcon;
+ QLabel *m_label;
+ QFormLayout *m_layout;
bool m_complete;
};
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.cpp b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.cpp
index f43937aa18e..dedef67ed40 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.cpp
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.cpp
@@ -31,6 +31,7 @@
#include "qmakeandroidbuildapkstep.h"
#include "qmakeandroidbuildapkwidget.h"
+#include "qmakeandroidrunconfiguration.h"
#include <android/androidconfigurations.h>
#include <android/androidconstants.h>
@@ -136,24 +137,21 @@ bool QmakeAndroidBuildApkStepFactory::canHandle(ProjectExplorer::Target *t) cons
QmakeAndroidBuildApkStep::QmakeAndroidBuildApkStep(ProjectExplorer::BuildStepList *bc)
- :Android::AndroidBuildApkStep(bc, ANDROID_BUILD_APK_ID)
+ :AndroidBuildApkStep(bc, ANDROID_BUILD_APK_ID)
{
ctor();
}
QString QmakeAndroidBuildApkStep::proFilePathForInputFile() const
{
- return m_proFilePathForInputFile;
-}
-
-void QmakeAndroidBuildApkStep::setProFilePathForInputFile(const QString &path)
-{
- m_proFilePathForInputFile = path;
+ ProjectExplorer::RunConfiguration *rc = target()->activeRunConfiguration();
+ if (auto *arc = qobject_cast<QmakeAndroidRunConfiguration *>(rc))
+ return arc->proFilePath();
+ return QString();
}
QmakeAndroidBuildApkStep::QmakeAndroidBuildApkStep(ProjectExplorer::BuildStepList *bc, QmakeAndroidBuildApkStep *other)
- : Android::AndroidBuildApkStep(bc, other),
- m_proFilePathForInputFile(other->m_proFilePathForInputFile)
+ : AndroidBuildApkStep(bc, other)
{
ctor();
}
@@ -162,7 +160,7 @@ Utils::FileName QmakeAndroidBuildApkStep::androidPackageSourceDir() const
{
QmakeProjectManager::QmakeProject *pro = static_cast<QmakeProjectManager::QmakeProject *>(project());
const QmakeProjectManager::QmakeProFileNode *node
- = pro->rootQmakeProjectNode()->findProFileFor(m_proFilePathForInputFile);
+ = pro->rootQmakeProjectNode()->findProFileFor(proFilePathForInputFile());
if (!node)
return Utils::FileName();
return Utils::FileName::fromString(node->singleVariableValue(QmakeProjectManager::AndroidPackageSourceDir));
@@ -170,8 +168,6 @@ Utils::FileName QmakeAndroidBuildApkStep::androidPackageSourceDir() const
void QmakeAndroidBuildApkStep::ctor()
{
- connect(project(), SIGNAL(proFilesEvaluated()),
- this, SLOT(updateInputFile()));
}
bool QmakeAndroidBuildApkStep::init()
@@ -179,7 +175,7 @@ bool QmakeAndroidBuildApkStep::init()
if (AndroidManager::checkForQt51Files(project()->projectDirectory()))
emit addOutput(tr("Found old folder \"android\" in source directory. Qt 5.2 does not use that folder by default."), ErrorOutput);
- if (!Android::AndroidBuildApkStep::init())
+ if (!AndroidBuildApkStep::init())
return false;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
@@ -205,11 +201,10 @@ bool QmakeAndroidBuildApkStep::init()
QString outputDir = bc->buildDirectory().appendPath(QLatin1String(Constants::ANDROID_BUILDDIRECTORY)).toString();
const auto *pro = static_cast<QmakeProjectManager::QmakeProject *>(project());
- const QmakeProjectManager::QmakeProFileNode *node = pro->rootQmakeProjectNode()->findProFileFor(m_proFilePathForInputFile);
- if (!node) { // should never happen
- emit addOutput(tr("Internal Error: Could not find .pro file."), BuildStep::ErrorMessageOutput);
- return false;
- }
+ const QmakeProjectManager::QmakeProFileNode *node = pro->rootQmakeProjectNode()->findProFileFor(proFilePathForInputFile());
+ m_skipBuilding = !node;
+ if (m_skipBuilding)
+ return true;
QString inputFile = node->singleVariableValue(QmakeProjectManager::AndroidDeploySettingsFile);
if (inputFile.isEmpty()) { // should never happen
@@ -270,6 +265,17 @@ bool QmakeAndroidBuildApkStep::init()
return true;
}
+void QmakeAndroidBuildApkStep::run(QFutureInterface<bool> &fi)
+{
+ if (m_skipBuilding) {
+ emit addOutput(tr("No application .pro file found, not building an APK."), BuildStep::ErrorMessageOutput);
+ fi.reportResult(true);
+ emit finished();
+ return;
+ }
+ AndroidBuildApkStep::run(fi);
+}
+
void QmakeAndroidBuildApkStep::setupProcessParameters(ProjectExplorer::ProcessParameters *pp,
ProjectExplorer::BuildConfiguration *bc,
const QStringList &arguments,
@@ -299,32 +305,14 @@ ProjectExplorer::BuildStepConfigWidget *QmakeAndroidBuildApkStep::createConfigWi
bool QmakeAndroidBuildApkStep::fromMap(const QVariantMap &map)
{
- m_proFilePathForInputFile = map.value(ProFilePathForInputFile).toString();
- return Android::AndroidBuildApkStep::fromMap(map);
+ return AndroidBuildApkStep::fromMap(map);
}
QVariantMap QmakeAndroidBuildApkStep::toMap() const
{
- QVariantMap map = Android::AndroidBuildApkStep::toMap();
- map.insert(ProFilePathForInputFile, m_proFilePathForInputFile);
+ QVariantMap map = AndroidBuildApkStep::toMap();
return map;
}
-void QmakeAndroidBuildApkStep::updateInputFile()
-{
- QmakeProject *pro = static_cast<QmakeProject *>(project());
- QList<QmakeProFileNode *> nodes = pro->applicationProFiles();
-
- const QmakeProFileNode *node = pro->rootQmakeProjectNode()->findProFileFor(m_proFilePathForInputFile);
- if (!nodes.contains(const_cast<QmakeProFileNode *>(node))) {
- if (!nodes.isEmpty())
- m_proFilePathForInputFile = nodes.first()->path();
- else
- m_proFilePathForInputFile.clear();
- }
-
- emit inputFileChanged();
-}
-
} // namespace Internal
-} // namespace QmakeProjectManager
+} // namespace QmakeAndroidSupport
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.h b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.h
index 457a81c3936..a188b7c214e 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.h
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkstep.h
@@ -69,6 +69,7 @@ public:
QString proFilePathForInputFile() const;
void setProFilePathForInputFile(const QString &path);
+
protected:
friend class QmakeAndroidBuildApkStepFactory;
QmakeAndroidBuildApkStep(ProjectExplorer::BuildStepList *bc,
@@ -79,25 +80,19 @@ protected:
protected:
void ctor();
bool init();
+ void run(QFutureInterface<bool> &fi);
void processStarted();
ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
bool fromMap(const QVariantMap &map);
QVariantMap toMap() const;
-signals:
- // also on purpose emitted if the possible values of this changed
- void inputFileChanged();
-
-private slots:
- void updateInputFile();
-
private:
void setupProcessParameters(ProjectExplorer::ProcessParameters *pp,
ProjectExplorer::BuildConfiguration *bc,
const QStringList &arguments, const QString &command);
- QString m_proFilePathForInputFile;
QString m_command;
QString m_argumentsPasswordConcealed;
+ bool m_skipBuilding;
};
} // namespace Internal
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.cpp b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.cpp
index 62859731eca..186f1918d62 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.cpp
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.cpp
@@ -39,6 +39,7 @@
#include <qmakeprojectmanager/qmakeproject.h>
#include <QFileDialog>
+#include <QLabel>
using QmakeProjectManager::QmakeProject;
using QmakeProjectManager::QmakeProFileNode;
@@ -86,13 +87,6 @@ QmakeAndroidBuildApkWidget::QmakeAndroidBuildApkWidget(QmakeAndroidBuildApkStep
m_extraLibraryListModel = new AndroidExtraLibraryListModel(static_cast<QmakeProject *>(m_step->project()), this);
m_ui->androidExtraLibsListView->setModel(m_extraLibraryListModel);
- updateInputFileUi();
- connect(m_step, SIGNAL(inputFileChanged()),
- SLOT(updateInputFileUi()));
-
- connect(m_ui->inputFileComboBox, SIGNAL(currentIndexChanged(int)),
- SLOT(inputFileComboBoxIndexChanged()));
-
connect(m_ui->createAndroidTemplatesButton, SIGNAL(clicked()),
SLOT(createAndroidTemplatesButton()));
@@ -116,40 +110,6 @@ QmakeAndroidBuildApkWidget::~QmakeAndroidBuildApkWidget()
delete m_ui;
}
-void QmakeAndroidBuildApkWidget::updateInputFileUi()
-{
- QmakeProject *project
- = static_cast<QmakeProject *>(m_step->project());
- QList<QmakeProFileNode *> 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 (QmakeProFileNode *node, nodes)
- m_ui->inputFileComboBox->addItem(node->displayName(), node->path());
-
- int index = m_ui->inputFileComboBox->findData(m_step->proFilePathForInputFile());
- m_ui->inputFileComboBox->setCurrentIndex(index);
- m_ignoreChange = false;
- }
-}
-
-void QmakeAndroidBuildApkWidget::inputFileComboBoxIndexChanged()
-{
- if (m_ignoreChange)
- return;
-
- QString proFilePath = m_ui->inputFileComboBox->itemData(m_ui->inputFileComboBox->currentIndex()).toString();
- m_step->setProFilePathForInputFile(proFilePath);
-}
-
void QmakeAndroidBuildApkWidget::createAndroidTemplatesButton()
{
CreateAndroidManifestWizard wizard(m_step->target());
@@ -189,6 +149,6 @@ QString QmakeAndroidBuildApkWidget::displayName() const
}
} // namespace Internal
-} // namespace QmakeProjectManager
+} // namespace QmakeAndroidSupport
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.h b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.h
index 5c8cf7eab21..b2394183636 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.h
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.h
@@ -61,8 +61,6 @@ public:
~QmakeAndroidBuildApkWidget();
private slots:
- void updateInputFileUi();
- void inputFileComboBoxIndexChanged();
void createAndroidTemplatesButton();
void addAndroidExtraLib();
void removeAndroidExtraLib();
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.ui b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.ui
index 48c6d3a5cff..2b5322c5fbf 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.ui
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidbuildapkwidget.ui
@@ -50,20 +50,6 @@
</item>
</layout>
</item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout_2">
- <item>
- <widget class="QLabel" name="inputFileLabel">
- <property name="text">
- <string>Input file for androiddeployqt:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QComboBox" name="inputFileComboBox"/>
- </item>
- </layout>
- </item>
</layout>
</widget>
</item>
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidrunconfiguration.cpp b/src/plugins/qmakeandroidsupport/qmakeandroidrunconfiguration.cpp
index 029e3e51b80..7a391b269e5 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidrunconfiguration.cpp
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidrunconfiguration.cpp
@@ -37,8 +37,11 @@
#include <qmakeprojectmanager/qmakeproject.h>
#include <qmakeprojectmanager/qmakenodes.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
+#include <QFileInfo>
+
namespace {
QLatin1String PRO_FILE_KEY("QMakeProjectManager.QmakeAndroidRunConfiguration.ProFile");
}
@@ -120,7 +123,7 @@ QString QmakeAndroidRunConfiguration::disabledReason() const
{
if (m_parseInProgress)
return tr("The .pro file \"%1\" is currently being parsed.")
- .arg(QFileInfo(m_proFilePath).fileName());
+ .arg(Utils::FileName::fromString(m_proFilePath).fileName());
if (!m_parseSuccess)
return static_cast<QmakeProject *>(target()->project())->disabledReasonForRunConfiguration(m_proFilePath);
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidrunfactories.cpp b/src/plugins/qmakeandroidsupport/qmakeandroidrunfactories.cpp
index 71b1323a25b..21d732c6234 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidrunfactories.cpp
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidrunfactories.cpp
@@ -58,7 +58,7 @@ static QString pathFromId(const Core::Id id)
}
QmakeAndroidRunConfigurationFactory::QmakeAndroidRunConfigurationFactory(QObject *parent)
- : ProjectExplorer::IRunConfigurationFactory(parent)
+ : IRunConfigurationFactory(parent)
{
}
@@ -104,7 +104,7 @@ QList<Core::Id> QmakeAndroidRunConfigurationFactory::availableCreationIds(Target
RunConfiguration *QmakeAndroidRunConfigurationFactory::doCreate(Target *parent, Core::Id id)
{
if (parent->project()->rootProjectNode())
- return new QmakeAndroidRunConfiguration(parent, id, parent->project()->rootProjectNode()->path());
+ return new QmakeAndroidRunConfiguration(parent, id, pathFromId(id));
return new QmakeAndroidRunConfiguration(parent, id);
}
@@ -113,7 +113,7 @@ RunConfiguration *QmakeAndroidRunConfigurationFactory::doRestore(Target *parent,
{
Core::Id id = ProjectExplorer::idFromMap(map);
if (parent->project()->rootProjectNode())
- return new QmakeAndroidRunConfiguration(parent, id, parent->project()->rootProjectNode()->path());
+ return new QmakeAndroidRunConfiguration(parent, id);
return new QmakeAndroidRunConfiguration(parent, id);
}
@@ -136,10 +136,10 @@ bool QmakeAndroidRunConfigurationFactory::canHandle(Target *t) const
#ifdef Q_CC_GCC
# warning FIX ME !!!
#endif
-QList<RunConfiguration *> QmakeAndroidRunConfigurationFactory::runConfigurationsForNode(Target *t, ProjectExplorer::Node *n)
+QList<RunConfiguration *> QmakeAndroidRunConfigurationFactory::runConfigurationsForNode(Target *t, Node *n)
{
- QList<ProjectExplorer::RunConfiguration *> result;
- foreach (ProjectExplorer::RunConfiguration *rc, t->runConfigurations())
+ QList<RunConfiguration *> result;
+ foreach (RunConfiguration *rc, t->runConfigurations())
if (QmakeAndroidRunConfiguration *qt4c = qobject_cast<QmakeAndroidRunConfiguration *>(rc))
if (qt4c->proFilePath() == n->path())
result << rc;
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidsupport.cpp b/src/plugins/qmakeandroidsupport/qmakeandroidsupport.cpp
index 13ab2537ad2..200a293349c 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidsupport.cpp
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidsupport.cpp
@@ -112,18 +112,18 @@ Utils::FileName QmakeAndroidSupport::androiddeployqtPath(ProjectExplorer::Target
Utils::FileName QmakeAndroidSupport::androiddeployJsonPath(ProjectExplorer::Target *target) const
{
- const auto *pro = static_cast<QmakeProjectManager::QmakeProject *>(target->project());
+ const auto *pro = static_cast<QmakeProject *>(target->project());
QmakeAndroidBuildApkStep *buildApkStep
= Android::AndroidGlobal::buildStep<QmakeAndroidBuildApkStep>(target->activeBuildConfiguration());
if (!buildApkStep) // should never happen
return Utils::FileName();
- const QmakeProjectManager::QmakeProFileNode *node = pro->rootQmakeProjectNode()->findProFileFor(buildApkStep->proFilePathForInputFile());
+ const QmakeProFileNode *node = pro->rootQmakeProjectNode()->findProFileFor(buildApkStep->proFilePathForInputFile());
if (!node) // should never happen
return Utils::FileName();
- QString inputFile = node->singleVariableValue(QmakeProjectManager::AndroidDeploySettingsFile);
+ QString inputFile = node->singleVariableValue(AndroidDeploySettingsFile);
if (inputFile.isEmpty()) // should never happen
return Utils::FileName();
@@ -154,4 +154,4 @@ void QmakeAndroidSupport::resetBuild(const ProjectExplorer::Target *target)
}
} // namespace Internal
-} // namespace QmakeProjectManager
+} // namespace QmakeAndroidSupport
diff --git a/src/plugins/qmakeandroidsupport/qmakeandroidsupport.h b/src/plugins/qmakeandroidsupport/qmakeandroidsupport.h
index e09c689f513..e274dd4a808 100644
--- a/src/plugins/qmakeandroidsupport/qmakeandroidsupport.h
+++ b/src/plugins/qmakeandroidsupport/qmakeandroidsupport.h
@@ -51,6 +51,6 @@ public:
};
} // namespace Internal
-} // namespace QmakeProjectManager
+} // namespace QmakeAndroidSupport
#endif // QMAKEANDROIDSUPPORT_H
diff --git a/src/plugins/qmakeprojectmanager/customwidgetwizard/plugingenerator.cpp b/src/plugins/qmakeprojectmanager/customwidgetwizard/plugingenerator.cpp
index 74f470139f5..3f36cf89e55 100644
--- a/src/plugins/qmakeprojectmanager/customwidgetwizard/plugingenerator.cpp
+++ b/src/plugins/qmakeprojectmanager/customwidgetwizard/plugingenerator.cpp
@@ -132,7 +132,7 @@ QList<Core::GeneratedFile> PluginGenerator::generatePlugin(const GenerationPara
QString iconResource;
if (!wo.iconFile.isEmpty()) {
iconResource = QLatin1String("QLatin1String(\":/");
- iconResource += QFileInfo(wo.iconFile).fileName();
+ iconResource += Utils::FileName::fromString(wo.iconFile).fileName();
iconResource += QLatin1String("\")");
}
sm.insert(QLatin1String("WIDGET_ICON"),iconResource);
diff --git a/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.cpp b/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.cpp
index 15bbb27bd78..19cd8485593 100644
--- a/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.cpp
+++ b/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.cpp
@@ -41,7 +41,9 @@
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtoutputformatter.h>
#include <qtsupport/qtsupportconstants.h>
+
#include <utils/detailswidget.h>
+#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <utils/persistentsettings.h>
@@ -121,7 +123,7 @@ QString DesktopQmakeRunConfiguration::disabledReason() const
{
if (m_parseInProgress)
return tr("The .pro file \"%1\" is currently being parsed.")
- .arg(QFileInfo(m_proFilePath).fileName());
+ .arg(FileName::fromString(m_proFilePath).fileName());
if (!m_parseSuccess)
return static_cast<QmakeProject *>(target()->project())->disabledReasonForRunConfiguration(m_proFilePath);
@@ -213,9 +215,9 @@ DesktopQmakeRunConfigurationWidget::DesktopQmakeRunConfigurationWidget(DesktopQm
toplayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
toplayout->setMargin(0);
- m_executableLineEdit = new QLineEdit(m_qmakeRunConfiguration->executable(), this);
- m_executableLineEdit->setEnabled(false);
- toplayout->addRow(tr("Executable:"), m_executableLineEdit);
+ m_executableLineLabel = new QLabel(m_qmakeRunConfiguration->executable(), this);
+ m_executableLineLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ toplayout->addRow(tr("Executable:"), m_executableLineLabel);
QLabel *argumentsLabel = new QLabel(tr("Arguments:"), this);
m_argumentsLineEdit = new QLineEdit(qmakeRunConfiguration->rawCommandLineArguments(), this);
@@ -393,7 +395,7 @@ void DesktopQmakeRunConfigurationWidget::usingDyldImageSuffixChanged(bool state)
void DesktopQmakeRunConfigurationWidget::effectiveTargetInformationChanged()
{
if (m_isShown) {
- m_executableLineEdit->setText(QDir::toNativeSeparators(m_qmakeRunConfiguration->executable()));
+ m_executableLineLabel->setText(QDir::toNativeSeparators(m_qmakeRunConfiguration->executable()));
m_ignoreChange = true;
m_workingDirectoryEdit->setPath(QDir::toNativeSeparators(m_qmakeRunConfiguration->baseWorkingDirectory()));
m_ignoreChange = false;
diff --git a/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.h b/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.h
index 0289cc91eab..6daba27162e 100644
--- a/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.h
+++ b/src/plugins/qmakeprojectmanager/desktopqmakerunconfiguration.h
@@ -171,7 +171,7 @@ private:
bool m_ignoreChange;
QLabel *m_disabledIcon;
QLabel *m_disabledReason;
- QLineEdit *m_executableLineEdit;
+ QLabel *m_executableLineLabel;
Utils::PathChooser *m_workingDirectoryEdit;
QLineEdit *m_argumentsLineEdit;
QCheckBox *m_useTerminalCheck;
diff --git a/src/plugins/qmakeprojectmanager/externaleditors.cpp b/src/plugins/qmakeprojectmanager/externaleditors.cpp
index fd1e468aa06..c510c96d56a 100644
--- a/src/plugins/qmakeprojectmanager/externaleditors.cpp
+++ b/src/plugins/qmakeprojectmanager/externaleditors.cpp
@@ -47,6 +47,8 @@
#include <QTcpSocket>
#include <QTcpServer>
+using namespace ProjectExplorer;
+
enum { debug = 0 };
namespace QmakeProjectManager {
@@ -130,8 +132,8 @@ bool ExternalQtEditor::getEditorLaunchData(const QString &fileName,
QString *errorMessage) const
{
// Get the binary either from the current Qt version of the project or Path
- if (ProjectExplorer::Project *project = ProjectExplorer::SessionManager::projectForFile(fileName)) {
- if (const ProjectExplorer::Target *target = project->activeTarget()) {
+ if (Project *project = SessionManager::projectForFile(fileName)) {
+ if (const Target *target = project->activeTarget()) {
if (const QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(target->kit())) {
data->binary = (qtVersion->*commandAccessor)();
data->workingDirectory = project->projectDirectory().toString();
diff --git a/src/plugins/qmakeprojectmanager/findqmakeprofiles.cpp b/src/plugins/qmakeprojectmanager/findqmakeprofiles.cpp
index 7c74233b290..0e6c75bf698 100644
--- a/src/plugins/qmakeprojectmanager/findqmakeprofiles.cpp
+++ b/src/plugins/qmakeprojectmanager/findqmakeprofiles.cpp
@@ -43,6 +43,6 @@ QList<QmakeProFileNode *> FindQmakeProFiles::operator()(ProjectExplorer::Project
void FindQmakeProFiles::visitProjectNode(ProjectExplorer::ProjectNode *projectNode)
{
- if (QmakeProFileNode *pro = qobject_cast<QmakeProFileNode *>(projectNode))
+ if (QmakeProFileNode *pro = dynamic_cast<QmakeProFileNode *>(projectNode))
m_proFiles.append(pro);
}
diff --git a/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp b/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp
index 4260211e660..ef7c14bdfe6 100644
--- a/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp
+++ b/src/plugins/qmakeprojectmanager/librarydetailscontroller.cpp
@@ -888,7 +888,7 @@ bool PackageLibraryDetailsController::isLinkPackageGenerated() const
if (!project)
return false;
- const QmakeProFileNode *rootProject = qobject_cast<const QmakeProFileNode *>(project->rootProjectNode());
+ const QmakeProFileNode *rootProject = dynamic_cast<const QmakeProFileNode *>(project->rootProjectNode());
if (!rootProject)
return false;
diff --git a/src/plugins/qmakeprojectmanager/profileeditor.cpp b/src/plugins/qmakeprojectmanager/profileeditor.cpp
index 71af8696a1c..f83994aeaad 100644
--- a/src/plugins/qmakeprojectmanager/profileeditor.cpp
+++ b/src/plugins/qmakeprojectmanager/profileeditor.cpp
@@ -137,7 +137,7 @@ ProFileEditorWidget::Link ProFileEditorWidget::findLinkAt(const QTextCursor &cur
}
}
- QDir dir(QFileInfo(textDocument()->filePath()).absolutePath());
+ QDir dir(textDocument()->filePath().toFileInfo().absolutePath());
QString fileName = dir.filePath(buffer);
QFileInfo fi(fileName);
if (fi.exists()) {
@@ -185,14 +185,12 @@ ProFileDocument::ProFileDocument()
QString ProFileDocument::defaultPath() const
{
- QFileInfo fi(filePath());
- return fi.absolutePath();
+ return filePath().toFileInfo().absolutePath();
}
QString ProFileDocument::suggestedFileName() const
{
- QFileInfo fi(filePath());
- return fi.fileName();
+ return filePath().fileName();
}
//
diff --git a/src/plugins/qmakeprojectmanager/qmakenodes.cpp b/src/plugins/qmakeprojectmanager/qmakenodes.cpp
index 737a6c2202d..442b0765ae6 100644
--- a/src/plugins/qmakeprojectmanager/qmakenodes.cpp
+++ b/src/plugins/qmakeprojectmanager/qmakenodes.cpp
@@ -49,6 +49,7 @@
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
+#include <projectexplorer/projecttree.h>
#include <qtsupport/profilereader.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/uicodemodelsupport.h>
@@ -60,6 +61,7 @@
#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
+#include <utils/qtcprocess.h>
#include <utils/stringutils.h>
#include <utils/theme/theme.h>
#include <proparser/prowriter.h>
@@ -75,6 +77,7 @@
#include <utils/QtConcurrentTools>
using namespace Core;
+using namespace ProjectExplorer;
using namespace Utils;
// Static cached data in struct QmakeNodeStaticData providing information and icons
@@ -82,41 +85,35 @@ using namespace Utils;
// to make sure the icons do not outlive QApplication, triggering warnings on X11.
struct FileTypeDataStorage {
- ProjectExplorer::FileType type;
+ FileType type;
const char *typeName;
const char *icon;
Theme::ImageFile themeImage;
};
static const FileTypeDataStorage fileTypeDataStorage[] = {
- { ProjectExplorer::HeaderType,
- QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Headers"),
+ { HeaderType, QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Headers"),
":/qmakeprojectmanager/images/headers.png", Theme::ProjectExplorerHeader },
- { ProjectExplorer::SourceType,
- QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Sources"),
+ { SourceType, QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Sources"),
":/qmakeprojectmanager/images/sources.png", Theme::ProjectExplorerSource },
- { ProjectExplorer::FormType,
- QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Forms"),
+ { FormType, QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Forms"),
":/qtsupport/images/forms.png", Theme::ProjectExplorerForm },
- { ProjectExplorer::ResourceType,
- QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Resources"),
+ { ResourceType, QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Resources"),
":/qtsupport/images/qt_qrc.png", Theme::ProjectExplorerResource },
- { ProjectExplorer::QMLType,
- QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "QML"),
+ { QMLType, QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "QML"),
":/qtsupport/images/qml.png", Theme::ProjectExplorerQML },
- { ProjectExplorer::UnknownFileType,
- QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Other files"),
+ { UnknownFileType, QT_TRANSLATE_NOOP("QmakeProjectManager::QmakePriFileNode", "Other files"),
":/qmakeprojectmanager/images/unknown.png", Theme::ProjectExplorerOtherFiles }
};
class SortByPath
{
public:
- bool operator()(ProjectExplorer::Node *a, ProjectExplorer::Node *b)
+ bool operator()(Node *a, Node *b)
{ return operator()(a->path(), b->path()); }
- bool operator()(ProjectExplorer::Node *a, const QString &b)
+ bool operator()(Node *a, const QString &b)
{ return operator()(a->path(), b); }
- bool operator()(const QString &a, ProjectExplorer::Node *b)
+ bool operator()(const QString &a, Node *b)
{ return operator()(a, b->path()); }
bool operator()(const QString &a, const QString &b)
{ return a < b; }
@@ -126,12 +123,12 @@ class QmakeNodeStaticData {
public:
class FileTypeData {
public:
- FileTypeData(ProjectExplorer::FileType t = ProjectExplorer::UnknownFileType,
+ FileTypeData(FileType t = UnknownFileType,
const QString &tN = QString(),
const QIcon &i = QIcon()) :
type(t), typeName(tN), icon(i) { }
- ProjectExplorer::FileType type;
+ FileType type;
QString typeName;
QIcon icon;
};
@@ -163,7 +160,7 @@ QmakeNodeStaticData::QmakeNodeStaticData()
overlayIcon, desiredSize);
QIcon folderIcon;
folderIcon.addPixmap(folderPixmap);
- const QString desc = QmakeProjectManager::QmakePriFileNode::tr(fileTypeDataStorage[i].typeName);
+ const QString desc = QCoreApplication::translate("QmakeProjectManager::QmakePriFileNode", fileTypeDataStorage[i].typeName);
fileTypeData.push_back(QmakeNodeStaticData::FileTypeData(fileTypeDataStorage[i].type,
desc, folderIcon));
}
@@ -211,8 +208,8 @@ class PriFileEvalResult
{
public:
QStringList folders;
- QSet<Utils::FileName> recursiveEnumerateFiles;
- QMap<FileType, QSet<Utils::FileName> > foundFiles;
+ QSet<FileName> recursiveEnumerateFiles;
+ QMap<FileType, QSet<FileName> > foundFiles;
};
class EvalResult
@@ -231,7 +228,6 @@ public:
QStringList newProjectFilesCumlative;
ProFile *fileForCurrentProjectCumlative; // probably only used in parser thread
TargetInformation targetInformation;
- QString resolvedMkspecPath;
InstallsList installsList;
QHash<QmakeVariable, QStringList> newVarValues;
bool isDeployable;
@@ -240,12 +236,13 @@ public:
};
}
}
+
QmakePriFile::QmakePriFile(QmakeProjectManager::QmakePriFileNode *qmakePriFile)
- : IDocument(qmakePriFile), m_priFile(qmakePriFile)
+ : IDocument(0), m_priFile(qmakePriFile)
{
setId("Qmake.PriFile");
setMimeType(QLatin1String(QmakeProjectManager::Constants::PROFILE_MIMETYPE));
- setFilePath(m_priFile->path());
+ setFilePath(FileName::fromString(m_priFile->path()));
}
bool QmakePriFile::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -319,6 +316,7 @@ QmakePriFileNode::QmakePriFileNode(QmakeProject *project, QmakeProFileNode *qmak
QmakePriFileNode::~QmakePriFileNode()
{
watchFolders(QSet<QString>());
+ delete m_qmakePriFile;
}
void QmakePriFileNode::scheduleUpdate()
@@ -333,7 +331,7 @@ struct InternalNode
QList<InternalNode *> virtualfolders;
QMap<QString, InternalNode *> subnodes;
QStringList files;
- ProjectExplorer::FileType type;
+ FileType type;
int priority;
QString displayName;
QString typeName;
@@ -342,7 +340,7 @@ struct InternalNode
InternalNode()
{
- type = ProjectExplorer::UnknownFileType;
+ type = UnknownFileType;
priority = 0;
}
@@ -370,12 +368,12 @@ struct InternalNode
// ...
// and afterwards calls compress() which merges directory nodes with single children, i.e. to
// * /absolute/path
- void create(const QString &projectDir, const QSet<Utils::FileName> &newFilePaths, ProjectExplorer::FileType type)
+ void create(const QString &projectDir, const QSet<FileName> &newFilePaths, FileType type)
{
static const QChar separator = QLatin1Char('/');
- const Utils::FileName projectDirFileName = Utils::FileName::fromString(projectDir);
- foreach (const Utils::FileName &file, newFilePaths) {
- Utils::FileName fileWithoutPrefix;
+ const FileName projectDirFileName = FileName::fromString(projectDir);
+ foreach (const FileName &file, newFilePaths) {
+ FileName fileWithoutPrefix;
bool isRelative;
if (file.isChildOf(projectDirFileName)) {
isRelative = true;
@@ -385,7 +383,7 @@ struct InternalNode
fileWithoutPrefix = file;
}
QStringList parts = fileWithoutPrefix.toString().split(separator, QString::SkipEmptyParts);
- if (!Utils::HostOsInfo::isWindowsHost() && !isRelative && parts.count() > 0)
+ if (!HostOsInfo::isWindowsHost() && !isRelative && parts.count() > 0)
parts[0].prepend(separator);
QStringListIterator it(parts);
InternalNode *currentNode = this;
@@ -451,9 +449,9 @@ struct InternalNode
}
// Makes the projectNode's subtree below the given folder match this internal node's subtree
- void updateSubFolders(ProjectExplorer::FolderNode *folder)
+ void updateSubFolders(FolderNode *folder)
{
- if (type == ProjectExplorer::ResourceType)
+ if (type == ResourceType)
updateResourceFiles(folder);
else
updateFiles(folder, type);
@@ -461,7 +459,7 @@ struct InternalNode
// updateFolders
QMultiMap<QString, FolderNode *> existingFolderNodes;
foreach (FolderNode *node, folder->subFolderNodes())
- if (node->nodeType() != ProjectNodeType && !qobject_cast<ResourceEditor::ResourceTopLevelNode *>(node))
+ if (node->nodeType() != ProjectNodeType && !dynamic_cast<ResourceEditor::ResourceTopLevelNode *>(node))
existingFolderNodes.insert(node->path(), node);
QList<FolderNode *> foldersToRemove;
@@ -479,9 +477,8 @@ struct InternalNode
QMultiMap<QString, FolderNode *>::const_iterator oldit
= existingFolderNodes.constFind(path);
while (oldit != existingFolderNodes.constEnd() && oldit.key() == path) {
- if (oldit.value()->nodeType() == ProjectExplorer::VirtualFolderNodeType) {
- ProjectExplorer::VirtualFolderNode *vfn
- = qobject_cast<ProjectExplorer::VirtualFolderNode *>(oldit.value());
+ if (oldit.value()->nodeType() == VirtualFolderNodeType) {
+ VirtualFolderNode *vfn = dynamic_cast<VirtualFolderNode *>(oldit.value());
if (vfn->priority() == (*it)->priority) {
found = true;
break;
@@ -509,7 +506,7 @@ struct InternalNode
QMultiMap<QString, FolderNode *>::const_iterator oldit
= existingFolderNodes.constFind(path);
while (oldit != existingFolderNodes.constEnd() && oldit.key() == path) {
- if (oldit.value()->nodeType() == ProjectExplorer::FolderNodeType) {
+ if (oldit.value()->nodeType() == FolderNodeType) {
found = true;
break;
}
@@ -564,7 +561,7 @@ struct InternalNode
QList<FileNode *> nodesToAdd;
foreach (const QString &file, filesToAdd)
- nodesToAdd << new ProjectExplorer::FileNode(file, type, false);
+ nodesToAdd << new FileNode(file, type, false);
folder->removeFileNodes(filesToRemove);
folder->addFileNodes(nodesToAdd);
@@ -573,13 +570,13 @@ struct InternalNode
// Makes the folder's files match this internal node's file list
void updateResourceFiles(FolderNode *folder)
{
- QList<ProjectExplorer::FolderNode *> existingResourceNodes; // for resource special handling
+ QList<FolderNode *> existingResourceNodes; // for resource special handling
foreach (FolderNode *folderNode, folder->subFolderNodes()) {
- if (ResourceEditor::ResourceTopLevelNode *rn = qobject_cast<ResourceEditor::ResourceTopLevelNode *>(folderNode))
+ if (ResourceEditor::ResourceTopLevelNode *rn = dynamic_cast<ResourceEditor::ResourceTopLevelNode *>(folderNode))
existingResourceNodes << rn;
}
- QList<ProjectExplorer::FolderNode *> resourcesToRemove;
+ QList<FolderNode *> resourcesToRemove;
QStringList resourcesToAdd;
SortByPath sortByPath;
@@ -598,7 +595,7 @@ struct InternalNode
folder->addFolderNodes(nodesToAdd);
foreach (FolderNode *fn, nodesToAdd)
- qobject_cast<ResourceEditor::ResourceTopLevelNode *>(fn)->update();
+ dynamic_cast<ResourceEditor::ResourceTopLevelNode *>(fn)->update();
}
};
}
@@ -627,9 +624,9 @@ QStringList QmakePriFileNode::fullVPaths(const QStringList &baseVPaths, QtSuppor
return vPaths;
}
-QSet<Utils::FileName> QmakePriFileNode::recursiveEnumerate(const QString &folder)
+QSet<FileName> QmakePriFileNode::recursiveEnumerate(const QString &folder)
{
- QSet<Utils::FileName> result;
+ QSet<FileName> result;
QFileInfo fi(folder);
if (fi.isDir()) {
QDir dir(folder);
@@ -639,10 +636,10 @@ QSet<Utils::FileName> QmakePriFileNode::recursiveEnumerate(const QString &folder
if (file.isDir() && !file.isSymLink())
result += recursiveEnumerate(file.absoluteFilePath());
else if (!Core::EditorManager::isAutoSaveFile(file.fileName()))
- result += Utils::FileName(file);
+ result += FileName(file);
}
} else if (fi.exists()) {
- result << Utils::FileName(fi);
+ result << FileName(fi);
}
return result;
}
@@ -682,7 +679,7 @@ PriFileEvalResult QmakePriFileNode::extractValues(const EvalInput &input, ProFil
++it;
} else {
// move files directly to recursiveEnumerateFiles
- result.recursiveEnumerateFiles << Utils::FileName::fromString(*it);
+ result.recursiveEnumerateFiles << FileName::fromString(*it);
it = result.folders.erase(it);
}
} else {
@@ -700,14 +697,14 @@ PriFileEvalResult QmakePriFileNode::extractValues(const EvalInput &input, ProFil
for (int i = 0; i < fileTypes.size(); ++i) {
FileType type = fileTypes.at(i).type;
const QList<VariableAndVPathInformation> &qmakeVariables = variableAndVPathInformation.at(i);
- QSet<Utils::FileName> newFilePaths;
+ QSet<FileName> newFilePaths;
foreach (const VariableAndVPathInformation &qmakeVariable, qmakeVariables) {
if (includeFileExact) {
QStringList tmp = input.readerExact->absoluteFileValues(qmakeVariable.variable, input.projectDir, qmakeVariable.vPathsExact, includeFileExact);
foreach (const QString &t, tmp) {
tmpFi.setFile(t);
if (tmpFi.isFile())
- newFilePaths += Utils::FileName::fromString(t);
+ newFilePaths += FileName::fromString(t);
}
}
if (includeFileCumlative) {
@@ -715,7 +712,7 @@ PriFileEvalResult QmakePriFileNode::extractValues(const EvalInput &input, ProFil
foreach (const QString &t, tmp) {
tmpFi.setFile(t);
if (tmpFi.isFile())
- newFilePaths += Utils::FileName::fromString(t);
+ newFilePaths += FileName::fromString(t);
}
}
}
@@ -727,7 +724,7 @@ PriFileEvalResult QmakePriFileNode::extractValues(const EvalInput &input, ProFil
for (int i = 0; i < fileTypes.size(); ++i) {
FileType type = fileTypes.at(i).type;
- QSet<Utils::FileName> newFilePaths = filterFilesProVariables(type, result.foundFiles[type]);
+ QSet<FileName> newFilePaths = filterFilesProVariables(type, result.foundFiles[type]);
newFilePaths += filterFilesRecursiveEnumerata(type, result.recursiveEnumerateFiles);
result.foundFiles[type] = newFilePaths;
}
@@ -740,7 +737,7 @@ void QmakePriFileNode::update(const Internal::PriFileEvalResult &result)
{
// add project file node
if (m_fileNodes.isEmpty())
- addFileNodes(QList<FileNode *>() << new ProjectExplorer::FileNode(m_projectFilePath, ProjectExplorer::ProjectFileType, false));
+ addFileNodes(QList<FileNode *>() << new FileNode(m_projectFilePath, ProjectFileType, false));
m_recursiveEnumerateFiles = result.recursiveEnumerateFiles;
watchFolders(result.folders.toSet());
@@ -749,7 +746,7 @@ void QmakePriFileNode::update(const Internal::PriFileEvalResult &result)
const QVector<QmakeNodeStaticData::FileTypeData> &fileTypes = qmakeNodeStaticData()->fileTypeData;
for (int i = 0; i < fileTypes.size(); ++i) {
FileType type = fileTypes.at(i).type;
- const QSet<Utils::FileName> &newFilePaths = result.foundFiles.value(type);
+ const QSet<FileName> &newFilePaths = result.foundFiles.value(type);
// We only need to save this information if
// we are watching folders
if (!result.folders.isEmpty())
@@ -772,10 +769,6 @@ void QmakePriFileNode::update(const Internal::PriFileEvalResult &result)
}
contents.updateSubFolders(this);
- if (!m_setCurrentNodeDelayed.isEmpty()) {
- ProjectExplorer::ProjectExplorerPlugin::setCurrentFile(m_project, m_setCurrentNodeDelayed);
- m_setCurrentNodeDelayed.clear();
- }
}
void QmakePriFileNode::watchFolders(const QSet<QString> &folders)
@@ -794,19 +787,19 @@ void QmakePriFileNode::watchFolders(const QSet<QString> &folders)
m_watchedFolders = folders;
}
-bool QmakePriFileNode::folderChanged(const QString &changedFolder, const QSet<Utils::FileName> &newFiles)
+bool QmakePriFileNode::folderChanged(const QString &changedFolder, const QSet<FileName> &newFiles)
{
//qDebug()<<"########## QmakePriFileNode::folderChanged";
// So, we need to figure out which files changed.
- QSet<Utils::FileName> addedFiles = newFiles;
+ QSet<FileName> addedFiles = newFiles;
addedFiles.subtract(m_recursiveEnumerateFiles);
- QSet<Utils::FileName> removedFiles = m_recursiveEnumerateFiles;
+ QSet<FileName> removedFiles = m_recursiveEnumerateFiles;
removedFiles.subtract(newFiles);
- foreach (const Utils::FileName &file, removedFiles) {
- if (!file.isChildOf(Utils::FileName::fromString(changedFolder)))
+ foreach (const FileName &file, removedFiles) {
+ if (!file.isChildOf(FileName::fromString(changedFolder)))
removedFiles.remove(file);
}
@@ -820,8 +813,8 @@ bool QmakePriFileNode::folderChanged(const QString &changedFolder, const QSet<Ut
const QVector<QmakeNodeStaticData::FileTypeData> &fileTypes = qmakeNodeStaticData()->fileTypeData;
for (int i = 0; i < fileTypes.size(); ++i) {
FileType type = fileTypes.at(i).type;
- QSet<Utils::FileName> add = filterFilesRecursiveEnumerata(type, addedFiles);
- QSet<Utils::FileName> remove = filterFilesRecursiveEnumerata(type, removedFiles);
+ QSet<FileName> add = filterFilesRecursiveEnumerata(type, addedFiles);
+ QSet<FileName> remove = filterFilesRecursiveEnumerata(type, removedFiles);
if (!add.isEmpty() || !remove.isEmpty()) {
// Scream :)
@@ -872,19 +865,19 @@ bool QmakePriFileNode::deploysFolder(const QString &folder) const
return false;
}
-QList<ProjectExplorer::RunConfiguration *> QmakePriFileNode::runConfigurations() const
+QList<RunConfiguration *> QmakePriFileNode::runConfigurations() const
{
QmakeRunConfigurationFactory *factory = QmakeRunConfigurationFactory::find(m_project->activeTarget());
if (factory)
return factory->runConfigurationsForNode(m_project->activeTarget(), this);
- return QList<ProjectExplorer::RunConfiguration *>();
+ return QList<RunConfiguration *>();
}
QList<QmakePriFileNode *> QmakePriFileNode::subProjectNodesExact() const
{
QList<QmakePriFileNode *> nodes;
foreach (ProjectNode *node, subProjectNodes()) {
- QmakePriFileNode *n = qobject_cast<QmakePriFileNode *>(node);
+ QmakePriFileNode *n = dynamic_cast<QmakePriFileNode *>(node);
if (n && n->includedInExactParse())
nodes << n;
}
@@ -906,13 +899,13 @@ void QmakePriFileNode::setIncludedInExactParse(bool b)
m_includedInExactParse = b;
}
-QList<ProjectExplorer::ProjectAction> QmakePriFileNode::supportedActions(Node *node) const
+QList<ProjectAction> QmakePriFileNode::supportedActions(Node *node) const
{
- QList<ProjectExplorer::ProjectAction> actions;
+ QList<ProjectAction> actions;
const FolderNode *folderNode = this;
const QmakeProFileNode *proFileNode;
- while (!(proFileNode = qobject_cast<const QmakeProFileNode*>(folderNode)))
+ while (!(proFileNode = dynamic_cast<const QmakeProFileNode*>(folderNode)))
folderNode = folderNode->parentFolderNode();
Q_ASSERT(proFileNode);
@@ -924,16 +917,16 @@ QList<ProjectExplorer::ProjectAction> QmakePriFileNode::supportedActions(Node *n
// projects (e.g. cpp). It'd be nice if the "add" action could
// work on a subset of the file types according to project type.
- actions << ProjectExplorer::AddNewFile;
- if (m_recursiveEnumerateFiles.contains(Utils::FileName::fromString(node->path())))
- actions << ProjectExplorer::EraseFile;
+ actions << AddNewFile;
+ if (m_recursiveEnumerateFiles.contains(FileName::fromString(node->path())))
+ actions << EraseFile;
else
- actions << ProjectExplorer::RemoveFile;
+ actions << RemoveFile;
bool addExistingFiles = true;
- if (node->nodeType() == ProjectExplorer::VirtualFolderNodeType) {
+ if (node->nodeType() == VirtualFolderNodeType) {
// A virtual folder, we do what the projectexplorer does
- FolderNode *folder = qobject_cast<FolderNode *>(node);
+ FolderNode *folder = dynamic_cast<FolderNode *>(node);
if (folder) {
QStringList list;
foreach (FolderNode *f, folder->subFolderNodes())
@@ -946,27 +939,27 @@ QList<ProjectExplorer::ProjectAction> QmakePriFileNode::supportedActions(Node *n
addExistingFiles = addExistingFiles && !deploysFolder(node->path());
if (addExistingFiles)
- actions << ProjectExplorer::AddExistingFile << ProjectExplorer::AddExistingDirectory;
+ actions << AddExistingFile << AddExistingDirectory;
break;
}
case SubDirsTemplate:
- actions << ProjectExplorer::AddSubProject << ProjectExplorer::RemoveSubProject;
+ actions << AddSubProject << RemoveSubProject;
break;
default:
break;
}
- ProjectExplorer::FileNode *fileNode = qobject_cast<FileNode *>(node);
- if ((fileNode && fileNode->fileType() != ProjectExplorer::ProjectFileType)
- || qobject_cast<ResourceEditor::ResourceTopLevelNode *>(node))
- actions << ProjectExplorer::Rename;
+ FileNode *fileNode = dynamic_cast<FileNode *>(node);
+ if ((fileNode && fileNode->fileType() != ProjectFileType)
+ || dynamic_cast<ResourceEditor::ResourceTopLevelNode *>(node))
+ actions << Rename;
- ProjectExplorer::Target *target = m_project->activeTarget();
+ Target *target = m_project->activeTarget();
QmakeRunConfigurationFactory *factory = QmakeRunConfigurationFactory::find(target);
if (factory && !factory->runConfigurationsForNode(target, node).isEmpty())
- actions << ProjectExplorer::HasSubProjectRunConfigurations;
+ actions << HasSubProjectRunConfigurations;
return actions;
}
@@ -994,7 +987,7 @@ static QString simplifyProFilePath(const QString &proFilePath)
bool QmakePriFileNode::addSubProjects(const QStringList &proFilePaths)
{
- ProjectExplorer::FindAllFilesVisitor visitor;
+ FindAllFilesVisitor visitor;
accept(&visitor);
const QStringList &allFiles = visitor.filePaths();
@@ -1029,7 +1022,7 @@ bool QmakePriFileNode::addFiles(const QStringList &filePaths, QStringList *notAd
// So it's obviously a bit limited, but in those cases you need to edit the
// project files manually anyway.
- ProjectExplorer::FindAllFilesVisitor visitor;
+ FindAllFilesVisitor visitor;
accept(&visitor);
const QStringList &allFiles = visitor.filePaths();
@@ -1107,8 +1100,6 @@ bool QmakePriFileNode::renameFile(const QString &filePath, const QString &newFil
if (newFilePath.isEmpty())
return false;
- m_setCurrentNodeDelayed = newFilePath;
-
bool changeProFileOptional = deploysFolder(QFileInfo(filePath).absolutePath());
const Core::MimeType mt = Core::MimeDatabase::findByFile(newFilePath);
QStringList dummy;
@@ -1122,10 +1113,10 @@ bool QmakePriFileNode::renameFile(const QString &filePath, const QString &newFil
return true;
}
-ProjectExplorer::FolderNode::AddNewInformation QmakePriFileNode::addNewInformation(const QStringList &files, Node *context) const
+FolderNode::AddNewInformation QmakePriFileNode::addNewInformation(const QStringList &files, Node *context) const
{
Q_UNUSED(files)
- return ProjectExplorer::FolderNode::AddNewInformation(QFileInfo(path()).fileName(), context && context->projectNode() == this ? 120 : 90);
+ return FolderNode::AddNewInformation(FileName::fromString(path()).fileName(), context && context->projectNode() == this ? 120 : 90);
}
bool QmakePriFileNode::priFileWritable(const QString &path)
@@ -1197,8 +1188,8 @@ bool QmakePriFileNode::ensureWriteableProFile(const QString &file)
bool makeWritable = QFile::setPermissions(file, fi.permissions() | QFile::WriteUser);
if (!makeWritable) {
QMessageBox::warning(Core::ICore::mainWindow(),
- tr("Failed"),
- tr("Could not write project file %1.").arg(file));
+ QCoreApplication::translate("QmakePriFileNode", "Failed"),
+ QCoreApplication::translate("QmakePriFileNode", "Could not write project file %1.").arg(file));
return false;
}
}
@@ -1213,7 +1204,7 @@ QPair<ProFile *, QStringList> QmakePriFileNode::readProFile(const QString &file)
{
QString contents;
{
- Utils::FileReader reader;
+ FileReader reader;
if (!reader.fetch(file, QIODevice::Text)) {
QmakeProject::proFileParseError(reader.errorString());
return qMakePair(includeFile, lines);
@@ -1291,7 +1282,7 @@ bool QmakePriFileNode::setProVariable(const QString &var, const QStringList &val
void QmakePriFileNode::save(const QStringList &lines)
{
Core::DocumentManager::expectFileChange(m_projectFilePath);
- Utils::FileSaver saver(m_projectFilePath, QIODevice::Text);
+ FileSaver saver(m_projectFilePath, QIODevice::Text);
saver.write(lines.join(QLatin1Char('\n')).toLocal8Bit());
saver.finalize(Core::ICore::mainWindow());
@@ -1310,19 +1301,19 @@ void QmakePriFileNode::save(const QStringList &lines)
errorStrings << errorString;
}
if (!errorStrings.isEmpty())
- QMessageBox::warning(Core::ICore::mainWindow(), tr("File Error"),
+ QMessageBox::warning(Core::ICore::mainWindow(), QCoreApplication::translate("QmakePriFileNode", "File Error"),
errorStrings.join(QLatin1Char('\n')));
}
-QStringList QmakePriFileNode::varNames(ProjectExplorer::FileType type, QtSupport::ProFileReader *readerExact)
+QStringList QmakePriFileNode::varNames(FileType type, QtSupport::ProFileReader *readerExact)
{
QStringList vars;
switch (type) {
- case ProjectExplorer::HeaderType:
+ case HeaderType:
vars << QLatin1String("HEADERS");
vars << QLatin1String("PRECOMPILED_HEADER");
break;
- case ProjectExplorer::SourceType: {
+ case SourceType: {
vars << QLatin1String("SOURCES");
QStringList listOfExtraCompilers = readerExact->values(QLatin1String("QMAKE_EXTRA_COMPILERS"));
foreach (const QString &var, listOfExtraCompilers) {
@@ -1336,16 +1327,16 @@ QStringList QmakePriFileNode::varNames(ProjectExplorer::FileType type, QtSupport
}
break;
}
- case ProjectExplorer::ResourceType:
+ case ResourceType:
vars << QLatin1String("RESOURCES");
break;
- case ProjectExplorer::FormType:
+ case FormType:
vars << QLatin1String("FORMS");
break;
- case ProjectExplorer::ProjectFileType:
+ case ProjectFileType:
vars << QLatin1String("SUBDIRS");
break;
- case ProjectExplorer::QMLType:
+ case QMLType:
vars << QLatin1String("OTHER_FILES");
vars << QLatin1String("DISTFILES");
break;
@@ -1453,34 +1444,34 @@ QStringList QmakePriFileNode::dynamicVarNames(QtSupport::ProFileReader *readerEx
return result;
}
-QSet<Utils::FileName> QmakePriFileNode::filterFilesProVariables(ProjectExplorer::FileType fileType, const QSet<Utils::FileName> &files)
+QSet<FileName> QmakePriFileNode::filterFilesProVariables(FileType fileType, const QSet<FileName> &files)
{
- if (fileType != ProjectExplorer::QMLType && fileType != ProjectExplorer::UnknownFileType)
+ if (fileType != QMLType && fileType != UnknownFileType)
return files;
- QSet<Utils::FileName> result;
- if (fileType == ProjectExplorer::QMLType) {
- foreach (const Utils::FileName &file, files)
+ QSet<FileName> result;
+ if (fileType == QMLType) {
+ foreach (const FileName &file, files)
if (file.toString().endsWith(QLatin1String(".qml")))
result << file;
} else {
- foreach (const Utils::FileName &file, files)
+ foreach (const FileName &file, files)
if (!file.toString().endsWith(QLatin1String(".qml")))
result << file;
}
return result;
}
-QSet<Utils::FileName> QmakePriFileNode::filterFilesRecursiveEnumerata(ProjectExplorer::FileType fileType, const QSet<Utils::FileName> &files)
+QSet<FileName> QmakePriFileNode::filterFilesRecursiveEnumerata(FileType fileType, const QSet<FileName> &files)
{
- QSet<Utils::FileName> result;
- if (fileType != ProjectExplorer::QMLType && fileType != ProjectExplorer::UnknownFileType)
+ QSet<FileName> result;
+ if (fileType != QMLType && fileType != UnknownFileType)
return result;
- if (fileType == ProjectExplorer::QMLType) {
- foreach (const Utils::FileName &file, files)
+ if (fileType == QMLType) {
+ foreach (const FileName &file, files)
if (file.toString().endsWith(QLatin1String(".qml")))
result << file;
} else {
- foreach (const Utils::FileName &file, files)
+ foreach (const FileName &file, files)
if (!file.toString().endsWith(QLatin1String(".qml")))
result << file;
}
@@ -1510,7 +1501,7 @@ static QmakeProjectType proFileTemplateTypeToProjectType(ProFileEvaluator::Templ
namespace {
// find all ui files in project
- class FindUiFileNodesVisitor : public ProjectExplorer::NodesVisitor {
+ class FindUiFileNodesVisitor : public NodesVisitor {
public:
void visitProjectNode(ProjectNode *projectNode)
{
@@ -1519,7 +1510,7 @@ namespace {
void visitFolderNode(FolderNode *folderNode)
{
foreach (FileNode *fileNode, folderNode->fileNodes()) {
- if (fileNode->fileType() == ProjectExplorer::FormType)
+ if (fileNode->fileType() == FormType)
uiFileNodes << fileNode;
}
}
@@ -1527,17 +1518,12 @@ namespace {
};
}
-QmakeNodesWatcher::QmakeNodesWatcher(QObject *parent)
- : NodesWatcher(parent)
-{
-}
-
const QmakeProFileNode *QmakeProFileNode::findProFileFor(const QString &fileName) const
{
if (fileName == path())
return this;
foreach (ProjectNode *pn, subProjectNodes())
- if (QmakeProFileNode *qmakeProFileNode = qobject_cast<QmakeProFileNode *>(pn))
+ if (QmakeProFileNode *qmakeProFileNode = dynamic_cast<QmakeProFileNode *>(pn))
if (const QmakeProFileNode *result = qmakeProFileNode->findProFileFor(fileName))
return result;
return 0;
@@ -1551,7 +1537,7 @@ QString QmakeProFileNode::makefile() const
QString QmakeProFileNode::objectExtension() const
{
if (m_varValues[ObjectExt].isEmpty())
- return Utils::HostOsInfo::isWindowsHost() ? QLatin1String(".obj") : QLatin1String(".o");
+ return HostOsInfo::isWindowsHost() ? QLatin1String(".obj") : QLatin1String(".o");
return m_varValues[ObjectExt].first();
}
@@ -1564,14 +1550,21 @@ QByteArray QmakeProFileNode::cxxDefines() const
{
QByteArray result;
foreach (const QString &def, variableValue(DefinesVar)) {
+ // 'def' is shell input, so interpret it.
+ QtcProcess::SplitError error = QtcProcess::SplitOk;
+ const QStringList args = QtcProcess::splitArgs(def, HostOsInfo::hostOs(), false, &error);
+ if (error != QtcProcess::SplitOk || args.size() == 0)
+ continue;
+
result += "#define ";
- const int index = def.indexOf(QLatin1Char('='));
+ const QString defInterpreted = args.first();
+ const int index = defInterpreted.indexOf(QLatin1Char('='));
if (index == -1) {
- result += def.toLatin1();
+ result += defInterpreted.toLatin1();
result += " 1\n";
} else {
- const QString name = def.left(index);
- const QString value = def.mid(index + 1);
+ const QString name = defInterpreted.left(index);
+ const QString value = defInterpreted.mid(index + 1);
result += name.toLatin1();
result += ' ';
result += value.toLocal8Bit();
@@ -1591,8 +1584,7 @@ bool QmakeProFileNode::isDeployable() const
Implements abstract ProjectNode class
*/
QmakeProFileNode::QmakeProFileNode(QmakeProject *project,
- const QString &filePath,
- QObject *parent)
+ const QString &filePath)
: QmakePriFileNode(project, this, filePath),
m_validParse(false),
m_parseInProgress(true),
@@ -1600,11 +1592,13 @@ QmakeProFileNode::QmakeProFileNode(QmakeProject *project,
m_readerExact(0),
m_readerCumulative(0)
{
- if (parent)
- setParent(parent);
-
- connect(&m_parseFutureWatcher, SIGNAL(finished()),
- this, SLOT(applyAsyncEvaluate()));
+ // The slot is a lambda, so that QmakeProFileNode does not need to be
+ // a qobject. The lifetime of the m_parserFutureWatcher is shorter
+ // than of this, so this is all safe
+ QObject::connect(&m_parseFutureWatcher, &QFutureWatcherBase::finished,
+ [this](){
+ applyAsyncEvaluate();
+ });
}
QmakeProFileNode::~QmakeProFileNode()
@@ -1616,7 +1610,7 @@ QmakeProFileNode::~QmakeProFileNode()
bool QmakeProFileNode::isParent(QmakeProFileNode *node)
{
- while ((node = qobject_cast<QmakeProFileNode *>(node->parentFolderNode()))) {
+ while ((node = dynamic_cast<QmakeProFileNode *>(node->parentFolderNode()))) {
if (node == this)
return true;
}
@@ -1628,10 +1622,10 @@ bool QmakeProFileNode::showInSimpleTree() const
return showInSimpleTree(projectType()) || m_project->rootProjectNode() == this;
}
-ProjectExplorer::FolderNode::AddNewInformation QmakeProFileNode::addNewInformation(const QStringList &files, Node *context) const
+FolderNode::AddNewInformation QmakeProFileNode::addNewInformation(const QStringList &files, Node *context) const
{
Q_UNUSED(files)
- return AddNewInformation(QFileInfo(path()).fileName(), context && context->projectNode() == this ? 120 : 100);
+ return AddNewInformation(FileName::fromString(path()).fileName(), context && context->projectNode() == this ? 120 : 100);
}
bool QmakeProFileNode::showInSimpleTree(QmakeProjectType projectType) const
@@ -1674,12 +1668,10 @@ QHash<QString, QString> QmakeProFileNode::uiFiles() const
void QmakeProFileNode::emitProFileUpdatedRecursive()
{
- foreach (ProjectExplorer::NodesWatcher *watcher, watchers())
- if (Internal::QmakeNodesWatcher *qmakeWatcher = qobject_cast<Internal::QmakeNodesWatcher*>(watcher))
- emit qmakeWatcher->proFileUpdated(this, m_validParse, m_parseInProgress);
+ emit m_project->proFileUpdated(this, m_validParse, m_parseInProgress);
foreach (ProjectNode *subNode, subProjectNodes()) {
- if (QmakeProFileNode *node = qobject_cast<QmakeProFileNode *>(subNode))
+ if (QmakeProFileNode *node = dynamic_cast<QmakeProFileNode *>(subNode))
node->emitProFileUpdatedRecursive();
}
}
@@ -1688,7 +1680,7 @@ void QmakeProFileNode::setParseInProgressRecursive(bool b)
{
setParseInProgress(b);
foreach (ProjectNode *subNode, subProjectNodes()) {
- if (QmakeProFileNode *node = qobject_cast<QmakeProFileNode *>(subNode))
+ if (QmakeProFileNode *node = dynamic_cast<QmakeProFileNode *>(subNode))
node->setParseInProgressRecursive(b);
}
}
@@ -1698,16 +1690,14 @@ void QmakeProFileNode::setParseInProgress(bool b)
if (m_parseInProgress == b)
return;
m_parseInProgress = b;
- foreach (ProjectExplorer::NodesWatcher *watcher, watchers())
- if (Internal::QmakeNodesWatcher *qmakeWatcher = qobject_cast<Internal::QmakeNodesWatcher*>(watcher))
- emit qmakeWatcher->proFileUpdated(this, m_validParse, m_parseInProgress);
+ emit m_project->proFileUpdated(this, m_validParse, m_parseInProgress);
}
void QmakeProFileNode::setValidParseRecursive(bool b)
{
setValidParse(b);
foreach (ProjectNode *subNode, subProjectNodes()) {
- if (QmakeProFileNode *node = qobject_cast<QmakeProFileNode *>(subNode))
+ if (QmakeProFileNode *node = dynamic_cast<QmakeProFileNode *>(subNode))
node->setValidParseRecursive(b);
}
}
@@ -1755,8 +1745,8 @@ EvalInput QmakeProFileNode::evalInput() const
input.buildDirectory = buildDir();
input.readerExact = m_readerExact;
input.readerCumulative = m_readerCumulative;
- ProjectExplorer::Target *t = m_project->activeTarget();
- ProjectExplorer::Kit *k = t ? t->kit() : ProjectExplorer::KitManager::defaultKit();
+ Target *t = m_project->activeTarget();
+ Kit *k = t ? t->kit() : KitManager::defaultKit();
QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k);
input.isQt5 = !qtVersion || qtVersion->qtVersion() >= QtSupport::QtVersionNumber(5,0,0);
input.qmakeGlobals = m_project->qmakeGlobals();
@@ -1898,7 +1888,6 @@ EvalResult *QmakeProFileNode::evaluate(const EvalInput &input)
}
}
result->targetInformation = targetInformation(input.readerExact, readerBuildPass, input.buildDirectory, input.projectFilePath);
- result->resolvedMkspecPath = input.readerExact->resolvedMkSpec();
result->installsList = installsList(readerBuildPass, input.projectFilePath, input.projectDir);
// update other variables
@@ -1943,6 +1932,7 @@ EvalResult *QmakeProFileNode::evaluate(const EvalInput &input)
result->newVarValues[AndroidDeploySettingsFile] = input.readerExact->values(QLatin1String("ANDROID_DEPLOYMENT_SETTINGS_FILE"));
result->newVarValues[AndroidPackageSourceDir] = input.readerExact->values(QLatin1String("ANDROID_PACKAGE_SOURCE_DIR"));
result->newVarValues[AndroidExtraLibs] = input.readerExact->values(QLatin1String("ANDROID_EXTRA_LIBS"));
+ result->newVarValues[IsoIconsVar] = input.readerExact->values(QLatin1String("ISO_ICONS"));
result->isDeployable = false;
if (result->projectType == ApplicationTemplate) {
@@ -1959,6 +1949,9 @@ EvalResult *QmakeProFileNode::evaluate(const EvalInput &input)
if (readerBuildPass && readerBuildPass != input.readerExact)
delete readerBuildPass;
+ }
+
+ if (result->state == EvalResult::EvalOk || result->state == EvalResult::EvalPartial) {
QList<QList<VariableAndVPathInformation>> variableAndVPathInformation;
{ // Collect information on VPATHS and qmake variables
@@ -2044,7 +2037,7 @@ void QmakeProFileNode::applyEvaluate(EvalResult *evalResult)
setParseInProgressRecursive(false);
if (result->state == EvalResult::EvalFail) {
- QmakeProject::proFileParseError(tr("Error while parsing file %1. Giving up.").arg(m_projectFilePath));
+ QmakeProject::proFileParseError(QCoreApplication::translate("QmakeProFileNode", "Error while parsing file %1. Giving up.").arg(m_projectFilePath));
if (m_projectType == InvalidProject)
return;
@@ -2053,13 +2046,7 @@ void QmakeProFileNode::applyEvaluate(EvalResult *evalResult)
removeProjectNodes(subProjectNodes());
removeFolderNodes(subFolderNodes());
- // change project type
- QmakeProjectType oldType = m_projectType;
m_projectType = InvalidProject;
-
- foreach (ProjectExplorer::NodesWatcher *watcher, watchers())
- if (Internal::QmakeNodesWatcher *qmakeWatcher = qobject_cast<Internal::QmakeNodesWatcher*>(watcher))
- emit qmakeWatcher->projectTypeChanged(this, oldType, InvalidProject);
}
return;
}
@@ -2068,11 +2055,10 @@ void QmakeProFileNode::applyEvaluate(EvalResult *evalResult)
qDebug() << "QmakeProFileNode - updating files for file " << m_projectFilePath;
if (result->projectType != m_projectType) {
- QmakeProjectType oldType = m_projectType;
// probably all subfiles/projects have changed anyway
// delete files && folders && projects
foreach (ProjectNode *projectNode, subProjectNodes()) {
- if (QmakeProFileNode *qmakeProFileNode = qobject_cast<QmakeProFileNode *>(projectNode)) {
+ if (QmakeProFileNode *qmakeProFileNode = dynamic_cast<QmakeProFileNode *>(projectNode)) {
qmakeProFileNode->setValidParseRecursive(false);
qmakeProFileNode->setParseInProgressRecursive(false);
}
@@ -2085,18 +2071,12 @@ void QmakeProFileNode::applyEvaluate(EvalResult *evalResult)
bool changesShowInSimpleTree = showInSimpleTree() ^ showInSimpleTree(result->projectType);
if (changesShowInSimpleTree)
- aboutToChangeShowInSimpleTree();
+ ProjectTree::instance()->emitAboutToChangeShowInSimpleTree(this);
m_projectType = result->projectType;
if (changesShowInSimpleTree)
- showInSimpleTreeChanged();
-
- // really emit here? or at the end? Nobody is connected to this signal at the moment
- // so we kind of can ignore that question for now
- foreach (ProjectExplorer::NodesWatcher *watcher, watchers())
- if (Internal::QmakeNodesWatcher *qmakeWatcher = qobject_cast<Internal::QmakeNodesWatcher*>(watcher))
- emit qmakeWatcher->projectTypeChanged(this, oldType, result->projectType);
+ ProjectTree::instance()->emitShowInSimpleTreeChanged(this);
}
//
@@ -2199,9 +2179,9 @@ void QmakeProFileNode::applyEvaluate(EvalResult *evalResult)
// Loop preventation, make sure that exact same node is not in our parent chain
bool loop = false;
- ProjectExplorer::Node *n = this;
+ Node *n = this;
while ((n = n->parentFolderNode())) {
- if (qobject_cast<QmakePriFileNode *>(n) && n->path() == nodeToAdd) {
+ if (dynamic_cast<QmakePriFileNode *>(n) && n->path() == nodeToAdd) {
loop = true;
break;
}
@@ -2226,7 +2206,7 @@ void QmakeProFileNode::applyEvaluate(EvalResult *evalResult)
} // for
foreach (ProjectNode *node, toRemove) {
- if (QmakeProFileNode *qmakeProFileNode = qobject_cast<QmakeProFileNode *>(node)) {
+ if (QmakeProFileNode *qmakeProFileNode = dynamic_cast<QmakeProFileNode *>(node)) {
qmakeProFileNode->setValidParseRecursive(false);
qmakeProFileNode->setParseInProgressRecursive(false);
}
@@ -2243,20 +2223,13 @@ void QmakeProFileNode::applyEvaluate(EvalResult *evalResult)
if (m_validParse) {
// update TargetInformation
m_qmakeTargetInformation = result->targetInformation;
- m_resolvedMkspecPath = result->resolvedMkspecPath;
m_subProjectsNotToDeploy = result->subProjectsNotToDeploy;
m_installsList = result->installsList;
m_isDeployable = result->isDeployable;
- if (m_varValues != result->newVarValues) {
- QmakeVariablesHash oldValues = m_varValues;
+ if (m_varValues != result->newVarValues)
m_varValues = result->newVarValues;
-
- foreach (ProjectExplorer::NodesWatcher *watcher, watchers())
- if (Internal::QmakeNodesWatcher *qmakeWatcher = qobject_cast<Internal::QmakeNodesWatcher*>(watcher))
- emit qmakeWatcher->variablesChanged(this, oldValues, m_varValues);
- }
} // result == EvalOk
setParseInProgress(false);
@@ -2323,13 +2296,10 @@ QStringList QmakeProFileNode::includePaths(QtSupport::ProFileReader *reader, con
}
paths.append(reader->absolutePathValues(QLatin1String("INCLUDEPATH"), projectDir));
- paths.append(reader->absolutePathValues(QLatin1String("QMAKE_INCDIR"), projectDir));
// paths already contains moc dir and ui dir, due to corrrectly parsing uic.prf and moc.prf
// except if those directories don't exist at the time of parsing
// thus we add those directories manually (without checking for existence)
paths << mocDirPath(reader, buildDir) << uiDirPath(reader, buildDir);
- // qmake always adds "."
- paths << projectDir;
paths.removeDuplicates();
return paths;
}
@@ -2391,7 +2361,7 @@ QStringList QmakeProFileNode::subDirsPaths(QtSupport::ProFileReader *reader,
}
} else {
if (errors)
- errors->append(tr("Could not find .pro file for sub dir \"%1\" in \"%2\"")
+ errors->append(QCoreApplication::translate("QmakeProFileNode", "Could not find .pro file for sub dir \"%1\" in \"%2\"")
.arg(subDirVar).arg(realDir));
}
}
@@ -2433,11 +2403,6 @@ TargetInformation QmakeProFileNode::targetInformation() const
return m_qmakeTargetInformation;
}
-QString QmakeProFileNode::resolvedMkspecPath() const
-{
- return m_resolvedMkspecPath;
-}
-
InstallsList QmakeProFileNode::installsList(const QtSupport::ProFileReader *reader, const QString &projectFilePath, const QString &projectDir)
{
InstallsList result;
@@ -2529,11 +2494,11 @@ void QmakeProFileNode::updateUiFiles(const QString &buildDir)
// Find all ui files
FindUiFileNodesVisitor uiFilesVisitor;
this->accept(&uiFilesVisitor);
- const QList<ProjectExplorer::FileNode*> uiFiles = uiFilesVisitor.uiFileNodes;
+ const QList<FileNode*> uiFiles = uiFilesVisitor.uiFileNodes;
// Find the UiDir, there can only ever be one
const QString uiDir = uiDirectory(buildDir);
- foreach (const ProjectExplorer::FileNode *uiFile, uiFiles)
+ foreach (const FileNode *uiFile, uiFiles)
m_uiFiles.insert(uiFile->path(), uiHeaderFile(uiDir, uiFile->path()));
}
}
diff --git a/src/plugins/qmakeprojectmanager/qmakenodes.h b/src/plugins/qmakeprojectmanager/qmakenodes.h
index 7f30d47fdae..33c37398215 100644
--- a/src/plugins/qmakeprojectmanager/qmakenodes.h
+++ b/src/plugins/qmakeprojectmanager/qmakenodes.h
@@ -108,7 +108,8 @@ enum QmakeVariable {
AndroidArchVar,
AndroidDeploySettingsFile,
AndroidPackageSourceDir,
- AndroidExtraLibs
+ AndroidExtraLibs,
+ IsoIconsVar
};
// Import base classes into namespace
@@ -116,7 +117,6 @@ using ProjectExplorer::Node;
using ProjectExplorer::FileNode;
using ProjectExplorer::FolderNode;
using ProjectExplorer::ProjectNode;
-using ProjectExplorer::NodesWatcher;
// Import enums into namespace
using ProjectExplorer::NodeType;
@@ -150,8 +150,6 @@ public:
// Implements ProjectNode for qmake .pri files
class QMAKEPROJECTMANAGER_EXPORT QmakePriFileNode : public ProjectExplorer::ProjectNode
{
- Q_OBJECT
-
public:
QmakePriFileNode(QmakeProject *project, QmakeProFileNode *qmakeProFileNode, const QString &filePath);
~QmakePriFileNode();
@@ -210,10 +208,9 @@ protected:
QStringList *notChanged,
ChangeType change);
-private slots:
+private:
void scheduleUpdate();
-private:
static bool ensureWriteableProFile(const QString &file);
static QPair<ProFile *, QStringList> readProFile(const QString &file);
static QPair<ProFile *, QStringList> readProFileFromContents(const QString &contents);
@@ -240,7 +237,6 @@ private:
QSet<Utils::FileName> m_recursiveEnumerateFiles;
QSet<QString> m_watchedFolders;
bool m_includedInExactParse;
- QString m_setCurrentNodeDelayed;
// managed by QmakeProFileNode
friend class QmakeProjectManager::QmakeProFileNode;
@@ -270,30 +266,6 @@ private:
QmakePriFileNode *m_priFile;
};
-class QmakeNodesWatcher : public ProjectExplorer::NodesWatcher
-{
- Q_OBJECT
-
-public:
- QmakeNodesWatcher(QObject *parent = 0);
-
-signals:
- void projectTypeChanged(QmakeProjectManager::QmakeProFileNode *projectNode,
- const QmakeProjectManager::QmakeProjectType oldType,
- const QmakeProjectManager::QmakeProjectType newType);
-
- void variablesChanged(QmakeProFileNode *projectNode,
- const QHash<QmakeVariable, QStringList> &oldValues,
- const QHash<QmakeVariable, QStringList> &newValues);
-
- void proFileUpdated(QmakeProjectManager::QmakeProFileNode *projectNode, bool success, bool parseInProgress);
-
-private:
- // let them emit signals
- friend class QmakeProjectManager::QmakeProFileNode;
- friend class QmakePriFileNode;
-};
-
class ProVirtualFolderNode : public ProjectExplorer::VirtualFolderNode
{
public:
@@ -376,12 +348,9 @@ struct QMAKEPROJECTMANAGER_EXPORT ProjectVersion {
// Implements ProjectNode for qmake .pro files
class QMAKEPROJECTMANAGER_EXPORT QmakeProFileNode : public QmakePriFileNode
{
- Q_OBJECT
-
public:
QmakeProFileNode(QmakeProject *project,
- const QString &filePath,
- QObject *parent = 0);
+ const QString &filePath);
~QmakeProFileNode();
bool isParent(QmakeProFileNode *node);
@@ -416,7 +385,6 @@ public:
QString objectsDirectory() const;
QByteArray cxxDefines() const;
bool isDeployable() const;
- QString resolvedMkspecPath() const;
enum AsyncUpdateDelay { ParseNow, ParseLater };
void scheduleUpdate(AsyncUpdateDelay delay);
@@ -433,13 +401,12 @@ public:
void setValidParse(bool b);
void setValidParseRecursive(bool b);
void emitProFileUpdatedRecursive();
-public slots:
+
void asyncUpdate();
-private slots:
+private:
void applyAsyncEvaluate();
-private:
void setupReader();
Internal::EvalInput evalInput() const;
@@ -474,7 +441,6 @@ private:
QMap<QString, QDateTime> m_uitimestamps;
TargetInformation m_qmakeTargetInformation;
- QString m_resolvedMkspecPath;
QStringList m_subProjectsNotToDeploy;
InstallsList m_installsList;
diff --git a/src/plugins/qmakeprojectmanager/qmakeproject.cpp b/src/plugins/qmakeprojectmanager/qmakeproject.cpp
index 94be05e0231..34096c70baf 100644
--- a/src/plugins/qmakeprojectmanager/qmakeproject.cpp
+++ b/src/plugins/qmakeprojectmanager/qmakeproject.cpp
@@ -42,7 +42,6 @@
#include "wizards/qtquickapp.h"
#include <utils/algorithm.h>
-#include <coreplugin/documentmanager.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/progressmanager/progressmanager.h>
@@ -55,7 +54,6 @@
#include <projectexplorer/headerpath.h>
#include <projectexplorer/target.h>
#include <projectexplorer/projectexplorer.h>
-#include <projectexplorer/session.h>
#include <proparser/qmakevfs.h>
#include <qtsupport/profilereader.h>
#include <qtsupport/qtkitinformation.h>
@@ -81,7 +79,7 @@ enum { debug = 0 };
namespace {
-QmakeBuildConfiguration *enableActiveQmakeBuildConfiguration(ProjectExplorer::Target *t, bool enabled)
+QmakeBuildConfiguration *enableActiveQmakeBuildConfiguration(Target *t, bool enabled)
{
if (!t)
return 0;
@@ -173,8 +171,8 @@ public:
void clear();
bool equals(const QmakeProjectFiles &f) const;
- QStringList files[ProjectExplorer::FileTypeSize];
- QStringList generatedFiles[ProjectExplorer::FileTypeSize];
+ QStringList files[FileTypeSize];
+ QStringList generatedFiles[FileTypeSize];
QStringList proFiles;
};
@@ -213,7 +211,7 @@ QDebug operator<<(QDebug d, const QmakeProjectFiles &f)
}
// A visitor to collect all files of a project in a QmakeProjectFiles struct
-class ProjectFilesVisitor : public ProjectExplorer::NodesVisitor
+class ProjectFilesVisitor : public NodesVisitor
{
ProjectFilesVisitor(QmakeProjectFiles *files);
@@ -265,7 +263,7 @@ void ProjectFilesVisitor::visitProjectNode(ProjectNode *projectNode)
void ProjectFilesVisitor::visitFolderNode(FolderNode *folderNode)
{
- if (qobject_cast<ResourceEditor::ResourceTopLevelNode *>(folderNode))
+ if (dynamic_cast<ResourceEditor::ResourceTopLevelNode *>(folderNode))
m_files->files[ResourceType].push_back(folderNode->path());
foreach (FileNode *fileNode, folderNode->fileNodes()) {
@@ -285,7 +283,7 @@ QmakeProjectFile::QmakeProjectFile(const QString &filePath, QObject *parent)
{
setId("Qmake.ProFile");
setMimeType(QLatin1String(QmakeProjectManager::Constants::PROFILE_MIMETYPE));
- setFilePath(filePath);
+ setFilePath(FileName::fromString(filePath));
}
bool QmakeProjectFile::save(QString *, const QString &, bool)
@@ -340,7 +338,6 @@ bool QmakeProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType
QmakeProject::QmakeProject(QmakeManager *manager, const QString &fileName) :
m_manager(manager),
m_rootProjectNode(0),
- m_nodesWatcher(new Internal::QmakeNodesWatcher(this)),
m_fileInfo(new QmakeProjectFile(fileName, this)),
m_projectFiles(new QmakeProjectFiles),
m_qmakeVfs(new QMakeVfs),
@@ -416,21 +413,17 @@ bool QmakeProject::fromMap(const QVariantMap &map)
m_manager->registerProject(this);
- m_rootProjectNode = new QmakeProFileNode(this, m_fileInfo->filePath(), this);
- m_rootProjectNode->registerWatcher(m_nodesWatcher);
-
- // We have the profile nodes now, so we know the runconfigs!
- connect(m_nodesWatcher, SIGNAL(proFileUpdated(QmakeProjectManager::QmakeProFileNode*,bool,bool)),
- this, SIGNAL(proFileUpdated(QmakeProjectManager::QmakeProFileNode*,bool,bool)));
+ m_rootProjectNode = new QmakeProFileNode(this, m_fileInfo->filePath().toString());
// On active buildconfiguration changes, reevaluate the .pro files
m_activeTarget = activeTarget();
- if (m_activeTarget)
- connect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
- this, SLOT(scheduleAsyncUpdate()));
+ if (m_activeTarget) {
+ connect(m_activeTarget, &Target::activeBuildConfigurationChanged,
+ this, &QmakeProject::scheduleAsyncUpdateLater);
+ }
- connect(this, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
- this, SLOT(activeTargetWasChanged()));
+ connect(this, &Project::activeTargetChanged,
+ this, &QmakeProject::activeTargetWasChanged);
scheduleAsyncUpdate(QmakeProFileNode::ParseNow);
return true;
@@ -480,7 +473,7 @@ void QmakeProject::updateCppCodeModel()
Kit *k = 0;
QtSupport::BaseQtVersion *qtVersion = 0;
- if (ProjectExplorer::Target *target = activeTarget())
+ if (Target *target = activeTarget())
k = target->kit();
else
k = KitManager::defaultKit();
@@ -495,8 +488,8 @@ void QmakeProject::updateCppCodeModel()
FindQmakeProFiles findQmakeProFiles;
QList<QmakeProFileNode *> proFiles = findQmakeProFiles(rootProjectNode());
- CppTools::ProjectInfo pinfo = modelmanager->projectInfo(this);
- pinfo.clearProjectParts();
+ CppTools::ProjectInfo pinfo = CppTools::ProjectInfo(this);
+
ProjectPart::QtVersion qtVersionForPart = ProjectPart::NoQt;
if (qtVersion) {
if (qtVersion->qtVersion() < QtSupport::QtVersionNumber(5,0,0))
@@ -523,9 +516,6 @@ void QmakeProject::updateCppCodeModel()
templatePart->projectDefines += pro->cxxDefines();
// part->headerPaths
- foreach (const QString &inc, pro->variableValue(IncludePathVar))
- templatePart->headerPaths += ProjectPart::HeaderPath(inc, ProjectPart::HeaderPath::IncludePath);
-
if (qtVersion) {
foreach (const HeaderPath &header, qtVersion->systemHeaderPathes(k)) {
ProjectPart::HeaderPath::Type type = ProjectPart::HeaderPath::IncludePath;
@@ -533,6 +523,19 @@ void QmakeProject::updateCppCodeModel()
type = ProjectPart::HeaderPath::FrameworkPath;
templatePart->headerPaths += ProjectPart::HeaderPath(header.path(), type);
}
+ }
+
+ foreach (const QString &inc, pro->variableValue(IncludePathVar)) {
+ const auto headerPath
+ = ProjectPart::HeaderPath(inc, ProjectPart::HeaderPath::IncludePath);
+ // We've added header paths from qtVersion->systemHeaderPathes() above,
+ // which also contains the mkspecs dir. However, it's also part of
+ // the pro->variableValue(IncludePathVar), so check for duplicates.
+ if (!templatePart->headerPaths.contains(headerPath))
+ templatePart->headerPaths += headerPath;
+ }
+
+ if (qtVersion) {
if (!qtVersion->frameworkInstallPath().isEmpty()) {
templatePart->headerPaths += ProjectPart::HeaderPath(
qtVersion->frameworkInstallPath(),
@@ -540,10 +543,6 @@ void QmakeProject::updateCppCodeModel()
}
}
- if (QmakeProFileNode *node = rootQmakeProjectNode())
- templatePart->headerPaths += ProjectPart::HeaderPath(node->resolvedMkspecPath(),
- ProjectPart::HeaderPath::IncludePath);
-
// part->precompiledHeaders
templatePart->precompiledHeaders.append(pro->variableValue(PrecompiledHeaderVar));
@@ -635,7 +634,7 @@ void QmakeProject::updateQmlJSCodeModel()
bool hasQmlLib = false;
foreach (QmakeProFileNode *node, proFiles) {
foreach (const QString &path, node->variableValue(QmlImportPathVar))
- projectInfo.importPaths.maybeInsert(Utils::FileName::fromString(path),
+ projectInfo.importPaths.maybeInsert(FileName::fromString(path),
QmlJS::Dialect::Qml);
projectInfo.activeResourceFiles.append(node->variableValue(ExactResourceVar));
projectInfo.allResourceFiles.append(node->variableValue(ResourceVar));
@@ -842,11 +841,6 @@ void QmakeProject::decrementPendingEvaluateFutures()
updateBoilerPlateCodeFiles(&qtQuickApp, path);
}
}
-
- ProjectExplorer::Node *node = ProjectExplorer::SessionManager::nodeForFile(Core::DocumentManager::currentFile());
- if (node)
- ProjectExplorerPlugin::setCurrentNode(node);
-
m_checkForTemplateUpdate = false;
}
@@ -901,7 +895,7 @@ void QmakeProject::buildFinished(bool success)
m_qmakeVfs->invalidateContents();
}
-ProjectExplorer::IProjectManager *QmakeProject::projectManager() const
+IProjectManager *QmakeProject::projectManager() const
{
return m_manager;
}
@@ -960,7 +954,7 @@ static FolderNode *folderOf(FolderNode *in, FileType fileType, const QString &fi
static QmakeProFileNode *proFileNodeOf(QmakeProFileNode *in, FileType fileType, const QString &fileName)
{
for (FolderNode *folder = folderOf(in, fileType, fileName); folder; folder = folder->parentFolderNode())
- if (QmakeProFileNode *proFile = qobject_cast<QmakeProFileNode *>(folder))
+ if (QmakeProFileNode *proFile = dynamic_cast<QmakeProFileNode *>(folder))
return proFile;
return 0;
}
@@ -987,7 +981,7 @@ QtSupport::ProFileReader *QmakeProject::createProFileReader(const QmakeProFileNo
m_qmakeGlobalsRefCnt = 0;
Kit *k;
- Utils::Environment env = Utils::Environment::systemEnvironment();
+ Environment env = Environment::systemEnvironment();
QStringList qmakeArgs;
if (!bc)
bc = activeTarget() ? static_cast<QmakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration()) : 0;
@@ -1014,7 +1008,7 @@ QtSupport::ProFileReader *QmakeProject::createProFileReader(const QmakeProFileNo
m_qmakeGlobals->setDirectories(m_rootProjectNode->sourceDir(), m_rootProjectNode->buildDir());
m_qmakeGlobals->sysroot = systemRoot;
- Utils::Environment::const_iterator eit = env.constBegin(), eend = env.constEnd();
+ Environment::const_iterator eit = env.constBegin(), eend = env.constEnd();
for (; eit != eend; ++eit)
m_qmakeGlobals->environment.insert(env.key(eit), env.value(eit));
@@ -1059,7 +1053,7 @@ void QmakeProject::destroyProFileReader(QtSupport::ProFileReader *reader)
{
delete reader;
if (!--m_qmakeGlobalsRefCnt) {
- QString dir = QFileInfo(m_fileInfo->filePath()).absolutePath();
+ QString dir = m_fileInfo->filePath().toFileInfo().absolutePath();
if (!dir.endsWith(QLatin1Char('/')))
dir += QLatin1Char('/');
QtSupport::ProFileCacheManager::instance()->discardFiles(dir);
@@ -1070,7 +1064,7 @@ void QmakeProject::destroyProFileReader(QtSupport::ProFileReader *reader)
}
}
-ProjectExplorer::ProjectNode *QmakeProject::rootProjectNode() const
+ProjectNode *QmakeProject::rootProjectNode() const
{
return m_rootProjectNode;
}
@@ -1103,7 +1097,7 @@ void QmakeProject::collectAllProFiles(QList<QmakeProFileNode *> &list, QmakeProF
if (projectTypes.isEmpty() || projectTypes.contains(node->projectType()))
list.append(node);
foreach (ProjectNode *n, node->subProjectNodes()) {
- QmakeProFileNode *qmakeProFileNode = qobject_cast<QmakeProFileNode *>(n);
+ QmakeProFileNode *qmakeProFileNode = dynamic_cast<QmakeProFileNode *>(n);
if (qmakeProFileNode)
collectAllProFiles(list, qmakeProFileNode, parse, projectTypes);
}
@@ -1156,8 +1150,8 @@ QList<Core::Id> QmakeProject::idsForNodes(Core::Id base, const QList<QmakeProFil
void QmakeProject::activeTargetWasChanged()
{
if (m_activeTarget) {
- disconnect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
- this, SLOT(scheduleAsyncUpdate()));
+ disconnect(m_activeTarget, &Target::activeBuildConfigurationChanged,
+ this, &QmakeProject::scheduleAsyncUpdateLater);
}
m_activeTarget = activeTarget();
@@ -1165,8 +1159,8 @@ void QmakeProject::activeTargetWasChanged()
if (!m_activeTarget)
return;
- connect(m_activeTarget, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
- this, SLOT(scheduleAsyncUpdate()));
+ connect(m_activeTarget, &Target::activeBuildConfigurationChanged,
+ this, &QmakeProject::scheduleAsyncUpdateLater);
scheduleAsyncUpdate();
}
@@ -1176,9 +1170,9 @@ bool QmakeProject::hasSubNode(QmakePriFileNode *root, const QString &path)
if (root->path() == path)
return true;
foreach (FolderNode *fn, root->subFolderNodes()) {
- if (qobject_cast<QmakeProFileNode *>(fn)) {
+ if (dynamic_cast<QmakeProFileNode *>(fn)) {
// we aren't interested in pro file nodes
- } else if (QmakePriFileNode *qt4prifilenode = qobject_cast<QmakePriFileNode *>(fn)) {
+ } else if (QmakePriFileNode *qt4prifilenode = dynamic_cast<QmakePriFileNode *>(fn)) {
if (hasSubNode(qt4prifilenode, path))
return true;
}
@@ -1192,7 +1186,7 @@ void QmakeProject::findProFile(const QString& fileName, QmakeProFileNode *root,
list.append(root);
foreach (FolderNode *fn, root->subFolderNodes())
- if (QmakeProFileNode *qt4proFileNode = qobject_cast<QmakeProFileNode *>(fn))
+ if (QmakeProFileNode *qt4proFileNode = dynamic_cast<QmakeProFileNode *>(fn))
findProFile(fileName, qt4proFileNode, list);
}
@@ -1363,7 +1357,7 @@ void CentralizedFolderWatcher::delayedFolderChanged(const QString &folder)
QList<QmakePriFileNode *> nodes = m_map.values(dir);
if (!nodes.isEmpty()) {
// Collect all the files
- QSet<Utils::FileName> newFiles;
+ QSet<FileName> newFiles;
newFiles += QmakePriFileNode::recursiveEnumerate(folder);
foreach (QmakePriFileNode *node, nodes) {
newOrRemovedFiles = newOrRemovedFiles
@@ -1445,17 +1439,17 @@ QString QmakeProject::disabledReasonForRunConfiguration(const QString &proFilePa
{
if (!QFileInfo::exists(proFilePath))
return tr("The .pro file \"%1\" does not exist.")
- .arg(QFileInfo(proFilePath).fileName());
+ .arg(FileName::fromString(proFilePath).fileName());
if (!m_rootProjectNode) // Shutting down
return QString();
if (!m_rootProjectNode->findProFileFor(proFilePath))
return tr("The .pro file \"%1\" is not part of the project.")
- .arg(QFileInfo(proFilePath).fileName());
+ .arg(FileName::fromString(proFilePath).fileName());
return tr("The .pro file \"%1\" could not be parsed.")
- .arg(QFileInfo(proFilePath).fileName());
+ .arg(FileName::fromString(proFilePath).fileName());
}
QString QmakeProject::buildNameFor(const Kit *k)
@@ -1482,8 +1476,8 @@ void QmakeProject::updateBuildSystemData()
BuildTargetInfoList appTargetList;
foreach (const QmakeProFileNode * const node, applicationProFiles()) {
appTargetList.list << BuildTargetInfo(node->targetInformation().target,
- Utils::FileName::fromString(executableFor(node)),
- Utils::FileName::fromString(node->path()));
+ FileName::fromString(executableFor(node)),
+ FileName::fromString(node->path()));
}
target->setApplicationTargets(appTargetList);
}
@@ -1510,7 +1504,7 @@ void QmakeProject::collectData(const QmakeProFileNode *node, DeploymentData &dep
case SubDirsTemplate:
foreach (const ProjectNode * const subProject, node->subProjectNodesExact()) {
const QmakeProFileNode * const qt4SubProject
- = qobject_cast<const QmakeProFileNode *>(subProject);
+ = dynamic_cast<const QmakeProFileNode *>(subProject);
if (!qt4SubProject)
continue;
collectData(qt4SubProject, deploymentData);
@@ -1543,9 +1537,8 @@ void QmakeProject::collectLibraryData(const QmakeProFileNode *node, DeploymentDa
const QString targetPath = node->installsList().targetPath;
if (targetPath.isEmpty())
return;
- const ProjectExplorer::Kit * const kit = activeTarget()->kit();
- const ProjectExplorer::ToolChain * const toolchain
- = ProjectExplorer::ToolChainKitInformation::toolChain(kit);
+ const Kit * const kit = activeTarget()->kit();
+ const ToolChain * const toolchain = ToolChainKitInformation::toolChain(kit);
if (!toolchain)
return;
@@ -1555,7 +1548,7 @@ void QmakeProject::collectLibraryData(const QmakeProFileNode *node, DeploymentDa
const bool isStatic = config.contains(QLatin1String("static"));
const bool isPlugin = config.contains(QLatin1String("plugin"));
switch (toolchain->targetAbi().os()) {
- case ProjectExplorer::Abi::WindowsOS: {
+ case Abi::WindowsOS: {
QString targetVersionExt = node->singleVariableValue(TargetVersionExtVar);
if (targetVersionExt.isEmpty()) {
const QString version = node->singleVariableValue(VersionVar);
@@ -1570,7 +1563,7 @@ void QmakeProject::collectLibraryData(const QmakeProFileNode *node, DeploymentDa
deploymentData.addFile(destDirFor(ti) + QLatin1Char('/') + targetFileName, targetPath);
break;
}
- case ProjectExplorer::Abi::MacOS: {
+ case Abi::MacOS: {
QString destDir = destDirFor(ti);
if (config.contains(QLatin1String("lib_bundle"))) {
destDir.append(QLatin1Char('/')).append(ti.target)
@@ -1592,9 +1585,9 @@ void QmakeProject::collectLibraryData(const QmakeProFileNode *node, DeploymentDa
deploymentData.addFile(destDir + QLatin1Char('/') + targetFileName, targetPath);
break;
}
- case ProjectExplorer::Abi::LinuxOS:
- case ProjectExplorer::Abi::BsdOS:
- case ProjectExplorer::Abi::UnixOS:
+ case Abi::LinuxOS:
+ case Abi::BsdOS:
+ case Abi::UnixOS:
targetFileName.prepend(QLatin1String("lib"));
targetFileName += QLatin1Char('.');
if (isStatic) {
@@ -1626,7 +1619,7 @@ void QmakeProject::collectLibraryData(const QmakeProFileNode *node, DeploymentDa
bool QmakeProject::matchesKit(const Kit *kit)
{
QList<QtSupport::BaseQtVersion *> parentQts;
- Utils::FileName filePath = projectFilePath();
+ FileName filePath = projectFilePath();
foreach (QtSupport::BaseQtVersion *version, QtSupport::QtVersionManager::validVersions()) {
if (version->isSubProject(filePath))
parentQts.append(version);
@@ -1640,9 +1633,8 @@ bool QmakeProject::matchesKit(const Kit *kit)
QString QmakeProject::executableFor(const QmakeProFileNode *node)
{
- const ProjectExplorer::Kit * const kit = activeTarget()->kit();
- const ProjectExplorer::ToolChain * const toolchain
- = ProjectExplorer::ToolChainKitInformation::toolChain(kit);
+ const Kit * const kit = activeTarget()->kit();
+ const ToolChain * const toolchain = ToolChainKitInformation::toolChain(kit);
if (!toolchain)
return QString();
@@ -1650,7 +1642,7 @@ QString QmakeProject::executableFor(const QmakeProFileNode *node)
QString target;
switch (toolchain->targetAbi().os()) {
- case ProjectExplorer::Abi::MacOS:
+ case Abi::MacOS:
if (node->variableValue(ConfigVar).contains(QLatin1String("app_bundle"))) {
target = ti.target + QLatin1String(".app/Contents/MacOS/") + ti.target;
break;
diff --git a/src/plugins/qmakeprojectmanager/qmakeproject.h b/src/plugins/qmakeprojectmanager/qmakeproject.h
index 6d05084d401..ea355a79361 100644
--- a/src/plugins/qmakeprojectmanager/qmakeproject.h
+++ b/src/plugins/qmakeprojectmanager/qmakeproject.h
@@ -61,7 +61,6 @@ class CentralizedFolderWatcher;
class QmakeProjectFiles;
class QmakeProjectConfigWidget;
class QmakeProjectFile;
-class QmakeNodesWatcher;
}
class QMAKEPROJECTMANAGER_EXPORT QmakeProject : public ProjectExplorer::Project
@@ -151,6 +150,7 @@ signals:
public slots:
void scheduleAsyncUpdate(QmakeProFileNode::AsyncUpdateDelay delay = QmakeProFileNode::ParseLater);
+ void scheduleAsyncUpdateLater() { scheduleAsyncUpdate(); }
protected:
bool fromMap(const QVariantMap &map);
@@ -186,7 +186,6 @@ private:
QmakeManager *m_manager;
QmakeProFileNode *m_rootProjectNode;
- Internal::QmakeNodesWatcher *m_nodesWatcher;
Internal::QmakeProjectFile *m_fileInfo;
diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectmanager.cpp b/src/plugins/qmakeprojectmanager/qmakeprojectmanager.cpp
index 7a05ca9c825..be99805b08f 100644
--- a/src/plugins/qmakeprojectmanager/qmakeprojectmanager.cpp
+++ b/src/plugins/qmakeprojectmanager/qmakeprojectmanager.cpp
@@ -42,6 +42,7 @@
#include <coreplugin/icore.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
@@ -134,13 +135,13 @@ void QmakeManager::setContextFile(ProjectExplorer::FileNode *file)
void QmakeManager::addLibrary()
{
if (auto editor = qobject_cast<BaseTextEditor *>(Core::EditorManager::currentEditor()))
- addLibrary(editor->document()->filePath(), editor);
+ addLibrary(editor->document()->filePath().toString(), editor);
}
void QmakeManager::addLibraryContextMenu()
{
- Node *node = ProjectExplorerPlugin::currentNode();
- if (qobject_cast<QmakeProFileNode *>(node))
+ Node *node = ProjectTree::currentNode();
+ if (dynamic_cast<QmakeProFileNode *>(node))
addLibrary(node->path());
}
@@ -200,7 +201,7 @@ void QmakeManager::runQMake(ProjectExplorer::Project *p, ProjectExplorer::Node *
qs->setForced(true);
if (node != 0 && node != qmakeProject->rootProjectNode())
- if (QmakeProFileNode *profile = qobject_cast<QmakeProFileNode *>(node))
+ if (QmakeProFileNode *profile = dynamic_cast<QmakeProFileNode *>(node))
bc->setSubNodeBuild(profile);
BuildManager::appendStep(qs, tr("QMake"));
@@ -230,8 +231,8 @@ void QmakeManager::buildFileContextMenu()
void QmakeManager::buildFile()
{
if (Core::IDocument *currentDocument= Core::EditorManager::currentDocument()) {
- const QString file = currentDocument->filePath();
- FileNode *node = qobject_cast<FileNode *>(SessionManager::nodeForFile(file));
+ const QString file = currentDocument->filePath().toString();
+ FileNode *node = dynamic_cast<FileNode *>(SessionManager::nodeForFile(file));
Project *project = SessionManager::projectForFile(file);
if (project && node)
@@ -263,7 +264,7 @@ void QmakeManager::handleSubDirContextMenu(QmakeManager::Action action, bool isF
return;
if (contextNode) {
- if (QmakePriFileNode *prifile = qobject_cast<QmakePriFileNode *>(contextNode)) {
+ if (QmakePriFileNode *prifile = dynamic_cast<QmakePriFileNode *>(contextNode)) {
if (QmakeProFileNode *profile = prifile->proFileNode()) {
if (profile != qmakeProject->rootProjectNode() || isFileBuild)
bc->setSubNodeBuild(profile);
diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp
index 32e2abb6209..888e1e553f7 100644
--- a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp
+++ b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp
@@ -53,7 +53,7 @@
#include <coreplugin/icore.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/session.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/target.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/coreconstants.h>
@@ -100,8 +100,6 @@ bool QmakeProjectManagerPlugin::initialize(const QStringList &arguments, QString
if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":qmakeprojectmanager/QmakeProjectManager.mimetypes.xml"), errorMessage))
return false;
- m_projectExplorer = ProjectExplorerPlugin::instance();
-
//create and register objects
m_qmakeProjectManager = new QmakeManager;
addObject(m_qmakeProjectManager);
@@ -235,8 +233,8 @@ bool QmakeProjectManagerPlugin::initialize(const QStringList &arguments, QString
this, SLOT(buildStateChanged(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*)));
+ connect(ProjectTree::instance(), &ProjectTree::currentNodeChanged,
+ this, &QmakeProjectManagerPlugin::updateContextActions);
Core::ActionContainer *contextMenu = Core::ActionManager::createMenu(QmakeProjectManager::Constants::M_CONTEXT);
@@ -307,9 +305,9 @@ void QmakeProjectManagerPlugin::activeTargetChanged()
void QmakeProjectManagerPlugin::updateRunQMakeAction()
{
bool enable = true;
- if (BuildManager::isBuilding(m_projectExplorer->currentProject()))
+ if (BuildManager::isBuilding(ProjectTree::currentProject()))
enable = false;
- QmakeProject *pro = qobject_cast<QmakeProject *>(m_projectExplorer->currentProject());
+ QmakeProject *pro = qobject_cast<QmakeProject *>(ProjectTree::currentProject());
if (!pro
|| !pro->activeTarget()
|| !pro->activeTarget()->activeBuildConfiguration())
@@ -320,16 +318,16 @@ void QmakeProjectManagerPlugin::updateRunQMakeAction()
void QmakeProjectManagerPlugin::updateContextActions(ProjectExplorer::Node *node, ProjectExplorer::Project *project)
{
- m_addLibraryActionContextMenu->setEnabled(qobject_cast<QmakeProFileNode *>(node));
+ m_addLibraryActionContextMenu->setEnabled(dynamic_cast<QmakeProFileNode *>(node));
- QmakeProFileNode *proFileNode = qobject_cast<QmakeProFileNode *>(node);
+ QmakeProFileNode *proFileNode = dynamic_cast<QmakeProFileNode *>(node);
QmakeProject *qmakeProject = qobject_cast<QmakeProject *>(project);
QmakeProFileNode *subProjectNode = 0;
if (node) {
- if (QmakePriFileNode *subPriFileNode = qobject_cast<QmakePriFileNode *>(node->projectNode()))
+ if (QmakePriFileNode *subPriFileNode = dynamic_cast<QmakePriFileNode *>(node->projectNode()))
subProjectNode = subPriFileNode->proFileNode();
}
- ProjectExplorer::FileNode *fileNode = qobject_cast<ProjectExplorer::FileNode *>(node);
+ ProjectExplorer::FileNode *fileNode = dynamic_cast<ProjectExplorer::FileNode *>(node);
bool buildFilePossible = subProjectNode && fileNode
&& (fileNode->fileType() == ProjectExplorer::SourceType);
@@ -347,7 +345,7 @@ void QmakeProjectManagerPlugin::updateContextActions(ProjectExplorer::Node *node
m_rebuildSubProjectAction->setParameter(subProjectName);
m_cleanSubProjectAction->setParameter(subProjectName);
m_buildSubProjectContextMenu->setParameter(subProjectName);
- m_buildFileAction->setParameter(buildFilePossible ? QFileInfo(fileNode->path()).fileName() : QString());
+ m_buildFileAction->setParameter(buildFilePossible ? Utils::FileName::fromString(fileNode->path()).fileName() : QString());
QmakeBuildConfiguration *buildConfiguration = (qmakeProject && qmakeProject->activeTarget()) ?
static_cast<QmakeBuildConfiguration *>(qmakeProject->activeTarget()->activeBuildConfiguration()) : 0;
@@ -380,10 +378,10 @@ void QmakeProjectManagerPlugin::updateContextActions(ProjectExplorer::Node *node
void QmakeProjectManagerPlugin::buildStateChanged(ProjectExplorer::Project *pro)
{
- ProjectExplorer::Project *currentProject = m_projectExplorer->currentProject();
+ ProjectExplorer::Project *currentProject = ProjectTree::currentProject();
if (pro == currentProject) {
updateRunQMakeAction();
- updateContextActions(ProjectExplorerPlugin::currentNode(), pro);
+ updateContextActions(ProjectTree::currentNode(), pro);
updateBuildFileAction();
}
}
@@ -394,13 +392,13 @@ void QmakeProjectManagerPlugin::updateBuildFileAction()
bool enabled = false;
if (Core::IDocument *currentDocument= Core::EditorManager::currentDocument()) {
- QString file = currentDocument->filePath();
+ QString file = currentDocument->filePath().toString();
Node *node = SessionManager::nodeForFile(file);
Project *project = SessionManager::projectForFile(file);
- m_buildFileAction->setParameter(QFileInfo(file).fileName());
+ m_buildFileAction->setParameter(Utils::FileName::fromString(file).fileName());
visible = qobject_cast<QmakeProject *>(project)
&& node
- && qobject_cast<QmakePriFileNode *>(node->projectNode());
+ && dynamic_cast<QmakePriFileNode *>(node->projectNode());
enabled = !BuildManager::isBuilding(project);
}
diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.h b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.h
index 683041a58d9..3c018989f56 100644
--- a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.h
+++ b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.h
@@ -41,7 +41,6 @@ QT_END_NAMESPACE
namespace ProjectExplorer {
class Node;
class Project;
-class ProjectExplorerPlugin;
class KitInformation;
class Target;
}
@@ -79,7 +78,6 @@ private slots:
#endif
private:
- ProjectExplorer::ProjectExplorerPlugin *m_projectExplorer;
QmakeManager *m_qmakeProjectManager;
QmakeProject *m_previousStartupProject;
ProjectExplorer::Target *m_previousTarget;
diff --git a/src/plugins/qmakeprojectmanager/qmakestep.cpp b/src/plugins/qmakeprojectmanager/qmakestep.cpp
index bdd2d6af6ab..98a168f9d38 100644
--- a/src/plugins/qmakeprojectmanager/qmakestep.cpp
+++ b/src/plugins/qmakeprojectmanager/qmakestep.cpp
@@ -129,7 +129,7 @@ QString QMakeStep::allArguments(bool shorted)
if (bc->subNodeBuild())
arguments << QDir::toNativeSeparators(bc->subNodeBuild()->path());
else if (shorted)
- arguments << project()->projectFilePath().toFileInfo().fileName();
+ arguments << project()->projectFilePath().fileName();
else
arguments << project()->projectFilePath().toUserOutput();
@@ -645,7 +645,7 @@ void QMakeStepConfigWidget::updateSummaryLabel()
// We don't want the full path to the .pro file
QString args = m_step->allArguments(true);
// And we only use the .pro filename not the full path
- QString program = qtVersion->qmakeCommand().toFileInfo().fileName();
+ QString program = qtVersion->qmakeCommand().fileName();
setSummaryText(tr("<b>qmake:</b> %1 %2").arg(program, args));
}
@@ -682,7 +682,7 @@ void QMakeStepConfigWidget::updateEffectiveQMakeCall()
QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(m_step->target()->kit());
QString program = tr("<No Qt version>");
if (qtVersion)
- program = qtVersion->qmakeCommand().toFileInfo().fileName();
+ program = qtVersion->qmakeCommand().fileName();
m_ui->qmakeArgumentsEdit->setPlainText(program + QLatin1Char(' ') + m_step->allArguments());
}
diff --git a/src/plugins/qmakeprojectmanager/qmakestep.ui b/src/plugins/qmakeprojectmanager/qmakestep.ui
index 721bc2d112a..aa659aa0664 100644
--- a/src/plugins/qmakeprojectmanager/qmakestep.ui
+++ b/src/plugins/qmakeprojectmanager/qmakestep.ui
@@ -156,7 +156,7 @@
<item row="3" column="0">
<widget class="QLabel" name="qtQuickCompilerLabel">
<property name="text">
- <string>Use QML compiler</string>
+ <string>Use QML compiler:</string>
</property>
</widget>
</item>
diff --git a/src/plugins/qmakeprojectmanager/wizards/abstractmobileappwizard.cpp b/src/plugins/qmakeprojectmanager/wizards/abstractmobileappwizard.cpp
index c9370546308..7efb103b153 100644
--- a/src/plugins/qmakeprojectmanager/wizards/abstractmobileappwizard.cpp
+++ b/src/plugins/qmakeprojectmanager/wizards/abstractmobileappwizard.cpp
@@ -131,11 +131,8 @@ bool AbstractMobileAppWizard::postGenerateFiles(const QWizard *w,
}
if (success) {
const QString fileToOpen = fileToOpenPostGeneration();
- if (!fileToOpen.isEmpty()) {
+ if (!fileToOpen.isEmpty())
EditorManager::openEditor(fileToOpen);
- Project *project = SessionManager::projectForFile(fileToOpen);
- ProjectExplorerPlugin::setCurrentFile(project, fileToOpen);
- }
}
return success;
}
diff --git a/src/plugins/qmakeprojectmanager/wizards/consoleappwizard.cpp b/src/plugins/qmakeprojectmanager/wizards/consoleappwizard.cpp
index 87a2f06baa6..e4d87e304c0 100644
--- a/src/plugins/qmakeprojectmanager/wizards/consoleappwizard.cpp
+++ b/src/plugins/qmakeprojectmanager/wizards/consoleappwizard.cpp
@@ -36,8 +36,9 @@
#include <cpptools/abstracteditorsupport.h>
#include <qtsupport/qtsupportconstants.h>
+#include <utils/fileutils.h>
+
#include <QCoreApplication>
-#include <QFileInfo>
#include <QTextStream>
static const char mainCppC[] =
@@ -98,7 +99,7 @@ Core::GeneratedFiles
QTextStream proStr(&contents);
QtProjectParameters::writeProFileHeader(proStr);
params.writeProFile(proStr);
- proStr << "\n\nSOURCES += " << QFileInfo(sourceFileName).fileName() << '\n';
+ proStr << "\n\nSOURCES += " << Utils::FileName::fromString(sourceFileName).fileName() << '\n';
}
profile.setContents(contents);
return Core::GeneratedFiles() << source << profile;
diff --git a/src/plugins/qmakeprojectmanager/wizards/guiappwizard.cpp b/src/plugins/qmakeprojectmanager/wizards/guiappwizard.cpp
index fda0e1192d4..d338bf3a297 100644
--- a/src/plugins/qmakeprojectmanager/wizards/guiappwizard.cpp
+++ b/src/plugins/qmakeprojectmanager/wizards/guiappwizard.cpp
@@ -44,7 +44,6 @@
#include <QCoreApplication>
#include <QDir>
#include <QTextStream>
-#include <QFileInfo>
#include <QSharedPointer>
static const char mainSourceFileC[] = "main";
@@ -195,11 +194,11 @@ Core::GeneratedFiles GuiAppWizard::generateFiles(const QWizard *w,
QTextStream proStr(&contents);
QtProjectParameters::writeProFileHeader(proStr);
projectParams.writeProFile(proStr);
- proStr << "\n\nSOURCES += " << QFileInfo(mainSourceFileName).fileName()
- << "\\\n " << QFileInfo(formSource.path()).fileName()
- << "\n\nHEADERS += " << QFileInfo(formHeader.path()).fileName();
+ proStr << "\n\nSOURCES += " << Utils::FileName::fromString(mainSourceFileName).fileName()
+ << "\\\n " << Utils::FileName::fromString(formSource.path()).fileName()
+ << "\n\nHEADERS += " << Utils::FileName::fromString(formHeader.path()).fileName();
if (params.designerForm)
- proStr << "\n\nFORMS += " << QFileInfo(form->path()).fileName();
+ proStr << "\n\nFORMS += " << Utils::FileName::fromString(form->path()).fileName();
if (params.isMobileApplication) {
proStr << "\n\nCONFIG += mobility"
<< "\nMOBILITY = "
@@ -221,9 +220,7 @@ bool GuiAppWizard::parametrizeTemplate(const QString &templatePath, const QStrin
const GuiAppParameters &params,
QString *target, QString *errorMessage)
{
- QString fileName = templatePath;
- fileName += QDir::separator();
- fileName += templateName;
+ const QString fileName = templatePath + QLatin1Char('/') + templateName;
Utils::FileReader reader;
if (!reader.fetch(fileName, QIODevice::Text, errorMessage))
return false;
diff --git a/src/plugins/qmakeprojectmanager/wizards/librarywizard.cpp b/src/plugins/qmakeprojectmanager/wizards/librarywizard.cpp
index 270ac51e7cf..ef75296057f 100644
--- a/src/plugins/qmakeprojectmanager/wizards/librarywizard.cpp
+++ b/src/plugins/qmakeprojectmanager/wizards/librarywizard.cpp
@@ -35,7 +35,8 @@
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtsupportconstants.h>
-#include <QFileInfo>
+#include <utils/fileutils.h>
+
#include <QTextStream>
#include <QCoreApplication>
@@ -96,12 +97,12 @@ Core::GeneratedFiles LibraryWizard::generateFiles(const QWizard *w,
source.setAttributes(Core::GeneratedFile::OpenEditorAttribute);
const QString headerFileFullName = buildFileName(projectPath, params.headerFileName, headerSuffix());
- const QString headerFileName = QFileInfo(headerFileFullName).fileName();
+ const QString headerFileName = Utils::FileName::fromString(headerFileFullName).fileName();
QString pluginJsonFileFullName;
QString pluginJsonFileName;
if (projectParams.type == QtProjectParameters::Qt4Plugin) {
pluginJsonFileFullName = buildFileName(projectPath, projectParams.fileName, QLatin1String("json"));
- pluginJsonFileName = QFileInfo(pluginJsonFileFullName).fileName();
+ pluginJsonFileName = Utils::FileName::fromString(pluginJsonFileFullName).fileName();
}
Core::GeneratedFile header(headerFileFullName);
@@ -111,7 +112,7 @@ Core::GeneratedFiles LibraryWizard::generateFiles(const QWizard *w,
if (projectParams.type == QtProjectParameters::SharedLibrary) {
const QString globalHeaderName = buildFileName(projectPath, projectParams.fileName.toLower() + QLatin1String(sharedHeaderPostfixC), headerSuffix());
Core::GeneratedFile globalHeader(globalHeaderName);
- globalHeaderFileName = QFileInfo(globalHeader.path()).fileName();
+ globalHeaderFileName = Utils::FileName::fromString(globalHeader.path()).fileName();
globalHeader.setContents(CppTools::AbstractEditorSupport::licenseTemplate(globalHeaderFileName)
+ LibraryParameters::generateSharedHeader(globalHeaderFileName, projectParams.fileName, sharedLibExportMacro));
rc.push_back(globalHeader);
@@ -138,7 +139,7 @@ Core::GeneratedFiles LibraryWizard::generateFiles(const QWizard *w,
QTextStream proStr(&profileContents);
QtProjectParameters::writeProFileHeader(proStr);
projectParams.writeProFile(proStr);
- proStr << "\nSOURCES += " << QFileInfo(source.path()).fileName()
+ proStr << "\nSOURCES += " << Utils::FileName::fromString(source.path()).fileName()
<< "\n\nHEADERS += " << headerFileName;
if (!globalHeaderFileName.isEmpty())
proStr << "\\\n " << globalHeaderFileName << '\n';
diff --git a/src/plugins/qmakeprojectmanager/wizards/qtprojectparameters.cpp b/src/plugins/qmakeprojectmanager/wizards/qtprojectparameters.cpp
index 54c17307bca..307e0a3bdfb 100644
--- a/src/plugins/qmakeprojectmanager/wizards/qtprojectparameters.cpp
+++ b/src/plugins/qmakeprojectmanager/wizards/qtprojectparameters.cpp
@@ -50,7 +50,7 @@ QString QtProjectParameters::projectPath() const
{
QString rc = path;
if (!rc.isEmpty())
- rc += QDir::separator();
+ rc += QLatin1Char('/');
rc += fileName;
return rc;
}
diff --git a/src/plugins/qmakeprojectmanager/wizards/testwizard.cpp b/src/plugins/qmakeprojectmanager/wizards/testwizard.cpp
index bb415285e66..f450ee78bd5 100644
--- a/src/plugins/qmakeprojectmanager/wizards/testwizard.cpp
+++ b/src/plugins/qmakeprojectmanager/wizards/testwizard.cpp
@@ -35,6 +35,7 @@
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/qtsupportconstants.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
@@ -175,7 +176,7 @@ Core::GeneratedFiles TestWizard::generateFiles(const QWizard *w, QString *errorM
QTextStream proStr(&contents);
QtProjectParameters::writeProFileHeader(proStr);
projectParams.writeProFile(proStr);
- proStr << "\n\nSOURCES += " << QFileInfo(sourceFilePath).fileName() << '\n'
+ proStr << "\n\nSOURCES += " << Utils::FileName::fromString(sourceFilePath).fileName() << '\n'
<< "DEFINES += SRCDIR=\\\\\\\"$$PWD/\\\\\\\"\n";
}
profile.setContents(contents);
diff --git a/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp b/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp
index f1296ab875c..1e346a2a47c 100644
--- a/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/crumblebar.cpp
@@ -65,7 +65,7 @@ static CrumbleBarInfo createCrumbleBarInfoFromModelNode(const ModelNode &modelNo
{
CrumbleBarInfo crumbleBarInfo;
crumbleBarInfo.displayName = componentIdForModelNode(modelNode);
- crumbleBarInfo.fileName = currentDesignDocument()->textEditor()->document()->filePath();
+ crumbleBarInfo.fileName = currentDesignDocument()->textEditor()->document()->filePath().toString();
crumbleBarInfo.modelNode = modelNode;
return crumbleBarInfo;
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
index 0a02216f56f..adeff1ded80 100644
--- a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
@@ -186,7 +186,7 @@ void toFront(const SelectionContext &selectionState)
maximumZ++;
node.setVariantProperty("z", maximumZ);
}
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -204,7 +204,7 @@ void toBack(const SelectionContext &selectionState)
node.setVariantProperty("z", minimumZ);
}
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -224,7 +224,7 @@ void raise(const SelectionContext &selectionState)
node.setVariantProperty("z", z);
}
}
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -245,7 +245,7 @@ void lower(const SelectionContext &selectionState)
node.setVariantProperty("z", z);
}
}
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -269,7 +269,7 @@ void setVisible(const SelectionContext &selectionState)
try {
selectionState.selectedModelNodes().first().variantProperty("visible").setValue(selectionState.toggled());
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -282,7 +282,7 @@ void setFillWidth(const SelectionContext &selectionState)
try {
selectionState.firstSelectedModelNode().variantProperty("Layout.fillWidth").setValue(selectionState.toggled());
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -295,7 +295,7 @@ void setFillHeight(const SelectionContext &selectionState)
try {
selectionState.firstSelectedModelNode().variantProperty("Layout.fillHeight").setValue(selectionState.toggled());
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -311,7 +311,7 @@ void resetSize(const SelectionContext &selectionState)
node.removeProperty("width");
node.removeProperty("height");
}
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -327,7 +327,7 @@ void resetPosition(const SelectionContext &selectionState)
node.removeProperty("x");
node.removeProperty("y");
}
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
@@ -392,7 +392,7 @@ void anchorsFill(const SelectionContext &selectionState)
}
transaction.commit();
- } catch (RewritingException &e) { //better save then sorry
+ } catch (const RewritingException &e) { //better save then sorry
e.showException();
}
}
diff --git a/src/plugins/qmldesigner/components/formeditor/dragtool.cpp b/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
index 20184a31468..0dbdacb3d93 100644
--- a/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
@@ -366,7 +366,7 @@ void DragTool::commitTransaction()
{
try {
m_rewriterTransaction.commit();
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
e.showException();
}
}
diff --git a/src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp b/src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp
index 3c92e73e061..24c4268b593 100644
--- a/src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp
+++ b/src/plugins/qmldesigner/components/importmanager/importmanagerview.cpp
@@ -250,7 +250,7 @@ void ImportManagerView::removeImport(const Import &import)
if (model())
model()->changeImports(QList<Import>(), QList<Import>() << import);
}
- catch (RewritingException &e) {
+ catch (const RewritingException &e) {
e.showException();
}
}
@@ -261,7 +261,7 @@ void ImportManagerView::addImport(const Import &import)
if (model())
model()->changeImports(QList<Import>() << import, QList<Import>());
}
- catch (RewritingException &e) {
+ catch (const RewritingException &e) {
e.showException();
}
}
diff --git a/src/plugins/qmldesigner/components/integration/designdocument.cpp b/src/plugins/qmldesigner/components/integration/designdocument.cpp
index 2a78ba94d0c..3dde05b2c27 100644
--- a/src/plugins/qmldesigner/components/integration/designdocument.cpp
+++ b/src/plugins/qmldesigner/components/integration/designdocument.cpp
@@ -41,7 +41,7 @@
#include <viewmanager.h>
#include <nodeinstanceview.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/session.h>
@@ -57,6 +57,8 @@
#include <QPlainTextEdit>
#include <QApplication>
+using namespace ProjectExplorer;
+
enum {
debug = false
};
@@ -194,25 +196,25 @@ QString DesignDocument::simplfiedDisplayName() const
return list.last();
}
-void DesignDocument::updateFileName(const QString & /*oldFileName*/, const QString &newFileName)
+void DesignDocument::updateFileName(const Utils::FileName & /*oldFileName*/, const Utils::FileName &newFileName)
{
if (m_documentModel)
- m_documentModel->setFileUrl(QUrl::fromLocalFile(newFileName));
+ m_documentModel->setFileUrl(QUrl::fromLocalFile(newFileName.toString()));
if (m_inFileComponentModel)
- m_inFileComponentModel->setFileUrl(QUrl::fromLocalFile(newFileName));
+ m_inFileComponentModel->setFileUrl(QUrl::fromLocalFile(newFileName.toString()));
- viewManager().setItemLibraryViewResourcePath(QFileInfo(newFileName).absolutePath());
+ viewManager().setItemLibraryViewResourcePath(newFileName.toFileInfo().absolutePath());
emit displayNameChanged(displayName());
}
QString DesignDocument::fileName() const
{
- return editor()->document()->filePath();
+ return editor()->document()->filePath().toString();
}
-ProjectExplorer::Kit *DesignDocument::currentKit() const
+Kit *DesignDocument::currentKit() const
{
return m_currentKit;
}
@@ -243,7 +245,7 @@ void DesignDocument::loadDocument(QPlainTextEdit *edit)
m_inFileComponentTextModifier.reset();
- updateFileName(QString(), fileName());
+ updateFileName(Utils::FileName(), Utils::FileName::fromString(fileName()));
m_documentLoaded = true;
}
@@ -352,7 +354,7 @@ void DesignDocument::deleteSelected()
QmlObjectNode(node).destroy();
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
e.showException();
}
}
@@ -515,7 +517,7 @@ void DesignDocument::paste()
}
view.setSelectedModelNodes(pastedNodeList);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
qWarning() << e.description(); //silent error
}
} else {
@@ -553,7 +555,7 @@ void DesignDocument::paste()
NodeMetaInfo::clearCache();
view.setSelectedModelNodes(QList<ModelNode>() << pastedNode);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
qWarning() << e.description(); //silent error
}
}
@@ -581,9 +583,8 @@ RewriterView *DesignDocument::rewriterView() const
void DesignDocument::setEditor(Core::IEditor *editor)
{
m_textEditor = editor;
- connect(editor->document(),
- SIGNAL(filePathChanged(QString,QString)),
- SLOT(updateFileName(QString,QString)));
+ connect(editor->document(), &Core::IDocument::filePathChanged,
+ this, &DesignDocument::updateFileName);
updateActiveQtVersion();
}
@@ -627,9 +628,9 @@ void DesignDocument::redo()
viewManager().resetPropertyEditorView();
}
-static bool isFileInProject(DesignDocument *designDocument, ProjectExplorer::Project *project)
+static bool isFileInProject(DesignDocument *designDocument, Project *project)
{
- foreach (const QString &fileNameInProject, project->files(ProjectExplorer::Project::ExcludeGeneratedFiles)) {
+ foreach (const QString &fileNameInProject, project->files(Project::ExcludeGeneratedFiles)) {
if (designDocument->fileName() == fileNameInProject)
return true;
}
@@ -637,13 +638,12 @@ static bool isFileInProject(DesignDocument *designDocument, ProjectExplorer::Pro
return false;
}
-static inline ProjectExplorer::Kit *getActiveKit(DesignDocument *designDocument)
+static inline Kit *getActiveKit(DesignDocument *designDocument)
{
- ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
- ProjectExplorer::Project *currentProject = projectExplorer->currentProject();
+ Project *currentProject = ProjectTree::currentProject();
if (!currentProject)
- currentProject = ProjectExplorer::SessionManager::projectForFile(designDocument->fileName());
+ currentProject = SessionManager::projectForFile(designDocument->fileName());
if (!currentProject)
return 0;
@@ -651,17 +651,20 @@ static inline ProjectExplorer::Kit *getActiveKit(DesignDocument *designDocument)
if (!isFileInProject(designDocument, currentProject))
return 0;
- designDocument->connect(projectExplorer, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)), designDocument, SLOT(updateActiveQtVersion()), Qt::UniqueConnection);
+ QObject::connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
+ designDocument, &DesignDocument::updateActiveQtVersion, Qt::UniqueConnection);
- designDocument->connect(currentProject, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)), designDocument, SLOT(updateActiveQtVersion()), Qt::UniqueConnection);
+ QObject::connect(currentProject, &Project::activeTargetChanged,
+ designDocument, &DesignDocument::updateActiveQtVersion, Qt::UniqueConnection);
- ProjectExplorer::Target *target = currentProject->activeTarget();
+ Target *target = currentProject->activeTarget();
if (!target)
return 0;
- designDocument->connect(target, SIGNAL(kitChanged()), designDocument, SLOT(updateActiveQtVersion()), Qt::UniqueConnection);
+ QObject::connect(target, &Target::kitChanged,
+ designDocument, &DesignDocument::updateActiveQtVersion, Qt::UniqueConnection);
return target->kit();
}
diff --git a/src/plugins/qmldesigner/components/integration/designdocument.h b/src/plugins/qmldesigner/components/integration/designdocument.h
index 0541158e4b1..d39f559d3ad 100644
--- a/src/plugins/qmldesigner/components/integration/designdocument.h
+++ b/src/plugins/qmldesigner/components/integration/designdocument.h
@@ -126,7 +126,7 @@ public slots:
void changeToMaster();
private slots:
- void updateFileName(const QString &oldFileName, const QString &newFileName);
+ void updateFileName(const Utils::FileName &oldFileName, const Utils::FileName &newFileName);
private: // functions
void changeToInFileComponentModel(ComponentTextModifier *textModifer);
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
index 6afde5e5e4d..863bb6e8591 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
@@ -330,7 +330,7 @@ void ItemLibraryWidget::setImportFilter(FilterChangeFlag flag)
QApplication::restoreOverrideCursor();
block = false;
m_filterFlag = flag;
- } catch (RewritingException &) {
+ } catch (const RewritingException &) {
QApplication::restoreOverrideCursor();
m_filterFlag = oldfilterFlag;
block = false;
diff --git a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
index 63ef92e9d35..b13caac1306 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
+++ b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
@@ -49,6 +49,8 @@
#include <QApplication>
#include <QPointF>
+#include <coreplugin/messagebox.h>
+
#include <QtDebug>
#define DISABLE_VISIBLE_PROPERTIES
@@ -344,7 +346,7 @@ void NavigatorTreeModel::updateItemRow(const ModelNode &node)
static void handleWrongId(QStandardItem *item, const ModelNode &modelNode, const QString &errorTitle, const QString &errorMessage, NavigatorTreeModel *treeModel)
{
- QMessageBox::warning(Core::ICore::dialogParent(), errorTitle, errorMessage);
+ Core::AsynchronousMessageBox::warning(errorTitle, errorMessage);
bool blockSingals = treeModel->blockItemChangedSignal(true);
item->setText(modelNode.id());
treeModel->blockItemChangedSignal(blockSingals);
@@ -632,7 +634,7 @@ void NavigatorTreeModel::moveNodesInteractive(NodeAbstractProperty &parentProper
}
}
}
- } catch (RewritingException &exception) { //better safe than sorry! There always might be cases where we fail
+ } catch (const RewritingException &exception) { //better safe than sorry! There always might be cases where we fail
exception.showException();
}
}
diff --git a/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp b/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp
index 4d30e8b3132..7e3ed1bd5b7 100644
--- a/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp
+++ b/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp
@@ -31,6 +31,8 @@
#include "pluginpath.h"
#include "pluginmanager.h"
+#include <utils/fileutils.h>
+
#include <iplugin.h>
#include <QLibrary>
#include <QPluginLoader>
@@ -41,7 +43,7 @@
#include <QObject>
#include <QDebug>
-enum { debug = 1 };
+enum { debug = 0 };
namespace QmlDesigner {
@@ -173,7 +175,7 @@ QStandardItem *PluginPath::createModelItem()
QStandardItem *failedCategory = 0;
const auto end = m_plugins.end();
for (auto it = m_plugins.begin(); it != end; ++it) {
- QStandardItem *pluginItem = new QStandardItem(QFileInfo(it->path).fileName());
+ QStandardItem *pluginItem = new QStandardItem(Utils::FileName::fromString(it->path).fileName());
if (instance(*it)) {
pluginItem->appendRow(new QStandardItem(QString::fromUtf8(it->instanceGuard->metaObject()->className())));
pathItem->appendRow(pluginItem);
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp
index 318212f3123..8ad80768fe7 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorview.cpp
@@ -46,10 +46,9 @@
#include <nodeabstractproperty.h>
#include <rewriterview.h>
-#include <qmldesignerwarning.h>
-
#include <coreplugin/icore.h>
#include <utils/fileutils.h>
+#include <coreplugin/messagebox.h>
#include <QCoreApplication>
#include <QDir>
@@ -58,7 +57,6 @@
#include <QDebug>
#include <QTimer>
#include <QShortcut>
-#include <QMessageBox>
#include <QApplication>
enum {
@@ -159,9 +157,9 @@ void PropertyEditorView::changeValue(const QString &name)
value->setValue(m_selectedNode.id());
m_locked = false;
if (!m_selectedNode.isValidId(newId))
- QmlDesignerWarning::show(tr("Invalid Id"), tr("%1 is an invalid id.").arg(newId));
+ Core::AsynchronousMessageBox::warning(tr("Invalid Id"), tr("%1 is an invalid id.").arg(newId));
else
- QmlDesignerWarning::show(tr("Invalid Id"), tr("%1 already exists.").arg(newId));
+ Core::AsynchronousMessageBox::warning(tr("Invalid Id"), tr("%1 already exists.").arg(newId));
}
return;
}
@@ -217,7 +215,7 @@ void PropertyEditorView::changeValue(const QString &name)
}
}
}
- catch (RewritingException &e) {
+ catch (const RewritingException &e) {
e.showException();
}
}
@@ -293,7 +291,7 @@ void PropertyEditorView::changeExpression(const QString &propertyName)
transaction.commit(); //committing in the try block
}
- catch (RewritingException &e) {
+ catch (const RewritingException &e) {
e.showException();
}
}
diff --git a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
index 9ec794d290a..b238302715b 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
@@ -300,6 +300,11 @@ bool QmlAnchorBindingProxy::hasParent()
return m_qmlItemNode.isValid() && m_qmlItemNode.hasNodeParent();
}
+bool QmlAnchorBindingProxy::isInLayout() const
+{
+ return false;
+}
+
bool QmlAnchorBindingProxy::isFilled()
{
return m_qmlItemNode.isValid()
diff --git a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h
index c85d0e41aad..77be3538e33 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.h
@@ -52,6 +52,7 @@ class QmlAnchorBindingProxy : public QObject
Q_PROPERTY(bool leftAnchored READ leftAnchored WRITE setLeftAnchor NOTIFY leftAnchorChanged)
Q_PROPERTY(bool rightAnchored READ rightAnchored WRITE setRightAnchor NOTIFY rightAnchorChanged)
Q_PROPERTY(bool hasParent READ hasParent NOTIFY parentChanged)
+ Q_PROPERTY(bool isInLayout READ isInLayout NOTIFY parentChanged)
Q_PROPERTY(QString topTarget READ topTarget WRITE setTopTarget NOTIFY topTargetChanged)
Q_PROPERTY(QString bottomTarget READ bottomTarget WRITE setBottomTarget NOTIFY bottomTargetChanged)
@@ -103,6 +104,8 @@ public:
bool hasParent();
bool isFilled();
+ bool isInLayout() const;
+
void removeTopAnchor();
void removeBottomAnchor();
void removeLeftAnchor();
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp
index b93d7ce2c33..654635ae34e 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp
@@ -31,16 +31,14 @@
#include "stateseditormodel.h"
#include "stateseditorview.h"
-#include <qmldesignerwarning.h>
-
#include <QDebug>
-#include <QMessageBox>
#include <nodelistproperty.h>
#include <modelnode.h>
#include <variantproperty.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
enum {
debug = false
@@ -178,10 +176,10 @@ void StatesEditorModel::renameState(int internalNodeId, const QString &newName)
return;
if (newName.isEmpty() ||! m_statesEditorView->validStateName(newName)) {
- QmlDesignerWarning::show(tr("Invalid state name"),
- newName.isEmpty() ?
- tr("The empty string as a name is reserved for the base state.") :
- tr("Name already used in another state"));
+ Core::AsynchronousMessageBox::warning(tr("Invalid state name"),
+ newName.isEmpty() ?
+ tr("The empty string as a name is reserved for the base state.") :
+ tr("Name already used in another state"));
} else {
m_statesEditorView->renameState(internalNodeId, newName);
}
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
index e435091abae..f7b92adced4 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
@@ -158,7 +158,7 @@ void StatesEditorView::removeState(int nodeId)
stateNode.destroy();
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
e.showException();
}
}
@@ -209,7 +209,7 @@ void StatesEditorView::addState()
model()->changeImports(QList<Import>() << Import::createLibraryImport("QtQuick", "1.0"), QList<Import>());
ModelNode newState = rootStateGroup().addState(newStateName);
setCurrentState(newState);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
e.showException();
}
}
@@ -304,7 +304,7 @@ void StatesEditorView::renameState(int internalNodeId, const QString &newName)
state.setName(newName);
setCurrentState(oldState);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
e.showException();
}
}
diff --git a/src/plugins/qmldesigner/componentsplugin/Controls/TabViewSpecifics.qml b/src/plugins/qmldesigner/componentsplugin/Controls/TabViewSpecifics.qml
index 70b867af49c..dd34c834e23 100644
--- a/src/plugins/qmldesigner/componentsplugin/Controls/TabViewSpecifics.qml
+++ b/src/plugins/qmldesigner/componentsplugin/Controls/TabViewSpecifics.qml
@@ -70,7 +70,7 @@ Column {
Label {
text: qsTr("Tabs visible")
- tooltip: qsTr("Determines the visibility of the the tab bar.")
+ tooltip: qsTr("Determines the visibility of the tab bar.")
}
SecondColumnLayout {
diff --git a/src/plugins/qmldesigner/componentsplugin/addtabdesigneraction.cpp b/src/plugins/qmldesigner/componentsplugin/addtabdesigneraction.cpp
index ee7bf62077c..c9fad661838 100644
--- a/src/plugins/qmldesigner/componentsplugin/addtabdesigneraction.cpp
+++ b/src/plugins/qmldesigner/componentsplugin/addtabdesigneraction.cpp
@@ -37,6 +37,8 @@
#include <QFileInfo>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
+
#include <documentmanager.h>
#include <nodemetainfo.h>
#include <modelnode.h>
@@ -115,7 +117,7 @@ void AddTabDesignerAction::addNewTab()
QString newFilePath = directoryPath +QStringLiteral("/") + tabName + QStringLiteral(".qml");
if (QFileInfo::exists(newFilePath)) {
- QMessageBox::warning(Core::ICore::mainWindow(), tr("Naming Error"), tr("Component already exists."));
+ Core::AsynchronousMessageBox::warning(tr("Naming Error"), tr("Component already exists."));
} else {
const QString sourceString = QStringLiteral("import QtQuick 2.1\nimport QtQuick.Controls 1.0\n\nItem {\n anchors.fill: parent\n}");
bool fileCreated = DocumentManager::createFile(newFilePath, sourceString);
diff --git a/src/plugins/qmldesigner/designercore/exceptions/exception.cpp b/src/plugins/qmldesigner/designercore/exceptions/exception.cpp
index 8331263c201..8f6ad5d04b3 100644
--- a/src/plugins/qmldesigner/designercore/exceptions/exception.cpp
+++ b/src/plugins/qmldesigner/designercore/exceptions/exception.cpp
@@ -36,9 +36,8 @@
#endif
#include <QCoreApplication>
-#include <QMessageBox>
-#include <qmldesignerwarning.h>
+#include <coreplugin/messagebox.h>
/*!
\defgroup CoreExceptions
@@ -156,7 +155,7 @@ QString Exception::description() const
void Exception::showException(const QString &title) const
{
QString composedTitle = title.isEmpty() ? QCoreApplication::translate("QmlDesigner", "Error") : title;
- QmlDesignerWarning::show(composedTitle, description());
+ Core::AsynchronousMessageBox::warning(composedTitle, description());
}
/*!
diff --git a/src/plugins/qmldesigner/designercore/include/rewriterview.h b/src/plugins/qmldesigner/designercore/include/rewriterview.h
index 64f918f70ed..9077cf4908b 100644
--- a/src/plugins/qmldesigner/designercore/include/rewriterview.h
+++ b/src/plugins/qmldesigner/designercore/include/rewriterview.h
@@ -84,7 +84,7 @@ public:
Error();
Error(const QmlJS::DiagnosticMessage &qmlError, const QUrl &document);
Error(const QString &shortDescription);
- Error(Exception *exception);
+ Error(const Exception *exception);
Type type() const
{ return m_type; }
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
index 442bcc4c776..93a0410307c 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
@@ -75,10 +75,10 @@
#include "qmldesignerplugin.h"
#include "puppetcreator.h"
-#include <qmldesignerwarning.h>
#include <coreplugin/icore.h>
#include <utils/hostosinfo.h>
+#include <coreplugin/messagebox.h>
#include <projectexplorer/kit.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/baseqtversion.h>
@@ -101,9 +101,9 @@ static bool hasQtQuick1(NodeInstanceView *nodeInstanceView)
static void showCannotConnectToPuppetWarningAndSwitchToEditMode()
{
- QmlDesignerWarning::show(QCoreApplication::translate("NodeInstanceServerProxy", "Cannot Connect to QML Emulation Layer (QML Puppet)"),
- QCoreApplication::translate("NodeInstanceServerProxy", "The executable of the QML emulation layer (QML Puppet) may not be responding. "
- "Switching to another kit might help."));
+ Core::AsynchronousMessageBox::warning(QCoreApplication::translate("NodeInstanceServerProxy", "Cannot Connect to QML Emulation Layer (QML Puppet)"),
+ QCoreApplication::translate("NodeInstanceServerProxy", "The executable of the QML emulation layer (QML Puppet) may not be responding. "
+ "Switching to another kit might help."));
QmlDesignerPlugin::instance()->switchToTextModeDeferred();
@@ -201,8 +201,8 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
}
} else {
- QmlDesignerWarning::show(tr("Cannot Start QML Emulation Layer (QML Puppet)"),
- tr("The executable of the QML emulation layer (QML Puppet) process cannot be started or does not respond."));
+ Core::AsynchronousMessageBox::warning(tr("Cannot Start QML Emulation Layer (QML Puppet)"),
+ tr("The executable of the QML emulation layer (QML Puppet) process cannot be started or does not respond."));
QmlDesignerPlugin::instance()->switchToTextModeDeferred();
}
@@ -385,7 +385,7 @@ void NodeInstanceServerProxy::processFinished(int exitCode, QProcess::ExitStatus
if (m_captureFileForTest.isOpen()) {
m_captureFileForTest.close();
m_captureFileForTest.remove();
- QMessageBox::warning(Core::ICore::dialogParent(), tr("QML Emulation Layer (QML Puppet) Crashed"),
+ Core::AsynchronousMessageBox::warning(tr("QML Emulation Layer (QML Puppet) Crashed"),
tr("You are recording a puppet stream and the emulations layer crashed. "
"It is recommended to reopen the Qt Quick Designer and start again."));
}
diff --git a/src/plugins/qmldesigner/designercore/instances/puppetcreator.cpp b/src/plugins/qmldesigner/designercore/instances/puppetcreator.cpp
index 258a4d62d18..d097ac81551 100644
--- a/src/plugins/qmldesigner/designercore/instances/puppetcreator.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/puppetcreator.cpp
@@ -41,13 +41,14 @@
#include <projectexplorer/kit.h>
#include <projectexplorer/toolchain.h>
#include <utils/environment.h>
+#include <coreplugin/messagebox.h>
#include <coreplugin/icore.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
#include <coreplugin/icore.h>
-#include <qmldesignerwarning.h>
+
#include <qmldesignerplugin.h>
#include <designersettings.h>
#include "puppetbuildprogressdialog.h"
@@ -229,19 +230,19 @@ bool PuppetCreator::build(const QString &qmlPuppetProjectFilePath) const
}
if (!buildSucceeded)
- QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "QML Emulation Layer (QML Puppet) Building was Unsuccessful"),
- QCoreApplication::translate("PuppetCreator",
+ Core::AsynchronousMessageBox::warning(QCoreApplication::translate("PuppetCreator", "QML Emulation Layer (QML Puppet) Building was Unsuccessful"),
+ QCoreApplication::translate("PuppetCreator",
"The QML emulation layer (QML Puppet) cannot be built. "
"The fallback emulation layer, which does not support all features, will be used."
));
}
} else {
- QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Qt Version is not supported"),
- QCoreApplication::translate("PuppetCreator",
- "The QML emulation layer (QML Puppet) cannot be built because the Qt version is too old "
- "or it cannot run natively on your computer. "
- "The fallback emulation layer, which does not support all features, will be used."
- ));
+ Core::AsynchronousMessageBox::warning(QCoreApplication::translate("PuppetCreator", "Qt Version is not supported"),
+ QCoreApplication::translate("PuppetCreator",
+ "The QML emulation layer (QML Puppet) cannot be built because the Qt version is too old "
+ "or it cannot run natively on your computer. "
+ "The fallback emulation layer, which does not support all features, will be used."
+ ));
}
return buildSucceeded;
@@ -249,13 +250,13 @@ bool PuppetCreator::build(const QString &qmlPuppetProjectFilePath) const
static void warnAboutInvalidKit()
{
- QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Kit is invalid"),
- QCoreApplication::translate("PuppetCreator",
- "The QML emulation layer (QML Puppet) cannot be built because the kit is not configured correctly. "
- "For example the compiler can be misconfigured. "
- "Fix the kit configuration and restart Qt Creator. "
- "Otherwise, the fallback emulation layer, which does not support all features, will be used."
- ));
+ Core::AsynchronousMessageBox::warning(QCoreApplication::translate("PuppetCreator", "Kit is invalid"),
+ QCoreApplication::translate("PuppetCreator",
+ "The QML emulation layer (QML Puppet) cannot be built because the kit is not configured correctly. "
+ "For example the compiler can be misconfigured. "
+ "Fix the kit configuration and restart Qt Creator. "
+ "Otherwise, the fallback emulation layer, which does not support all features, will be used."
+ ));
}
void PuppetCreator::createQml1PuppetExecutableIfMissing()
diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
index 7e1dc0edbfa..b55fdc6a40c 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
@@ -34,8 +34,7 @@
#include "metainforeader.h"
#include "iwidgetplugin.h"
-#include <qmldesignerwarning.h>
-
+#include <coreplugin/messagebox.h>
#include "pluginmanager/widgetpluginmanager.h"
@@ -97,10 +96,10 @@ void MetaInfoPrivate::parseItemLibraryDescriptions()
Internal::MetaInfoReader reader(*m_q);
try {
reader.readMetaInfoFile(plugin->metaInfo());
- } catch (InvalidMetaInfoException &e) {
+ } catch (const InvalidMetaInfoException &e) {
qWarning() << e.description();
const QString errorMessage = plugin->metaInfo() + QLatin1Char('\n') + QLatin1Char('\n') + reader.errors().join(QLatin1Char('\n'));
- QmlDesignerWarning::show(QCoreApplication::translate("QmlDesigner::Internal::MetaInfoPrivate", "Invalid meta info"),
+ Core::AsynchronousMessageBox::warning(QCoreApplication::translate("QmlDesigner::Internal::MetaInfoPrivate", "Invalid meta info"),
errorMessage);
}
}
diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
index 5150b0190e1..600ce22ea01 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
@@ -301,7 +301,7 @@ void MetaInfoReader::insertItemLibraryEntry()
try {
m_metaInfo.itemLibraryInfo()->addEntry(m_currentEntry, m_overwriteDuplicates);
- } catch (InvalidMetaInfoException &) {
+ } catch (const InvalidMetaInfoException &) {
addError(tr("Invalid or duplicate item library entry %1").arg(m_currentEntry.name()), currentSourceLocation());
}
}
diff --git a/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp b/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
index d31f038d78d..244c2080b9f 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
@@ -35,10 +35,9 @@
#include "model.h"
#include "metainforeader.h"
-#include <qmldesignerwarning.h>
-
#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
+#include <coreplugin/messagebox.h>
#include <QDir>
#include <QMessageBox>
@@ -236,11 +235,11 @@ void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool a
reader.setQualifcation(qualification);
try {
reader.readMetaInfoFile(metaInfoFile.absoluteFilePath(), true);
- } catch (InvalidMetaInfoException &e) {
+ } catch (const InvalidMetaInfoException &e) {
qWarning() << e.description();
const QString errorMessage = metaInfoFile.absoluteFilePath() + QLatin1Char('\n') + QLatin1Char('\n') + reader.errors().join(QLatin1Char('\n'));
- QmlDesignerWarning::show(QCoreApplication::translate("SubComponentManager::parseDirectory", "Invalid meta info"),
- errorMessage);
+ Core::AsynchronousMessageBox::warning(QCoreApplication::translate("SubComponentManager::parseDirectory", "Invalid meta info"),
+ errorMessage);
}
}
}
diff --git a/src/plugins/qmldesigner/designercore/model/model.cpp b/src/plugins/qmldesigner/designercore/model/model.cpp
index f2b4a8a21fc..b917bbbbcdf 100644
--- a/src/plugins/qmldesigner/designercore/model/model.cpp
+++ b/src/plugins/qmldesigner/designercore/model/model.cpp
@@ -157,7 +157,7 @@ void ModelPrivate::notifyImportsChanged(const QList<Import> &addedImports, const
try {
if (rewriterView())
rewriterView()->importsChanged(addedImports, removedImports);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -309,7 +309,7 @@ void ModelPrivate::changeNodeId(const InternalNode::Pointer& internalNodePointer
try {
notifyNodeIdChanged(internalNodePointer, id, oldId);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
throw InvalidIdException(__LINE__, __FUNCTION__, __FILE__, id, e.description());
}
}
@@ -337,7 +337,7 @@ void ModelPrivate::notifyAuxiliaryDataChanged(const InternalNodePointer &interna
ModelNode node(internalNode, model(), rewriterView());
rewriterView()->auxiliaryDataChanged(node, name, data);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -368,7 +368,7 @@ void ModelPrivate::notifyNodeSourceChanged(const InternalNodePointer &internalNo
ModelNode node(internalNode, model(), rewriterView());
rewriterView()->nodeSourceChanged(node, newNodeSource);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -397,7 +397,7 @@ void ModelPrivate::notifyRootNodeTypeChanged(const QString &type, int majorVersi
try {
if (rewriterView())
rewriterView()->rootNodeTypeChanged(type, majorVersion, minorVersion);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -443,7 +443,7 @@ void ModelPrivate::notifyInstancesCompleted(const QVector<ModelNode> &nodeVector
try {
if (rewriterView())
rewriterView()->instancesCompleted(toModelNodeVector(internalVector, rewriterView()));
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -481,7 +481,7 @@ void ModelPrivate::notifyInstancesInformationsChange(const QMultiHash<ModelNode,
try {
if (rewriterView())
rewriterView()->instanceInformationsChange(convertModelNodeInformationHash(informationChangeHash, rewriterView()));
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -508,7 +508,7 @@ void ModelPrivate::notifyInstancesRenderImageChanged(const QVector<ModelNode> &n
try {
if (rewriterView())
rewriterView()->instancesRenderImageChanged(toModelNodeVector(internalVector, rewriterView()));
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -535,7 +535,7 @@ void ModelPrivate::notifyInstancesPreviewImageChanged(const QVector<ModelNode> &
try {
if (rewriterView())
rewriterView()->instancesPreviewImageChanged(toModelNodeVector(internalVector, rewriterView()));
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -562,7 +562,7 @@ void ModelPrivate::notifyInstancesChildrenChanged(const QVector<ModelNode> &node
try {
if (rewriterView())
rewriterView()->instancesChildrenChanged(toModelNodeVector(internalVector, rewriterView()));
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -589,7 +589,7 @@ void ModelPrivate::notifyCurrentStateChanged(const ModelNode &node)
try {
if (rewriterView())
rewriterView()->currentStateChanged(ModelNode(node.internalNode(), model(), rewriterView()));
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -614,7 +614,7 @@ void ModelPrivate::notifyRewriterBeginTransaction()
try {
if (rewriterView())
rewriterView()->rewriterBeginTransaction();
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -639,7 +639,7 @@ void ModelPrivate::notifyRewriterEndTransaction()
try {
if (rewriterView())
rewriterView()->rewriterEndTransaction();
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -667,7 +667,7 @@ void ModelPrivate::notifyInstanceToken(const QString &token, int number, const Q
try {
if (rewriterView())
rewriterView()->instancesToken(token, number, toModelNodeVector(internalVector, rewriterView()));
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -694,7 +694,7 @@ void ModelPrivate::notifyCustomNotification(const AbstractView *senderView, cons
try {
if (rewriterView())
rewriterView()->customNotification(senderView, identifier, toModelNodeList(internalList, rewriterView()), data);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -727,7 +727,7 @@ void ModelPrivate::notifyPropertiesRemoved(const QList<PropertyPair> &propertyPa
rewriterView()->propertiesRemoved(propertyList);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -772,7 +772,7 @@ void ModelPrivate::notifyPropertiesAboutToBeRemoved(const QList<InternalProperty
rewriterView()->propertiesAboutToBeRemoved(propertyList);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -786,7 +786,7 @@ void ModelPrivate::notifyPropertiesAboutToBeRemoved(const QList<InternalProperty
}
try {
view->propertiesAboutToBeRemoved(propertyList);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -856,7 +856,7 @@ void ModelPrivate::notifyNodeCreated(const InternalNode::Pointer &newInternalNod
ModelNode createdNode(newInternalNodePointer, model(), rewriterView());
rewriterView()->nodeCreated(createdNode);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -886,7 +886,7 @@ void ModelPrivate::notifyNodeAboutToBeRemoved(const InternalNode::Pointer &inter
ModelNode modelNode(internalNodePointer, model(), rewriterView());
rewriterView()->nodeAboutToBeRemoved(modelNode);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -920,7 +920,7 @@ void ModelPrivate::notifyNodeRemoved(const InternalNodePointer &internalNodePoin
NodeAbstractProperty parentProperty(parentPropertyName, parentNodePointer, model(), rewriterView());
rewriterView()->nodeRemoved(modelNode, parentProperty, propertyChange);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -953,7 +953,7 @@ void ModelPrivate::notifyNodeIdChanged(const InternalNode::Pointer& internalNode
ModelNode modelNode(internalNodePointer, model(), rewriterView());
rewriterView()->nodeIdChanged(modelNode, newId, oldId);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -987,7 +987,7 @@ void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPro
}
rewriterView()->bindingPropertiesChanged(propertyList, propertyChange);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -1028,7 +1028,7 @@ void ModelPrivate::notifySignalHandlerPropertiesChanged(const QVector<InternalSi
}
rewriterView()->signalHandlerPropertiesChanged(propertyList, propertyChange);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -1065,7 +1065,7 @@ void ModelPrivate::notifyScriptFunctionsChanged(const InternalNodePointer &inter
ModelNode node(internalNodePointer, model(), rewriterView());
rewriterView()->scriptFunctionsChanged(node, scriptFunctionList);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -1106,7 +1106,7 @@ void ModelPrivate::notifyVariantPropertiesChanged(const InternalNodePointer &int
ModelNode node(internalNodePointer, model(), rewriterView());
rewriterView()->variantPropertiesChanged(propertyList, propertyChange);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -1163,7 +1163,7 @@ void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &intern
ModelNode modelNode(internalNodePointer, model(), rewriterView());
rewriterView()->nodeAboutToBeReparented(modelNode, newProperty, oldProperty, propertyChange);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -1224,7 +1224,7 @@ void ModelPrivate::notifyNodeReparent(const InternalNode::Pointer &internalNodeP
ModelNode node(internalNodePointer, model(), rewriterView());
rewriterView()->nodeReparented(node, newProperty, oldProperty, propertyChange);
}
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
@@ -1274,7 +1274,7 @@ void ModelPrivate::notifyNodeOrderChanged(const InternalNodeListPropertyPointer
rewriterView()->nodeOrderChanged(NodeListProperty(internalListPropertyPointer, model(), rewriterView()),
ModelNode(internalNodePointer, model(), rewriterView()),
oldIndex);
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
description = e.description();
resetModel = true;
}
diff --git a/src/plugins/qmldesigner/designercore/model/modelmerger.cpp b/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
index 620695a0720..79c4db6b0ce 100644
--- a/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
@@ -193,7 +193,7 @@ void ModelMerger::replaceModel(const ModelNode &modelNode)
syncNodeProperties(rootNode, modelNode, idRenamingHash, view());
syncNodeListProperties(rootNode, modelNode, idRenamingHash, view());
m_view->changeRootNodeType(modelNode.type(), modelNode.majorVersion(), modelNode.minorVersion());
- } catch (RewritingException &e) {
+ } catch (const RewritingException &e) {
qWarning() << e.description(); //silent error
}
}
diff --git a/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp b/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp
index 9c5d6d7f435..7a5a85c30ef 100644
--- a/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp
@@ -283,7 +283,7 @@ void ModelToTextMerger::applyChanges()
textModifier->commitGroup();
textModifier->reactivateChangeSignals();
- } catch (Exception &e) {
+ } catch (const Exception &e) {
m_rewriterView->enterErrorState(e.description());
qDeleteAll(m_rewriteActions);
diff --git a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
index d23724249d4..cd86d089dbc 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
@@ -154,7 +154,7 @@ QmlItemNode QmlItemNode::createQmlItemNode(AbstractView *view, const ItemLibrary
Q_ASSERT(newQmlItemNode.isValid());
}
- catch (RewritingException &e) {
+ catch (const RewritingException &e) {
e.showException();
}
diff --git a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
index 5de3e2a4659..b693440e394 100644
--- a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
+++ b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
@@ -56,7 +56,7 @@ RewriterView::Error::Error():
{
}
-RewriterView::Error::Error(Exception *exception):
+RewriterView::Error::Error(const Exception *exception):
m_type(InternalError),
m_line(exception->line()),
m_column(-1),
@@ -521,7 +521,7 @@ void RewriterView::applyChanges()
modelToTextMerger()->applyChanges();
if (!errors().isEmpty())
enterErrorState(errors().first().description());
- } catch (Exception &e) {
+ } catch (const Exception &e) {
const QString content = textModifierContent();
qDebug() << "RewriterException:" << m_rewritingErrorMessage;
qDebug() << "Content:" << content;
diff --git a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
index 15674f25a7d..6d3a3f2153f 100644
--- a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
@@ -966,7 +966,7 @@ bool TextToModelMerger::load(const QString &data, DifferenceHandler &differenceH
setActive(false);
return true;
- } catch (Exception &e) {
+ } catch (const Exception &e) {
RewriterView::Error error(&e);
// Somehow, the error below gets eaten in upper levels, so printing the
// exception info here for debugging purposes:
diff --git a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp
index dad6b6a6798..d0641f0c73a 100644
--- a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp
+++ b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp
@@ -30,6 +30,9 @@
#include "widgetpluginpath.h"
#include <iwidgetplugin.h>
+
+#include <utils/fileutils.h>
+
#include <QLibrary>
#include <QPluginLoader>
#include <QFileInfo>
@@ -192,7 +195,7 @@ QStandardItem *WidgetPluginPath::createModelItem()
QStandardItem *failedCategory = 0;
const auto end = m_plugins.end();
for (auto it = m_plugins.begin(); it != end; ++it) {
- QStandardItem *pluginItem = new QStandardItem(QFileInfo(it->path).fileName());
+ QStandardItem *pluginItem = new QStandardItem(Utils::FileName::fromString(it->path).fileName());
if (instance(*it)) {
pluginItem->appendRow(new QStandardItem(QString::fromUtf8(it->instanceGuard->metaObject()->className())));
pathItem->appendRow(pluginItem);
diff --git a/src/plugins/qmldesigner/designmodewidget.cpp b/src/plugins/qmldesigner/designmodewidget.cpp
index 32b68cbad83..ef73428d7c3 100644
--- a/src/plugins/qmldesigner/designmodewidget.cpp
+++ b/src/plugins/qmldesigner/designmodewidget.cpp
@@ -87,7 +87,7 @@ DocumentWarningWidget::DocumentWarningWidget(DesignModeWidget *parent) :
m_errorMessage->setForegroundRole(QPalette::ToolTipText);
m_goToError->setText(tr("<a href=\"goToError\">Go to error</a>"));
m_goToError->setForegroundRole(QPalette::Link);
- connect(m_goToError, SIGNAL(linkActivated(QString)), this, SLOT(goToError()));
+ connect(m_goToError, &QLabel::linkActivated, this, &DocumentWarningWidget::goToError);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(20);
@@ -405,8 +405,8 @@ void DesignModeWidget::setup()
m_toolBar->setToolbarCreationFlags(Core::EditorToolBar::FlagsStandalone);
m_toolBar->setNavigationVisible(true);
- connect(m_toolBar, SIGNAL(goForwardClicked()), this, SLOT(toolBarOnGoForwardClicked()));
- connect(m_toolBar, SIGNAL(goBackClicked()), this, SLOT(toolBarOnGoBackClicked()));
+ connect(m_toolBar, &Core::EditorToolBar::goForwardClicked, this, &DesignModeWidget::toolBarOnGoForwardClicked);
+ connect(m_toolBar, &Core::EditorToolBar::goBackClicked, this, &DesignModeWidget::toolBarOnGoBackClicked);
if (currentDesignDocument())
setupNavigatorHistory(currentDesignDocument()->textEditor());
@@ -509,7 +509,7 @@ void DesignModeWidget::resizeEvent(QResizeEvent *event)
void DesignModeWidget::setupNavigatorHistory(Core::IEditor *editor)
{
if (!m_keepNavigatorHistory)
- addNavigatorHistoryEntry(editor->document()->filePath());
+ addNavigatorHistoryEntry(editor->document()->filePath().toString());
const bool canGoBack = m_navigatorHistoryCounter > 0;
const bool canGoForward = m_navigatorHistoryCounter < (m_navigatorHistory.size() - 1);
diff --git a/src/plugins/qmldesigner/documentmanager.cpp b/src/plugins/qmldesigner/documentmanager.cpp
index 8b7e5dd9ba7..ccfe398f6c9 100644
--- a/src/plugins/qmldesigner/documentmanager.cpp
+++ b/src/plugins/qmldesigner/documentmanager.cpp
@@ -44,6 +44,7 @@
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/vcsmanager.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagebox.h>
#include <QMessageBox>
@@ -337,9 +338,8 @@ void DocumentManager::addFileToVersionControl(const QString &directoryPath, cons
Core::VcsManager::msgPromptToAddToVcs(QStringList(newFilePath), versionControl),
QMessageBox::Yes | QMessageBox::No);
if (button == QMessageBox::Yes && !versionControl->vcsAdd(newFilePath)) {
- QMessageBox::warning(Core::ICore::mainWindow(),
- Core::VcsManager::msgAddToVcsFailedTitle(),
- Core::VcsManager::msgToAddToVcsFailed(QStringList(newFilePath), versionControl));
+ Core::AsynchronousMessageBox::warning(Core::VcsManager::msgAddToVcsFailedTitle(),
+ Core::VcsManager::msgToAddToVcsFailed(QStringList(newFilePath), versionControl));
}
}
}
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.cpp b/src/plugins/qmldesigner/qmldesignerplugin.cpp
index baabb3bad01..e005475c0a0 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.cpp
+++ b/src/plugins/qmldesigner/qmldesignerplugin.cpp
@@ -366,7 +366,7 @@ static bool checkIfEditorIsQtQuick(Core::IEditor *editor)
if (editor)
if (editor && editor->document()->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID) {
QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
- QmlJS::Document::Ptr document = modelManager->ensuredGetDocumentForPath(editor->document()->filePath());
+ QmlJS::Document::Ptr document = modelManager->ensuredGetDocumentForPath(editor->document()->filePath().toString());
if (!document.isNull())
return document->language() == QmlJS::Dialect::QmlQtQuick1
|| document->language() == QmlJS::Dialect::QmlQtQuick2
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.pri b/src/plugins/qmldesigner/qmldesignerplugin.pri
index ebef4805160..7c52f0aaf49 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.pri
+++ b/src/plugins/qmldesigner/qmldesignerplugin.pri
@@ -6,8 +6,7 @@ HEADERS += $$PWD/qmldesignerconstants.h \
$$PWD/settingspage.h \
$$PWD/designmodecontext.h \
$$PWD/documentmanager.h \
- $$PWD/styledoutputpaneplaceholder.h \
- $$PWD/qmldesignerwarning.h
+ $$PWD/styledoutputpaneplaceholder.h
SOURCES += $$PWD/qmldesignerplugin.cpp \
$$PWD/shortcutmanager.cpp \
@@ -16,7 +15,6 @@ SOURCES += $$PWD/qmldesignerplugin.cpp \
$$PWD/settingspage.cpp \
$$PWD/designmodecontext.cpp \
$$PWD/documentmanager.cpp \
- $$PWD/styledoutputpaneplaceholder.cpp \
- $$PWD/qmldesignerwarning.cpp
+ $$PWD/styledoutputpaneplaceholder.cpp
FORMS += $$PWD/settingspage.ui
diff --git a/src/plugins/qmldesigner/settingspage.cpp b/src/plugins/qmldesigner/settingspage.cpp
index 6b82b64b48e..51a66ae6ae3 100644
--- a/src/plugins/qmldesigner/settingspage.cpp
+++ b/src/plugins/qmldesigner/settingspage.cpp
@@ -45,7 +45,8 @@ SettingsPageWidget::SettingsPageWidget(QWidget *parent) :
QWidget(parent)
{
m_ui.setupUi(this);
- connect(m_ui.designerEnableDebuggerCheckBox, SIGNAL(toggled(bool)), this, SLOT(debugViewEnabledToggled(bool)));
+ connect(m_ui.designerEnableDebuggerCheckBox, &QCheckBox::toggled,
+ this, &SettingsPageWidget::debugViewEnabledToggled);
}
DesignerSettings SettingsPageWidget::settings() const
diff --git a/src/plugins/qmljseditor/qmljscompletionassist.cpp b/src/plugins/qmljseditor/qmljscompletionassist.cpp
index cda348ed767..1fe4a5dfc6e 100644
--- a/src/plugins/qmljseditor/qmljscompletionassist.cpp
+++ b/src/plugins/qmljseditor/qmljscompletionassist.cpp
@@ -54,7 +54,7 @@
#include <qmljs/qmljscompletioncontextfinder.h>
#include <qmljs/qmljsbundle.h>
#include <qmljs/qmljsscopebuilder.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <QFile>
#include <QFileInfo>
@@ -652,7 +652,7 @@ IAssistProposal *QmlJSCompletionAssistProcessor::perform(const AssistInterface *
// currently path-in-stringliteral is the only completion available in imports
if (contextFinder.isInImport()) {
QmlJS::ModelManagerInterface::ProjectInfo pInfo = QmlJS::ModelManagerInterface::instance()
- ->projectInfo(ProjectExplorer::ProjectExplorerPlugin::currentProject());
+ ->projectInfo(ProjectExplorer::ProjectTree::currentProject());
QmlBundle platform = pInfo.extendedBundle.bundleForLanguage(document->language());
if (!platform.supportedImports().isEmpty()) {
QTextCursor tc(qmlInterface->textDocument());
@@ -914,13 +914,10 @@ bool QmlJSCompletionAssistProcessor::completeFileName(const QString &relativeBas
{
const QFileInfo fileInfo(fileName);
QString directoryPrefix;
- if (fileInfo.isRelative()) {
- directoryPrefix = relativeBasePath;
- directoryPrefix += QDir::separator();
- directoryPrefix += fileInfo.path();
- } else {
+ if (fileInfo.isRelative())
+ directoryPrefix = relativeBasePath + QLatin1Char('/') + fileInfo.path();
+ else
directoryPrefix = fileInfo.path();
- }
if (!QFileInfo::exists(directoryPrefix))
return false;
diff --git a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
index ab46365cc2b..7f8d208fa1c 100644
--- a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
+++ b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
@@ -106,7 +106,7 @@ public:
if (componentName.isEmpty() || path.isEmpty())
return;
- const QString newFileName = path + QDir::separator() + componentName
+ const QString newFileName = path + QLatin1Char('/') + componentName
+ QLatin1String(".qml");
QString imports;
diff --git a/src/plugins/qmljseditor/qmljseditor.cpp b/src/plugins/qmljseditor/qmljseditor.cpp
index 72ac9e33e05..100f8386f51 100644
--- a/src/plugins/qmljseditor/qmljseditor.cpp
+++ b/src/plugins/qmljseditor/qmljseditor.cpp
@@ -224,7 +224,7 @@ void QmlJSEditorWidget::updateCodeWarnings(QmlJS::Document::Ptr doc)
void QmlJSEditorWidget::modificationChanged(bool changed)
{
if (!changed && m_modelManager)
- m_modelManager->fileChangedOnDisk(textDocument()->filePath());
+ m_modelManager->fileChangedOnDisk(textDocument()->filePath().toString());
}
void QmlJSEditorWidget::jumpToOutlineElement(int /*index*/)
@@ -641,12 +641,12 @@ TextEditorWidget::Link QmlJSEditorWidget::findLinkAt(const QTextCursor &cursor,
void QmlJSEditorWidget::findUsages()
{
- m_findReferences->findUsages(textDocument()->filePath(), textCursor().position());
+ m_findReferences->findUsages(textDocument()->filePath().toString(), textCursor().position());
}
void QmlJSEditorWidget::renameUsages()
{
- m_findReferences->renameUsages(textDocument()->filePath(), textCursor().position());
+ m_findReferences->renameUsages(textDocument()->filePath().toString(), textCursor().position());
}
void QmlJSEditorWidget::showContextPane()
@@ -846,7 +846,7 @@ AssistInterface *QmlJSEditorWidget::createAssistInterface(
if (assistKind == TextEditor::Completion) {
return new QmlJSCompletionAssistInterface(document(),
position(),
- textDocument()->filePath(),
+ textDocument()->filePath().toString(),
reason,
m_qmlJsEditorDocument->semanticInfo());
} else if (assistKind == TextEditor::QuickFix) {
diff --git a/src/plugins/qmljseditor/qmljseditordocument.cpp b/src/plugins/qmljseditor/qmljseditordocument.cpp
index 7a03122e089..cf81dd9a4f3 100644
--- a/src/plugins/qmljseditor/qmljseditordocument.cpp
+++ b/src/plugins/qmljseditor/qmljseditordocument.cpp
@@ -451,7 +451,7 @@ QmlJSEditorDocumentPrivate::QmlJSEditorDocumentPrivate(QmlJSEditorDocument *pare
m_updateOutlineModelTimer.setSingleShot(true);
connect(&m_updateOutlineModelTimer, SIGNAL(timeout()), this, SLOT(updateOutlineModel()));
- modelManager->updateSourceFiles(QStringList(parent->filePath()), false);
+ modelManager->updateSourceFiles(QStringList(parent->filePath().toString()), false);
}
QmlJSEditorDocumentPrivate::~QmlJSEditorDocumentPrivate()
@@ -468,13 +468,13 @@ void QmlJSEditorDocumentPrivate::invalidateFormatterCache()
void QmlJSEditorDocumentPrivate::reparseDocument()
{
- ModelManagerInterface::instance()->updateSourceFiles(QStringList() << q->filePath(),
- false);
+ ModelManagerInterface::instance()->updateSourceFiles(QStringList(q->filePath().toString()),
+ false);
}
void QmlJSEditorDocumentPrivate::onDocumentUpdated(Document::Ptr doc)
{
- if (q->filePath() != doc->fileName())
+ if (q->filePath().toString() != doc->fileName())
return;
// text document has changed, simply wait for the next onDocumentUpdated
diff --git a/src/plugins/qmljseditor/qmljshoverhandler.cpp b/src/plugins/qmljseditor/qmljshoverhandler.cpp
index 2c573ff8f6d..981ef133347 100644
--- a/src/plugins/qmljseditor/qmljshoverhandler.cpp
+++ b/src/plugins/qmljseditor/qmljshoverhandler.cpp
@@ -49,7 +49,6 @@
#include <texteditor/texteditor.h>
#include <texteditor/helpitem.h>
#include <utils/tooltip/tooltip.h>
-#include <utils/tooltip/tipcontents.h>
#include <QDir>
#include <QList>
@@ -373,9 +372,9 @@ void QmlJSHoverHandler::operateTooltip(TextEditorWidget *editorWidget, const QPo
if (toolTip().isEmpty())
Utils::ToolTip::hide();
else if (m_colorTip.isValid())
- Utils::ToolTip::show(point, Utils::ColorContent(m_colorTip), editorWidget);
+ Utils::ToolTip::show(point, m_colorTip, editorWidget);
else
- Utils::ToolTip::show(point, Utils::TextContent(toolTip()), editorWidget);
+ Utils::ToolTip::show(point, toolTip(), editorWidget);
}
void QmlJSHoverHandler::prettyPrintTooltip(const QmlJS::Value *value,
diff --git a/src/plugins/qmljseditor/qmljsoutline.cpp b/src/plugins/qmljseditor/qmljsoutline.cpp
index 04e01841e82..bfcfa4312f8 100644
--- a/src/plugins/qmljseditor/qmljsoutline.cpp
+++ b/src/plugins/qmljseditor/qmljsoutline.cpp
@@ -160,19 +160,17 @@ void QmlJSOutlineWidget::setCursorSynchronization(bool syncWithCursor)
updateSelectionInTree(m_editor->outlineModelIndex());
}
-void QmlJSOutlineWidget::restoreSettings(int position)
+void QmlJSOutlineWidget::restoreSettings(const QVariantMap &map)
{
- QSettings *settings = Core::ICore::settings();
- bool showBindings = settings->value(
- QString::fromLatin1("QmlJSOutline.%1.ShowBindings").arg(position), true).toBool();
+ bool showBindings = map.value(QString::fromLatin1("QmlJSOutline.ShowBindings"), true).toBool();
m_showBindingsAction->setChecked(showBindings);
}
-void QmlJSOutlineWidget::saveSettings(int position)
+QVariantMap QmlJSOutlineWidget::settings() const
{
- QSettings *settings = Core::ICore::settings();
- settings->setValue(QString::fromLatin1("QmlJSOutline.%1.ShowBindings").arg(position),
- m_showBindingsAction->isChecked());
+ QVariantMap map;
+ map.insert(QLatin1String("QmlJSOutline.ShowBindings"), m_showBindingsAction->isChecked());
+ return map;
}
void QmlJSOutlineWidget::modelUpdated()
diff --git a/src/plugins/qmljseditor/qmljsoutline.h b/src/plugins/qmljseditor/qmljsoutline.h
index 72f8c9a486b..6ac1920a58c 100644
--- a/src/plugins/qmljseditor/qmljsoutline.h
+++ b/src/plugins/qmljseditor/qmljsoutline.h
@@ -74,8 +74,8 @@ public:
// IOutlineWidget
virtual QList<QAction*> filterMenuActions() const;
virtual void setCursorSynchronization(bool syncWithCursor);
- virtual void restoreSettings(int position);
- virtual void saveSettings(int position);
+ virtual void restoreSettings(const QVariantMap &map);
+ virtual QVariantMap settings() const;
private slots:
void modelUpdated();
diff --git a/src/plugins/qmljseditor/qmljsquickfixassist.cpp b/src/plugins/qmljseditor/qmljsquickfixassist.cpp
index 8e750d2166c..b95fb6ae1d6 100644
--- a/src/plugins/qmljseditor/qmljsquickfixassist.cpp
+++ b/src/plugins/qmljseditor/qmljsquickfixassist.cpp
@@ -50,7 +50,7 @@ using namespace Internal;
QmlJSQuickFixAssistInterface::QmlJSQuickFixAssistInterface(QmlJSEditorWidget *editor,
TextEditor::AssistReason reason)
: AssistInterface(editor->document(), editor->position(),
- editor->textDocument()->filePath(), reason)
+ editor->textDocument()->filePath().toString(), reason)
, m_semanticInfo(editor->qmlJsEditorDocument()->semanticInfo())
, m_currentFile(QmlJSRefactoringChanges::file(editor, m_semanticInfo.document))
{}
diff --git a/src/plugins/qmljseditor/qmloutlinemodel.cpp b/src/plugins/qmljseditor/qmloutlinemodel.cpp
index 1efff1cb65b..8fbc0845f86 100644
--- a/src/plugins/qmljseditor/qmloutlinemodel.cpp
+++ b/src/plugins/qmljseditor/qmloutlinemodel.cpp
@@ -336,7 +336,7 @@ QMimeData *QmlOutlineModel::mimeData(const QModelIndexList &indexes) const
QModelIndex index = indexes.at(i);
AST::SourceLocation location = sourceLocation(index);
- data->addFile(m_editorDocument->filePath(), location.startLine,
+ data->addFile(m_editorDocument->filePath().toString(), location.startLine,
location.startColumn - 1 /*editors have 0-based column*/);
QList<int> rowPath;
diff --git a/src/plugins/qmljstools/qmlconsoleitemdelegate.cpp b/src/plugins/qmljstools/qmlconsoleitemdelegate.cpp
index 7939c0b9881..d42af3cd212 100644
--- a/src/plugins/qmljstools/qmlconsoleitemdelegate.cpp
+++ b/src/plugins/qmljstools/qmlconsoleitemdelegate.cpp
@@ -313,7 +313,8 @@ QWidget *QmlConsoleItemDelegate::createEditor(QWidget *parent,
{
QmlConsoleEdit *editor = new QmlConsoleEdit(index, parent);
- connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
+ connect(editor, &QmlConsoleEdit::editingFinished,
+ this, &QmlConsoleItemDelegate::commitAndCloseEditor);
return editor;
}
diff --git a/src/plugins/qmljstools/qmlconsolepane.cpp b/src/plugins/qmljstools/qmlconsolepane.cpp
index a49f9c17752..8b660d9c405 100644
--- a/src/plugins/qmljstools/qmlconsolepane.cpp
+++ b/src/plugins/qmljstools/qmlconsolepane.cpp
@@ -73,22 +73,23 @@ QmlConsolePane::QmlConsolePane(QObject *parent)
m_proxyModel = new QmlConsoleProxyModel(this);
m_proxyModel->setSourceModel(QmlConsoleModel::qmlConsoleItemModel());
connect(QmlConsoleModel::qmlConsoleItemModel(),
- SIGNAL(selectEditableRow(QModelIndex,QItemSelectionModel::SelectionFlags)),
+ &QmlConsoleItemModel::selectEditableRow,
m_proxyModel,
- SLOT(selectEditableRow(QModelIndex,QItemSelectionModel::SelectionFlags)));
+ &QmlConsoleProxyModel::selectEditableRow);
//Scroll to bottom when rows matching current filter settings are inserted
//Not connecting rowsRemoved as the only way to remove rows is to clear the
//model which will automatically reset the view.
- connect(QmlConsoleModel::qmlConsoleItemModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
- m_proxyModel, SLOT(onRowsInserted(QModelIndex,int,int)));
+ connect(QmlConsoleModel::qmlConsoleItemModel(), &QAbstractItemModel::rowsInserted,
+ m_proxyModel, &QmlConsoleProxyModel::onRowsInserted);
m_consoleView->setModel(m_proxyModel);
connect(m_proxyModel,
SIGNAL(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)),
m_consoleView->selectionModel(),
SLOT(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)));
- connect(m_proxyModel, SIGNAL(scrollToBottom()), m_consoleView, SLOT(onScrollToBottom()));
+ connect(m_proxyModel, &QmlConsoleProxyModel::scrollToBottom,
+ m_consoleView, &QmlConsoleView::onScrollToBottom);
m_itemDelegate = new QmlConsoleItemDelegate(this);
connect(m_consoleView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
@@ -111,7 +112,8 @@ QmlConsolePane::QmlConsolePane(QObject *parent)
m_showDebugButtonAction->setToolTip(tr("Show debug, log, and info messages."));
m_showDebugButtonAction->setCheckable(true);
m_showDebugButtonAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_INFO)));
- connect(m_showDebugButtonAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowLogs(bool)));
+ connect(m_showDebugButtonAction, &Utils::SavedAction::toggled,
+ m_proxyModel, &QmlConsoleProxyModel::setShowLogs);
m_showDebugButton->setDefaultAction(m_showDebugButtonAction);
m_showWarningButton = new QToolButton(m_consoleWidget);
@@ -123,8 +125,8 @@ QmlConsolePane::QmlConsolePane(QObject *parent)
m_showWarningButtonAction->setToolTip(tr("Show warning messages."));
m_showWarningButtonAction->setCheckable(true);
m_showWarningButtonAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_WARNING)));
- connect(m_showWarningButtonAction, SIGNAL(toggled(bool)), m_proxyModel,
- SLOT(setShowWarnings(bool)));
+ connect(m_showWarningButtonAction, &Utils::SavedAction::toggled,
+ m_proxyModel, &QmlConsoleProxyModel::setShowWarnings);
m_showWarningButton->setDefaultAction(m_showWarningButtonAction);
m_showErrorButton = new QToolButton(m_consoleWidget);
@@ -136,8 +138,7 @@ QmlConsolePane::QmlConsolePane(QObject *parent)
m_showErrorButtonAction->setToolTip(tr("Show error messages."));
m_showErrorButtonAction->setCheckable(true);
m_showErrorButtonAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_ERROR)));
- connect(m_showErrorButtonAction, SIGNAL(toggled(bool)), m_proxyModel,
- SLOT(setShowErrors(bool)));
+ connect(m_showErrorButtonAction, &Utils::SavedAction::toggled, m_proxyModel, &QmlConsoleProxyModel::setShowErrors);
m_showErrorButton->setDefaultAction(m_showErrorButtonAction);
m_spacer = new QWidget(m_consoleWidget);
diff --git a/src/plugins/qmljstools/qmlconsoleview.cpp b/src/plugins/qmljstools/qmlconsoleview.cpp
index b2bfd120d09..0d97940ed3f 100644
--- a/src/plugins/qmljstools/qmlconsoleview.cpp
+++ b/src/plugins/qmljstools/qmlconsoleview.cpp
@@ -129,7 +129,7 @@ QmlConsoleView::QmlConsoleView(QWidget *parent) :
horizontalScrollBar()->setSingleStep(20);
verticalScrollBar()->setSingleStep(20);
- connect(this, SIGNAL(activated(QModelIndex)), SLOT(onRowActivated(QModelIndex)));
+ connect(this, &QmlConsoleView::activated, this, &QmlConsoleView::onRowActivated);
}
void QmlConsoleView::onScrollToBottom()
diff --git a/src/plugins/qmljstools/qmljscodestylesettingspage.cpp b/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
index 1cb0d82f834..27c9f891380 100644
--- a/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
+++ b/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
@@ -88,8 +88,8 @@ void QmlJSCodeStylePreferencesWidget::setPreferences(TextEditor::ICodeStylePrefe
m_preferences = preferences;
m_ui->tabPreferencesWidget->setPreferences(preferences);
if (m_preferences)
- connect(m_preferences, SIGNAL(currentTabSettingsChanged(TextEditor::TabSettings)),
- this, SLOT(slotSettingsChanged()));
+ connect(m_preferences, &TextEditor::ICodeStylePreferences::currentTabSettingsChanged,
+ this, &QmlJSCodeStylePreferencesWidget::slotSettingsChanged);
updatePreview();
}
diff --git a/src/plugins/qmljstools/qmljslocatordata.cpp b/src/plugins/qmljstools/qmljslocatordata.cpp
index 82f5425603c..2fad7753306 100644
--- a/src/plugins/qmljstools/qmljslocatordata.cpp
+++ b/src/plugins/qmljstools/qmljslocatordata.cpp
@@ -35,7 +35,6 @@
//#include <qmljs/qmljsinterpreter.h>
#include <qmljs/parser/qmljsast_p.h>
-#include <QFileInfo>
#include <QMutexLocker>
using namespace QmlJSTools::Internal;
@@ -47,10 +46,10 @@ LocatorData::LocatorData(QObject *parent)
{
QmlJS::ModelManagerInterface *manager = QmlJS::ModelManagerInterface::instance();
- connect(manager, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
- this, SLOT(onDocumentUpdated(QmlJS::Document::Ptr)));
- connect(manager, SIGNAL(aboutToRemoveFiles(QStringList)),
- this, SLOT(onAboutToRemoveFiles(QStringList)));
+ connect(manager, &QmlJS::ModelManagerInterface::documentUpdated,
+ this, &LocatorData::onDocumentUpdated);
+ connect(manager, &QmlJS::ModelManagerInterface::aboutToRemoveFiles,
+ this, &LocatorData::onAboutToRemoveFiles);
}
LocatorData::~LocatorData()
@@ -75,7 +74,7 @@ public:
if (!doc->componentName().isEmpty())
m_documentContext = doc->componentName();
else
- m_documentContext = QFileInfo(doc->fileName()).fileName();
+ m_documentContext = Utils::FileName::fromString(doc->fileName()).fileName();
accept(doc->ast(), m_documentContext);
return m_entries;
}
diff --git a/src/plugins/qmljstools/qmljsmodelmanager.cpp b/src/plugins/qmljstools/qmljsmodelmanager.cpp
index 2fcb3d3413f..8fc7fb4796d 100644
--- a/src/plugins/qmljstools/qmljsmodelmanager.cpp
+++ b/src/plugins/qmljstools/qmljsmodelmanager.cpp
@@ -40,7 +40,8 @@
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <qmljs/qmljsbind.h>
@@ -222,10 +223,10 @@ void ModelManager::delayedInitialization()
this, SLOT(maybeQueueCppQmlTypeUpdate(CPlusPlus::Document::Ptr)), Qt::DirectConnection);
}
- connect(ProjectExplorer::SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)),
- this, SLOT(removeProjectInfo(ProjectExplorer::Project*)));
- connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
- SLOT(updateDefaultProjectInfo()));
+ connect(ProjectExplorer::SessionManager::instance(), &ProjectExplorer::SessionManager::projectRemoved,
+ this, &ModelManager::removeProjectInfo);
+ connect(ProjectExplorer::SessionManager::instance(), &ProjectExplorer::SessionManager::startupProjectChanged,
+ this, &ModelManager::updateDefaultProjectInfo);
QmlJS::ViewerContext qbsVContext;
qbsVContext.language = Dialect::QmlQbs;
@@ -250,7 +251,7 @@ ModelManagerInterface::WorkingCopy ModelManager::workingCopyInternal() const
{
WorkingCopy workingCopy;
foreach (IDocument *document, DocumentModel::openedDocuments()) {
- const QString key = document->filePath();
+ const QString key = document->filePath().toString();
if (TextEditor::TextDocument *textDocument = qobject_cast<TextEditor::TextDocument *>(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))
@@ -263,8 +264,8 @@ ModelManagerInterface::WorkingCopy ModelManager::workingCopyInternal() const
void ModelManager::updateDefaultProjectInfo()
{
- // needs to be performed in the ui therad
- ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ // needs to be performed in the ui thread
+ ProjectExplorer::Project *currentProject = ProjectExplorer::SessionManager::startupProject();
ProjectInfo newDefaultProjectInfo = projectInfo(currentProject,
defaultProjectInfoForProject(currentProject));
setDefaultProject(projectInfo(currentProject,newDefaultProjectInfo), currentProject);
diff --git a/src/plugins/qmljstools/qmljstoolsplugin.cpp b/src/plugins/qmljstools/qmljstoolsplugin.cpp
index f17aa0589e6..114fabed712 100644
--- a/src/plugins/qmljstools/qmljstoolsplugin.cpp
+++ b/src/plugins/qmljstools/qmljstoolsplugin.cpp
@@ -108,7 +108,8 @@ bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
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()));
+ connect(m_resetCodeModelAction, &QAction::triggered,
+ m_modelManager, &ModelManager::resetCodeModel);
mqmljstools->addAction(cmd);
// watch task progress
diff --git a/src/plugins/qmlprofiler/abstracttimelinemodel.cpp b/src/plugins/qmlprofiler/abstracttimelinemodel.cpp
deleted file mode 100644
index 7bc39fb2271..00000000000
--- a/src/plugins/qmlprofiler/abstracttimelinemodel.cpp
+++ /dev/null
@@ -1,299 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "abstracttimelinemodel.h"
-#include "abstracttimelinemodel_p.h"
-
-namespace QmlProfiler {
-
-AbstractTimelineModel::AbstractTimelineModel(AbstractTimelineModelPrivate *dd,
- const QString &displayName, QmlDebug::Message message, QmlDebug::RangeType rangeType,
- QObject *parent) :
- SortedTimelineModel(parent), d_ptr(dd)
-{
- Q_D(AbstractTimelineModel);
- connect(this,SIGNAL(rowHeightChanged()),this,SIGNAL(heightChanged()));
- connect(this,SIGNAL(expandedChanged()),this,SIGNAL(heightChanged()));
- connect(this,SIGNAL(hiddenChanged()),this,SIGNAL(heightChanged()));
-
- d->q_ptr = this;
- d->modelId = 0;
- d->modelManager = 0;
- d->expanded = false;
- d->hidden = false;
- d->displayName = displayName;
- d->message = message;
- d->rangeType = rangeType;
- d->expandedRowCount = 1;
- d->collapsedRowCount = 1;
-}
-
-AbstractTimelineModel::~AbstractTimelineModel()
-{
- Q_D(AbstractTimelineModel);
- delete d;
-}
-
-void AbstractTimelineModel::setModelManager(QmlProfilerModelManager *modelManager)
-{
- Q_D(AbstractTimelineModel);
- d->modelManager = modelManager;
- connect(d->modelManager->qmlModel(),SIGNAL(changed()),this,SLOT(dataChanged()));
- d->modelId = d->modelManager->registerModelProxy();
- d->modelManager->announceFeatures(d->modelId, features());
-}
-
-bool AbstractTimelineModel::isEmpty() const
-{
- return count() == 0;
-}
-
-int AbstractTimelineModel::modelId() const
-{
- Q_D(const AbstractTimelineModel);
- return d->modelId;
-}
-
-int AbstractTimelineModel::rowHeight(int rowNumber) const
-{
- Q_D(const AbstractTimelineModel);
- if (!expanded())
- return DefaultRowHeight;
-
- if (d->rowOffsets.size() > rowNumber)
- return d->rowOffsets[rowNumber] - (rowNumber > 0 ? d->rowOffsets[rowNumber - 1] : 0);
- return DefaultRowHeight;
-}
-
-int AbstractTimelineModel::rowOffset(int rowNumber) const
-{
- Q_D(const AbstractTimelineModel);
- if (rowNumber == 0)
- return 0;
- if (!expanded())
- return DefaultRowHeight * rowNumber;
-
- if (d->rowOffsets.size() >= rowNumber)
- return d->rowOffsets[rowNumber - 1];
- if (!d->rowOffsets.empty())
- return d->rowOffsets.last() + (rowNumber - d->rowOffsets.size()) * DefaultRowHeight;
- return rowNumber * DefaultRowHeight;
-}
-
-void AbstractTimelineModel::setRowHeight(int rowNumber, int height)
-{
- Q_D(AbstractTimelineModel);
- if (d->hidden || !d->expanded)
- return;
- if (height < DefaultRowHeight)
- height = DefaultRowHeight;
-
- int nextOffset = d->rowOffsets.empty() ? 0 : d->rowOffsets.last();
- while (d->rowOffsets.size() <= rowNumber)
- d->rowOffsets << (nextOffset += DefaultRowHeight);
- int difference = height - d->rowOffsets[rowNumber] +
- (rowNumber > 0 ? d->rowOffsets[rowNumber - 1] : 0);
- if (difference != 0) {
- for (; rowNumber < d->rowOffsets.size(); ++rowNumber) {
- d->rowOffsets[rowNumber] += difference;
- }
- emit rowHeightChanged();
- }
-}
-
-int AbstractTimelineModel::height() const
-{
- Q_D(const AbstractTimelineModel);
- int depth = rowCount();
- if (d->hidden || !d->expanded || d->rowOffsets.empty())
- return depth * DefaultRowHeight;
-
- return d->rowOffsets.last() + (depth - d->rowOffsets.size()) * DefaultRowHeight;
-}
-
-qint64 AbstractTimelineModel::traceStartTime() const
-{
- Q_D(const AbstractTimelineModel);
- return d->modelManager->traceTime()->startTime();
-}
-
-qint64 AbstractTimelineModel::traceEndTime() const
-{
- Q_D(const AbstractTimelineModel);
- return d->modelManager->traceTime()->endTime();
-}
-
-qint64 AbstractTimelineModel::traceDuration() const
-{
- Q_D(const AbstractTimelineModel);
- return d->modelManager->traceTime()->duration();
-}
-
-QVariantMap AbstractTimelineModel::location(int index) const
-{
- Q_UNUSED(index);
- QVariantMap map;
- return map;
-}
-
-bool AbstractTimelineModel::isSelectionIdValid(int typeIndex) const
-{
- Q_UNUSED(typeIndex);
- return false;
-}
-
-int AbstractTimelineModel::selectionIdForLocation(const QString &filename, int line, int column) const
-{
- Q_UNUSED(filename);
- Q_UNUSED(line);
- Q_UNUSED(column);
- return -1;
-}
-
-int AbstractTimelineModel::bindingLoopDest(int index) const
-{
- Q_UNUSED(index);
- return -1;
-}
-
-float AbstractTimelineModel::relativeHeight(int index) const
-{
- Q_UNUSED(index);
- return 1.0f;
-}
-
-int AbstractTimelineModel::rowMinValue(int rowNumber) const
-{
- Q_UNUSED(rowNumber);
- return 0;
-}
-
-int AbstractTimelineModel::rowMaxValue(int rowNumber) const
-{
- Q_UNUSED(rowNumber);
- return 0;
-}
-
-void AbstractTimelineModel::dataChanged()
-{
- Q_D(AbstractTimelineModel);
- bool wasEmpty = isEmpty();
- switch (d->modelManager->state()) {
- case QmlProfilerDataState::ProcessingData:
- loadData();
- break;
- case QmlProfilerDataState::ClearingData:
- clear();
- break;
- default:
- break;
- }
- if (wasEmpty != isEmpty())
- emit emptyChanged();
-}
-
-bool AbstractTimelineModel::accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const
-{
- Q_D(const AbstractTimelineModel);
- return (event.rangeType == d->rangeType && event.message == d->message);
-}
-
-bool AbstractTimelineModel::expanded() const
-{
- Q_D(const AbstractTimelineModel);
- return d->expanded;
-}
-
-void AbstractTimelineModel::setExpanded(bool expanded)
-{
- Q_D(AbstractTimelineModel);
- if (expanded != d->expanded) {
- d->expanded = expanded;
- emit expandedChanged();
- }
-}
-
-bool AbstractTimelineModel::hidden() const
-{
- Q_D(const AbstractTimelineModel);
- return d->hidden;
-}
-
-void AbstractTimelineModel::setHidden(bool hidden)
-{
- Q_D(AbstractTimelineModel);
- if (hidden != d->hidden) {
- d->hidden = hidden;
- emit hiddenChanged();
- }
-}
-
-QString AbstractTimelineModel::displayName() const
-{
- Q_D(const AbstractTimelineModel);
- return d->displayName;
-}
-
-int AbstractTimelineModel::rowCount() const
-{
- Q_D(const AbstractTimelineModel);
- if (d->hidden)
- return 0;
- if (isEmpty())
- return d->modelManager->isEmpty() ? 1 : 0;
- return d->expanded ? d->expandedRowCount : d->collapsedRowCount;
-}
-
-int AbstractTimelineModel::selectionId(int index) const
-{
- return range(index).typeId;
-}
-
-void AbstractTimelineModel::clear()
-{
- Q_D(AbstractTimelineModel);
- d->collapsedRowCount = d->expandedRowCount = 1;
- bool wasExpanded = d->expanded;
- bool wasHidden = d->hidden;
- bool hadRowHeights = !d->rowOffsets.empty();
- d->rowOffsets.clear();
- d->expanded = false;
- d->hidden = false;
- SortedTimelineModel::clear();
- if (hadRowHeights)
- emit rowHeightChanged();
- if (wasExpanded)
- emit expandedChanged();
- if (wasHidden)
- emit hiddenChanged();
- d->modelManager->modelProxyCountUpdated(d->modelId, 0, 1);
-}
-
-}
diff --git a/src/plugins/qmlprofiler/abstracttimelinemodel.h b/src/plugins/qmlprofiler/abstracttimelinemodel.h
deleted file mode 100644
index 6b0736148f1..00000000000
--- a/src/plugins/qmlprofiler/abstracttimelinemodel.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company 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 "qmlprofilerdatamodel.h"
-#include "sortedtimelinemodel.h"
-#include <QVariant>
-#include <QColor>
-
-namespace QmlProfiler {
-
-class QMLPROFILER_EXPORT AbstractTimelineModel : public SortedTimelineModel
-{
- Q_OBJECT
- Q_PROPERTY(QString displayName READ displayName CONSTANT)
- Q_PROPERTY(bool empty READ isEmpty NOTIFY emptyChanged)
- Q_PROPERTY(bool hidden READ hidden WRITE setHidden NOTIFY hiddenChanged)
- Q_PROPERTY(int height READ height NOTIFY heightChanged)
-
-public:
- class AbstractTimelineModelPrivate;
- ~AbstractTimelineModel();
-
- // Trivial methods implemented by the abstract model itself
- void setModelManager(QmlProfilerModelManager *modelManager);
- bool isEmpty() const;
- int modelId() const;
-
- // Methods are directly passed on to the private model and relying on its virtual methods.
- int rowHeight(int rowNumber) const;
- int rowOffset(int rowNumber) const;
- void setRowHeight(int rowNumber, int height);
- int height() const;
-
- qint64 traceStartTime() const;
- qint64 traceEndTime() const;
- qint64 traceDuration() const;
- bool accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const;
- bool expanded() const;
- bool hidden() const;
- void setExpanded(bool expanded);
- void setHidden(bool hidden);
- QString displayName() const;
- int rowCount() const;
-
- // Methods that have to be implemented by child models
- virtual QColor color(int index) const = 0;
- virtual QVariantList labels() const = 0;
- virtual QVariantMap details(int index) const = 0;
- virtual int row(int index) const = 0;
- virtual quint64 features() const = 0;
-
- // Methods which can optionally be implemented by child models.
- // returned map should contain "file", "line", "column" properties, or be empty
- virtual QVariantMap location(int index) const;
- virtual int selectionId(int index) const;
- virtual bool isSelectionIdValid(int selectionId) const;
- virtual int selectionIdForLocation(const QString &filename, int line, int column) const;
- virtual int bindingLoopDest(int index) const;
- virtual float relativeHeight(int index) const;
- virtual int rowMinValue(int rowNumber) const;
- virtual int rowMaxValue(int rowNumber) const;
-
-signals:
- void expandedChanged();
- void hiddenChanged();
- void rowHeightChanged();
- void emptyChanged();
- void heightChanged();
-
-protected:
- static const int DefaultRowHeight = 30;
-
- enum BoxColorProperties {
- SelectionIdHueMultiplier = 25,
- FractionHueMultiplier = 96,
- FractionHueMininimum = 10,
- Saturation = 150,
- Lightness = 166
- };
-
- QColor colorBySelectionId(int index) const
- {
- return colorByHue(selectionId(index) * SelectionIdHueMultiplier);
- }
-
- QColor colorByFraction(double fraction) const
- {
- return colorByHue(fraction * FractionHueMultiplier + FractionHueMininimum);
- }
-
- QColor colorByHue(int hue) const
- {
- return QColor::fromHsl(hue % 360, Saturation, Lightness);
- }
-
- explicit AbstractTimelineModel(AbstractTimelineModelPrivate *dd, const QString &displayName,
- QmlDebug::Message message, QmlDebug::RangeType rangeType,
- QObject *parent);
- AbstractTimelineModelPrivate *d_ptr;
-
- virtual void loadData() = 0;
- virtual void clear();
-
-protected slots:
- void dataChanged();
-
-private:
- Q_DECLARE_PRIVATE(AbstractTimelineModel)
-};
-
-}
-
-#endif // ABSTRACTTIMELINEMODEL_H
diff --git a/src/plugins/qmlprofiler/notesmodel.cpp b/src/plugins/qmlprofiler/notesmodel.cpp
deleted file mode 100644
index 2d1f9ce3f50..00000000000
--- a/src/plugins/qmlprofiler/notesmodel.cpp
+++ /dev/null
@@ -1,229 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "notesmodel.h"
-
-namespace QmlProfiler {
-
-NotesModel::NotesModel(QObject *parent) : QObject(parent), m_modelManager(0), m_modified(false)
-{
-}
-
-int NotesModel::count() const
-{
- return m_data.count();
-}
-
-void NotesModel::setModelManager(QmlProfilerModelManager *modelManager)
-{
- m_modelManager = modelManager;
-}
-
-void NotesModel::addTimelineModel(const AbstractTimelineModel *timelineModel)
-{
- connect(timelineModel, &AbstractTimelineModel::destroyed,
- this, &NotesModel::removeTimelineModel);
- m_timelineModels.insert(timelineModel->modelId(), timelineModel);
-}
-
-int NotesModel::typeId(int index) const
-{
- const Note &note = m_data[index];
- auto it = m_timelineModels.find(note.timelineModel);
- if (it == m_timelineModels.end())
- return -1; // This can happen if one of the timeline models has been removed
- return it.value()->typeId(note.timelineIndex);
-}
-
-QString NotesModel::text(int index) const
-{
- return m_data[index].text;
-}
-
-int NotesModel::timelineModel(int index) const
-{
- return m_data[index].timelineModel;
-}
-
-int NotesModel::timelineIndex(int index) const
-{
- return m_data[index].timelineIndex;
-}
-
-QVariantList NotesModel::byTypeId(int selectedType) const
-{
- QVariantList ret;
- for (int noteId = 0; noteId < count(); ++noteId) {
- if (selectedType == typeId(noteId))
- ret << noteId;
- }
- return ret;
-}
-
-QVariantList NotesModel::byTimelineModel(int timelineModel) const
-{
- QVariantList ret;
- for (int noteId = 0; noteId < count(); ++noteId) {
- if (m_data[noteId].timelineModel == timelineModel)
- ret << noteId;
- }
- return ret;
-}
-
-int NotesModel::get(int timelineModel, int timelineIndex) const
-{
- for (int noteId = 0; noteId < count(); ++noteId) {
- const Note &note = m_data[noteId];
- if (note.timelineModel == timelineModel && note.timelineIndex == timelineIndex)
- return noteId;
- }
-
- return -1;
-}
-
-int NotesModel::add(int timelineModel, int timelineIndex, const QString &text)
-{
- const AbstractTimelineModel *model = m_timelineModels[timelineModel];
- int typeId = model->range(timelineIndex).typeId;
- Note note = { text, timelineModel, timelineIndex };
- m_data << note;
- m_modified = true;
- emit changed(typeId, timelineModel, timelineIndex);
- return m_data.count() - 1;
-}
-
-void NotesModel::update(int index, const QString &text)
-{
- Note &note = m_data[index];
- if (text != note.text) {
- note.text = text;
- m_modified = true;
- emit changed(typeId(index), note.timelineModel, note.timelineIndex);
- }
-}
-
-void NotesModel::remove(int index)
-{
- Note &note = m_data[index];
- int noteType = typeId(index);
- int timelineModel = note.timelineModel;
- int timelineIndex = note.timelineIndex;
- m_data.removeAt(index);
- m_modified = true;
- emit changed(noteType, timelineModel, timelineIndex);
-}
-
-bool NotesModel::isModified() const
-{
- return m_modified;
-}
-
-void NotesModel::removeTimelineModel(QObject *timelineModel)
-{
- for (auto i = m_timelineModels.begin(); i != m_timelineModels.end();) {
- if (i.value() == timelineModel)
- i = m_timelineModels.erase(i);
- else
- ++i;
- }
-}
-
-int NotesModel::add(int typeId, qint64 start, qint64 duration, const QString &text)
-{
- int timelineModel = -1;
- int timelineIndex = -1;
- const QVector<QmlProfilerDataModel::QmlEventTypeData> &types =
- m_modelManager->qmlModel()->getEventTypes();
- foreach (const AbstractTimelineModel *model, m_timelineModels) {
- if (model->accepted(types[typeId])) {
- for (int i = model->firstIndex(start); i <= model->lastIndex(start + duration); ++i) {
- if (i < 0)
- continue;
- const SortedTimelineModel::Range &timelineRange = model->range(i);
- if (timelineRange.typeId == typeId && timelineRange.start == start &&
- timelineRange.duration == duration) {
- timelineModel = model->modelId();
- timelineIndex = i;
- break;
- }
- }
- if (timelineIndex != -1)
- break;
- }
- }
-
- if (timelineModel == -1 || timelineIndex == -1)
- return -1;
-
- Note note = { text, timelineModel, timelineIndex };
- m_data << note;
- m_modified = true;
- return m_data.count() - 1;
-}
-
-void NotesModel::clear()
-{
- m_data.clear();
- m_modified = false;
- emit changed(-1, -1, -1);
-}
-
-void NotesModel::loadData()
-{
- m_data.clear();
- const QVector<QmlProfilerDataModel::QmlEventNoteData> &notes =
- m_modelManager->qmlModel()->getEventNotes();
- for (int i = 0; i != notes.size(); ++i) {
- const QmlProfilerDataModel::QmlEventNoteData &note = notes[i];
- add(note.typeIndex, note.startTime, note.duration, note.text);
- }
- m_modified = false; // reset after loading
- emit changed(-1, -1, -1);
-}
-
-void NotesModel::saveData()
-{
- QVector<QmlProfilerDataModel::QmlEventNoteData> notes;
- for (int i = 0; i < count(); ++i) {
- const Note &note = m_data[i];
- auto it = m_timelineModels.find(note.timelineModel);
- if (it == m_timelineModels.end())
- continue;
-
- const SortedTimelineModel::Range &noteRange = it.value()->range(note.timelineIndex);
- QmlProfilerDataModel::QmlEventNoteData save = {
- noteRange.typeId, noteRange.start, noteRange.duration, note.text
- };
- notes.append(save);
- }
- m_modelManager->qmlModel()->setNoteData(notes);
- m_modified = false;
-}
-}
diff --git a/src/plugins/qmlprofiler/qml/CategoryLabel.qml b/src/plugins/qmlprofiler/qml/CategoryLabel.qml
deleted file mode 100644
index c121f8461f8..00000000000
--- a/src/plugins/qmlprofiler/qml/CategoryLabel.qml
+++ /dev/null
@@ -1,312 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-import QtQuick 2.1
-import QtQuick.Controls 1.2
-import QtQuick.Controls.Styles 1.2
-
-Item {
- id: labelContainer
- property string text: trigger(1) ? qmlProfilerModelProxy.displayName(modelIndex) : ""
- property bool expanded: trigger(qmlProfilerModelProxy.expanded(modelIndex))
- property int modelIndex: index
- property int bindingTrigger: 1
- property var descriptions: []
- property var extdescriptions: []
- property var selectionIds: []
- property bool dragging
- property Item draggerParent
-
- signal dragStarted;
- signal dragStopped;
-
- readonly property int dragHeight: 5
-
- function trigger(i) {
- return i * bindingTrigger * bindingTrigger;
- }
-
- property bool reverseSelect: false
-
- visible: trigger(qmlProfilerModelProxy.rowCount(modelIndex)) > 0
-
- height: trigger(qmlProfilerModelProxy.models[modelIndex].height)
- width: 150
-
- function updateDescriptions() {
- bindingTrigger = -bindingTrigger;
- if (!visible)
- return;
-
- var desc=[];
- var ids=[];
- var extdesc=[];
- var labelList = qmlProfilerModelProxy.labels(modelIndex);
- for (var i = 0; i < labelList.length; i++ ) {
- extdesc[i] = desc[i] = (labelList[i].description || qsTr("<bytecode>"));
- ids[i] = labelList[i].id;
- if (labelList[i].displayName !== undefined)
- extdesc[i] += " (" + labelList[i].displayName + ")";
- }
- descriptions = desc;
- selectionIds = ids;
- extdescriptions = extdesc;
- }
-
- Connections {
- target: qmlProfilerModelProxy.models[modelIndex]
- onExpandedChanged: updateDescriptions()
- onRowHeightChanged: updateDescriptions()
- onHiddenChanged: updateDescriptions()
- }
-
- Connections {
- target: qmlProfilerModelProxy
- onStateChanged: updateDescriptions()
- onModelsChanged: updateDescriptions()
- }
-
- MouseArea {
- id: dragArea
- anchors.fill: txt
- drag.target: dragger
- cursorShape: dragging ? Qt.ClosedHandCursor : Qt.OpenHandCursor
- }
-
- DropArea {
- id: dropArea
-
- onPositionChanged: {
- if ((drag.source.modelIndex > labelContainer.modelIndex &&
- drag.source.y < labelContainer.y + drag.source.height) ||
- (drag.source.modelIndex < labelContainer.modelIndex &&
- drag.source.y > labelContainer.y + labelContainer.height -
- drag.source.height)) {
- qmlProfilerModelProxy.swapModels(drag.source.modelIndex,
- labelContainer.modelIndex);
- drag.source.modelIndex = labelContainer.modelIndex;
- }
- }
-
- anchors.fill: parent
- }
-
- Text {
- id: txt
- x: 5
- font.pixelSize: 12
- text: labelContainer.text
- color: "#232323"
- height: trigger(qmlProfilerModelProxy.rowHeight(modelIndex, 0))
- width: 140
- verticalAlignment: Text.AlignVCenter
- renderType: Text.NativeRendering
- }
-
- Rectangle {
- height: 1
- width: parent.width
- color: "#999999"
- anchors.bottom: parent.bottom
- z: 2
- }
-
- Column {
- anchors.top: txt.bottom
- visible: expanded
- Repeater {
- model: descriptions.length
- Button {
- width: labelContainer.width
- height: trigger(qmlProfilerModelProxy.rowHeight(modelIndex, index + 1))
- action: Action {
- onTriggered: {
- if (reverseSelect)
- view.selectPrevFromSelectionId(modelIndex,selectionIds[index]);
- else
- view.selectNextFromSelectionId(modelIndex,selectionIds[index]);
- }
-
- tooltip: extdescriptions[index]
- }
-
- style: ButtonStyle {
- background: Rectangle {
- border.width: 1
- border.color: "#c8c8c8"
- color: "#eaeaea"
- }
- label: Text {
- text: descriptions[index]
- textFormat: Text.PlainText
- verticalAlignment: Text.AlignVCenter
- horizontalAlignment: Text.AlignLeft
- elide: Text.ElideRight
- renderType: Text.NativeRendering
- }
- }
- MouseArea {
- hoverEnabled: true
- property bool resizing: false
- onPressed: resizing = true
- onReleased: resizing = false
-
- height: dragHeight
- anchors.bottom: parent.bottom
- anchors.left: parent.left
- anchors.right: parent.right
- cursorShape: Qt.SizeVerCursor
-
- onMouseYChanged: {
- if (resizing)
- qmlProfilerModelProxy.setRowHeight(modelIndex, index + 1, y + mouseY);
- }
- }
- }
- }
- }
-
- ToolButton {
- id: notesButton
- anchors.verticalCenter: txt.verticalCenter
- anchors.right: expandButton.left
- implicitWidth: 17
- implicitHeight: txt.height - 1
- property var eventIds: []
- property var texts: []
- property int currentNote: -1
- Connections {
- target: qmlProfilerModelProxy
- onModelsChanged: notesButton.updateNotes()
- onNotesChanged: {
- if (arguments[1] === -1 || arguments[1] === modelIndex)
- notesButton.updateNotes();
- }
- }
-
- function updateNotes() {
- var notes = qmlProfilerModelProxy.notesByTimelineModel(modelIndex);
- var newTexts = [];
- var newEventIds = [];
- for (var i in notes) {
- newTexts.push(qmlProfilerModelProxy.noteText(notes[i]))
- newEventIds.push(qmlProfilerModelProxy.noteTimelineIndex(notes[i]));
- }
-
- // Bindings are only triggered when assigning the whole array.
- eventIds = newEventIds;
- texts = newTexts;
- }
-
- visible: eventIds.length > 0
- iconSource: "ico_note.png"
- tooltip: texts.join("\n");
- onClicked: {
- if (++currentNote >= eventIds.length)
- currentNote = 0;
- view.selectFromEventIndex(modelIndex, eventIds[currentNote]);
- }
- }
-
- ToolButton {
- id: expandButton
- anchors.verticalCenter: txt.verticalCenter
- anchors.right: parent.right
- implicitWidth: 17
- implicitHeight: txt.height - 1
- enabled: expanded || trigger(qmlProfilerModelProxy.count(modelIndex)) > 0
- iconSource: expanded ? "arrow_down.png" : "arrow_right.png"
- tooltip: expanded ? qsTr("Collapse category") : qsTr("Expand category.")
- onClicked: qmlProfilerModelProxy.setExpanded(modelIndex, !expanded);
- }
-
- Rectangle {
- id: dragger
- property int modelIndex
- width: labelContainer.width
- height: 0
- color: "black"
- opacity: 0.5
- anchors.left: parent.left
-
- // anchor to top so that it reliably snaps back after dragging
- anchors.top: parent.top
-
- Drag.active: dragArea.drag.active
- Drag.onActiveChanged: {
- // We don't want height, text, or modelIndex to be changed when reordering occurs, so we
- // don't make them properties.
- draggerText.text = txt.text;
- modelIndex = labelContainer.modelIndex;
- if (Drag.active) {
- height = labelContainer.height;
- labelContainer.dragStarted();
- } else {
- height = 0;
- labelContainer.dragStopped();
- }
- }
-
- states: [
- State {
- when: dragger.Drag.active
- ParentChange {
- target: dragger
- parent: draggerParent
- }
- PropertyChanges {
- target: dragger
- anchors.top: undefined
- }
- }
- ]
-
- Text {
- id: draggerText
- visible: parent.Drag.active
- x: txt.x
- font.pixelSize: txt.font.pixelSize
- color: "white"
- width: txt.width
- height: txt.height
- verticalAlignment: txt.verticalAlignment
- renderType: txt.renderType
- }
- }
-
- MouseArea {
- anchors.top: dragArea.bottom
- anchors.bottom: labelContainer.dragging ? labelContainer.bottom : dragArea.bottom
- anchors.left: labelContainer.left
- anchors.right: labelContainer.right
- cursorShape: dragArea.cursorShape
- }
-
-}
diff --git a/src/plugins/qmlprofiler/qml/MainView.qml b/src/plugins/qmlprofiler/qml/MainView.qml
deleted file mode 100644
index 25800a86e3a..00000000000
--- a/src/plugins/qmlprofiler/qml/MainView.qml
+++ /dev/null
@@ -1,544 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-import QtQuick 2.1
-import Monitor 1.0
-import QtQuick.Controls 1.0
-
-Rectangle {
- id: root
-
- // ***** properties
-
- property alias selectionLocked : view.selectionLocked
- property bool lockItemSelection : false
-
- property real mainviewTimePerPixel : 0
-
- signal updateCursorPosition
- property string fileName: ""
- property int lineNumber: -1
- property int columnNumber: 0
- property int typeId: -1
-
- property bool selectionRangeMode: false
-
- property bool selectionRangeReady: selectionRange.ready
- property real selectionRangeStart: selectionRange.startTime
- property real selectionRangeEnd: selectionRange.startTime + selectionRange.duration
-
- color: "#dcdcdc"
-
- // ***** connections with external objects
- Connections {
- target: zoomControl
- onRangeChanged: {
- var startTime = zoomControl.startTime();
- var endTime = zoomControl.endTime();
-
- mainviewTimePerPixel = Math.abs(endTime - startTime) / root.width;
-
- backgroundMarks.updateMarks(startTime, endTime);
- view.startTime = startTime;
- view.endTime = endTime;
- view.updateWindow();
- }
- onWindowChanged: {
- view.updateWindow();
- }
- }
-
-
- Connections {
- target: qmlProfilerModelProxy
- onDataAvailable: {
- view.clearData();
- zoomControl.setRange(qmlProfilerModelProxy.traceStartTime(),
- qmlProfilerModelProxy.traceStartTime() +
- qmlProfilerModelProxy.traceDuration()/10);
- view.requestPaint();
- }
- onStateChanged: backgroundMarks.requestPaint()
- onModelsChanged: backgroundMarks.requestPaint()
- onExpandedChanged: backgroundMarks.requestPaint()
- onRowHeightChanged: backgroundMarks.requestPaint()
- }
-
-
- // ***** functions
- function gotoSourceLocation(file,line,column) {
- if (file !== undefined) {
- root.fileName = file;
- root.lineNumber = line;
- root.columnNumber = column;
- }
- }
-
- function clear() {
- flick.contentY = 0;
- flick.contentX = 0;
- flick.contentWidth = 0;
- view.clearData();
- view.startTime = view.endTime = 0;
- rangeDetails.hide();
- selectionRangeMode = false;
- buttonsBar.updateRangeButton(selectionRangeMode);
- zoomControl.setRange(0,0);
- zoomSlider.externalUpdate = true;
- zoomSlider.value = zoomSlider.minimumValue;
- overview.clear();
- timeDisplay.clear();
- }
-
- function enableButtonsBar(enable) {
- buttonsBar.enabled = enable;
- }
-
- function recenter( centerPoint ) {
- var windowLength = view.endTime - view.startTime;
- var newStart = Math.floor(centerPoint - windowLength/2);
- if (newStart < 0)
- newStart = 0;
- if (newStart + windowLength > qmlProfilerModelProxy.traceEndTime())
- newStart = qmlProfilerModelProxy.traceEndTime() - windowLength;
- zoomControl.setRange(newStart, newStart + windowLength);
- }
-
- function recenterOnItem(modelIndex, itemIndex)
- {
- if (itemIndex === -1)
- return;
-
- // if item is outside of the view, jump back to its position
- if (qmlProfilerModelProxy.endTime(modelIndex, itemIndex) < view.startTime ||
- qmlProfilerModelProxy.startTime(modelIndex, itemIndex) > view.endTime) {
- recenter((qmlProfilerModelProxy.startTime(modelIndex, itemIndex) +
- qmlProfilerModelProxy.endTime(modelIndex, itemIndex)) / 2);
- }
- var row = qmlProfilerModelProxy.row(modelIndex, itemIndex);
- var totalRowOffset = qmlProfilerModelProxy.modelOffset(modelIndex) +
- qmlProfilerModelProxy.rowOffset(modelIndex, row);
- if (totalRowOffset > flick.contentY + flick.height ||
- totalRowOffset + qmlProfilerModelProxy.rowHeight(modelIndex, row) < flick.contentY)
- flick.contentY = Math.min(flick.contentHeight - flick.height,
- Math.max(0, totalRowOffset - flick.height / 2));
- }
-
- function selectBySelectionId(modelIndex, selectionId)
- {
- if (selectionId === -1 || (modelIndex === view.selectedModel && view.selectedItem !== -1 &&
- selectionId === qmlProfilerModelProxy.selectionId(modelIndex, view.selectedItem)))
- return;
-
- // 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 = -1;
- var notes = qmlProfilerModelProxy.notesByTypeId(selectionId);
- if (notes.length !== 0) {
- itemIndex = qmlProfilerModelProxy.noteTimelineIndex(notes[0]);
- // for some models typeId != selectionId. In that case we cannot select the noted
- // events. This is purely theoretical as their data doesn't show up in the events
- // view so that we cannot receive a selection event for them.
- if (qmlProfilerModelProxy.typeId(modelIndex, itemIndex) !== selectionId)
- itemIndex = -1;
- }
-
- if (itemIndex === -1)
- itemIndex = view.nextItemFromSelectionId(modelIndex, selectionId);
- // select an item, lock to it, and recenter if necessary
- view.selectFromEventIndex(modelIndex, itemIndex); // triggers recentering
- if (itemIndex !== -1)
- view.selectionLocked = true;
- lockItemSelection = false;
- }
- }
-
- // ***** slots
- onSelectionRangeModeChanged: {
- selectionRangeControl.enabled = selectionRangeMode;
- selectionRange.reset();
- buttonsBar.updateRangeButton(selectionRangeMode);
- }
-
- onSelectionLockedChanged: {
- buttonsBar.updateLockButton(selectionLocked);
- }
-
- focus: true
- property bool shiftPressed: false;
- Keys.onPressed: shiftPressed = (event.key === Qt.Key_Shift);
- Keys.onReleased: shiftPressed = false;
-
- Flickable {
- id: labelsflick
- flickableDirection: Flickable.VerticalFlick
- interactive: false
- anchors.top: buttonsBar.bottom
- anchors.bottom: overview.top
- anchors.left: parent.left
- width: labels.width
- contentY: flick.contentY
-
- // reserve some more space than needed to prevent weird effects when resizing
- contentHeight: labels.height + height
-
- Rectangle {
- id: labels
- anchors.left: parent.left
- width: 150
- color: root.color
- height: col.height
-
- property int rowCount: qmlProfilerModelProxy.modelCount();
-
- Column {
- id: col
-
- // Dispatch the cursor shape to all labels. When dragging the DropArea receiving
- // the drag events is not necessarily related to the MouseArea receiving the mouse
- // events, so we can't use the drag events to determine the cursor shape.
- property bool dragging: false
-
- Repeater {
- model: labels.rowCount
- delegate: CategoryLabel {
- dragging: col.dragging
- reverseSelect: root.shiftPressed
- onDragStarted: col.dragging = true
- onDragStopped: col.dragging = false
- draggerParent: labels
- }
- }
- }
- }
- }
-
- // border between labels and timeline
- Rectangle {
- id: labelsborder
- anchors.left: labelsflick.right
- anchors.top: parent.top
- anchors.bottom: overview.top
- width: 1
- color: "#858585"
- }
-
- ButtonsBar {
- id: buttonsBar
- enabled: false
- anchors.top: parent.top
- anchors.left: parent.left
- width: 150
- height: 24
- onZoomControlChanged: zoomSliderToolBar.visible = !zoomSliderToolBar.visible
- onFilterMenuChanged: filterMenu.visible = !filterMenu.visible
- onJumpToNext: view.selectNext();
- onJumpToPrev: view.selectPrev();
- onRangeSelectChanged: selectionRangeMode = rangeButtonChecked();
- onLockChanged: selectionLocked = !lockButtonChecked();
- }
-
- TimeDisplay {
- id: timeDisplay
- anchors.top: parent.top
- anchors.left: labelsborder.right
- anchors.right: parent.right
- height: 24
- }
-
- Flickable {
- id: flick
- contentHeight: labels.height
- contentWidth: 0
- flickableDirection: Flickable.HorizontalAndVerticalFlick
- boundsBehavior: Flickable.StopAtBounds
- clip:true
-
- // ScrollView will try to deinteractivate it. We don't want that
- // as the horizontal flickable is interactive, too. We do occasionally
- // switch to non-interactive ourselves, though.
- property bool stayInteractive: true
- onInteractiveChanged: interactive = stayInteractive
- onStayInteractiveChanged: interactive = stayInteractive
-
- onWidthChanged: {
- var duration = Math.abs(zoomControl.endTime() - zoomControl.startTime());
- if (duration > 0)
- contentWidth = zoomControl.windowLength() * width / duration;
- }
-
- // ***** child items
- TimeMarks {
- id: backgroundMarks
- y: flick.contentY
- x: flick.contentX
- height: flick.height
- width: scroller.width
- }
-
- SelectionRange {
- id: selectionRange
- visible: root.selectionRangeMode && creationState !== 0
- z: 2
- }
-
- TimelineRenderer {
- id: view
-
- profilerModelProxy: qmlProfilerModelProxy
-
- x: flick.contentX
- y: flick.contentY
-
- // paint "under" the vertical scrollbar, so that it always matches with the timemarks
- width: scroller.width
- height: flick.height
-
- onEndTimeChanged: requestPaint()
- onYChanged: requestPaint()
- onHeightChanged: requestPaint()
- property bool recursionGuard: false
-
- property int intX: x
- property int intWidth: width
- onIntXChanged: {
- // Don't updateZoomControl if we're just updating the flick range, _from_
- // zoomControl. The other way round is OK. We _want_ the flick range to be updated
- // on external changes to zoomControl.
- if (recursionGuard)
- return;
-
- var newStartTime = intX * (endTime - startTime) / intWidth +
- zoomControl.windowStart();
- if (Math.abs(newStartTime - startTime) >= 1) {
- var newEndTime = (intX + intWidth) * (endTime - startTime) / intWidth +
- zoomControl.windowStart();
- zoomControl.setRange(newStartTime, newEndTime);
- }
- }
-
- function updateWindow() {
- var duration = zoomControl.duration();
- if (recursionGuard || duration <= 0)
- return;
-
- recursionGuard = true;
-
- if (!flick.movingHorizontally) {
- // This triggers an unwanted automatic change in contentX. We ignore that by
- // checking recursionGuard in this function and in updateZoomControl.
- flick.contentWidth = zoomControl.windowLength() * intWidth / duration;
-
- var newStartX = (startTime - zoomControl.windowStart()) * intWidth /
- duration;
-
- if (isFinite(newStartX) && Math.abs(newStartX - intX) >= 1)
- flick.contentX = newStartX;
- }
- recursionGuard = false;
- }
-
- onSelectionChanged: {
- if (selectedItem !== -1) {
- // display details
- rangeDetails.showInfo(selectedModel, selectedItem);
-
- // center view (horizontally)
- recenterOnItem(selectedModel, selectedItem);
- if (!lockItemSelection) {
- lockItemSelection = true;
- // update in other views
- var eventLocation = qmlProfilerModelProxy.location(view.selectedModel,
- view.selectedItem);
- gotoSourceLocation(eventLocation.file, eventLocation.line,
- eventLocation.column);
- root.typeId = qmlProfilerModelProxy.typeId(view.selectedModel,
- view.selectedItem);
- root.updateCursorPosition();
- lockItemSelection = false;
- }
- } else {
- rangeDetails.hide();
- }
- }
-
- onItemPressed: {
- var location = qmlProfilerModelProxy.location(modelIndex, pressedItem);
- if (location.hasOwnProperty("file")) // not empty
- root.gotoSourceLocation(location.file, location.line, location.column);
- root.typeId = qmlProfilerModelProxy.typeId(modelIndex, pressedItem);
- root.updateCursorPosition();
- }
-
- // hack to pass mouse events to the other mousearea if enabled
- startDragArea: selectionRange.ready ? selectionRange.rangeLeft : -x
- endDragArea: selectionRange.ready ? selectionRange.rangeRight : -x - 1
- }
- MouseArea {
- id: selectionRangeControl
- enabled: false
- width: flick.width
- height: flick.height
- x: flick.contentX
- y: flick.contentY
- hoverEnabled: enabled
- z: 2
-
- onReleased: {
- selectionRange.releasedOnCreation();
- }
- onPressed: {
- selectionRange.pressedOnCreation();
- }
- onCanceled: {
- selectionRange.releasedOnCreation();
- }
- onPositionChanged: {
- selectionRange.movedOnCreation();
- }
- }
- }
-
- ScrollView {
- id: scroller
- contentItem: flick
- anchors.left: labelsborder.right
- anchors.top: timeDisplay.bottom
- anchors.bottom: overview.top
- anchors.right: parent.right
- }
-
- SelectionRangeDetails {
- id: selectionRangeDetails
- visible: selectionRange.visible
- startTime: selectionRange.startTimeString
- duration: selectionRange.durationString
- endTime: selectionRange.endTimeString
- showDuration: selectionRange.rangeWidth > 1
- }
-
- RangeDetails {
- id: rangeDetails
- }
-
- Rectangle {
- id: filterMenu
- color: "#9b9b9b"
- enabled: buttonsBar.enabled
- visible: false
- width: labels.width
- anchors.left: parent.left
- anchors.top: buttonsBar.bottom
- height: qmlProfilerModelProxy.modelCount() * buttonsBar.height
-
- Repeater {
- id: filterMenuInner
- model: qmlProfilerModelProxy.models
- CheckBox {
- anchors.left: filterMenu.left
- anchors.right: filterMenu.right
- height: buttonsBar.height
- y: index * height
- text: qmlProfilerModelProxy.models[index].displayName
- enabled: !qmlProfilerModelProxy.models[index].empty
- checked: enabled && !qmlProfilerModelProxy.models[index].hidden
- onCheckedChanged: qmlProfilerModelProxy.models[index].hidden = !checked
- }
- }
-
- }
-
- Rectangle {
- id: zoomSliderToolBar
- objectName: "zoomSliderToolBar"
- color: "#9b9b9b"
- enabled: buttonsBar.enabled
- visible: false
- width: labels.width
- height: buttonsBar.height
- anchors.left: parent.left
- anchors.top: buttonsBar.bottom
-
- function updateZoomLevel() {
- zoomSlider.externalUpdate = true;
- zoomSlider.value = Math.pow((view.endTime - view.startTime) /
- zoomControl.windowLength(),
- 1 / zoomSlider.exponent) * zoomSlider.maximumValue;
- }
-
-
- Slider {
- id: zoomSlider
- anchors.fill: parent
- minimumValue: 1
- maximumValue: 10000
- stepSize: 100
-
- property int exponent: 3
- property bool externalUpdate: false
- property int minWindowLength: 1e5 // 0.1 ms
-
- onValueChanged: {
- if (externalUpdate || zoomControl.windowEnd() <= zoomControl.windowStart()) {
- // Zoom range is independently updated. We shouldn't mess
- // with it here as otherwise we might introduce rounding
- // or arithmetic errors.
- externalUpdate = false;
- return;
- }
-
- var windowLength = Math.max(
- Math.pow(value / maximumValue, exponent) * zoomControl.windowLength(),
- minWindowLength);
-
- var fixedPoint = (view.startTime + view.endTime) / 2;
- if (view.selectedItem !== -1) {
- // center on selected item if it's inside the current screen
- var newFixedPoint = qmlProfilerModelProxy.startTime(view.selectedModel, view.selectedItem);
- if (newFixedPoint >= view.startTime && newFixedPoint < view.endTime)
- fixedPoint = newFixedPoint;
- }
-
- var startTime = Math.max(zoomControl.windowStart(), fixedPoint - windowLength / 2)
- zoomControl.setRange(startTime, startTime + windowLength);
- }
- }
- }
-
- Overview {
- id: overview
- height: 50
- anchors.bottom: parent.bottom
- anchors.right: parent.right
- anchors.left: parent.left
- }
-}
diff --git a/src/plugins/qmlprofiler/qml/Overview.js b/src/plugins/qmlprofiler/qml/Overview.js
deleted file mode 100644
index 2aa0fd4bbc5..00000000000
--- a/src/plugins/qmlprofiler/qml/Overview.js
+++ /dev/null
@@ -1,193 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-.pragma library
-
-var qmlProfilerModelProxy = 0;
-
-//draw background of the graph
-function drawGraph(canvas, ctxt)
-{
- ctxt.fillStyle = "#eaeaea";
- ctxt.fillRect(0, 0, canvas.width, canvas.height);
-}
-
-//draw the actual data to be graphed
-function drawData(canvas, ctxt)
-{
- if ((!qmlProfilerModelProxy) || qmlProfilerModelProxy.isEmpty())
- return;
-
- var spacing = canvas.width / qmlProfilerModelProxy.traceDuration();
-
- for (var modelIndex = 0; modelIndex < qmlProfilerModelProxy.modelCount(); ++modelIndex) {
- for (var ii = canvas.offset; ii < qmlProfilerModelProxy.count(modelIndex);
- ii += canvas.increment) {
-
- var xx = (qmlProfilerModelProxy.startTime(modelIndex,ii) -
- qmlProfilerModelProxy.traceStartTime()) * spacing;
-
- var eventWidth = qmlProfilerModelProxy.duration(modelIndex,ii) * spacing;
-
- if (eventWidth < 1)
- eventWidth = 1;
-
- xx = Math.round(xx);
-
- var itemHeight = qmlProfilerModelProxy.relativeHeight(modelIndex, ii) *
- canvas.blockHeight;
- var yy = (modelIndex + 1) * canvas.blockHeight - itemHeight ;
-
- ctxt.fillStyle = qmlProfilerModelProxy.color(modelIndex, ii);
- ctxt.fillRect(xx, canvas.bump + yy, eventWidth, itemHeight);
- }
- }
-}
-
-function drawBindingLoops(canvas, ctxt) {
- ctxt.strokeStyle = "orange";
- ctxt.lineWidth = 2;
- var radius = 1;
- var spacing = canvas.width / qmlProfilerModelProxy.traceDuration();
- for (var modelIndex = 0; modelIndex < qmlProfilerModelProxy.modelCount(); ++modelIndex) {
- for (var ii = canvas.offset - canvas.increment; ii < qmlProfilerModelProxy.count(modelIndex);
- ii += canvas.increment) {
- if (qmlProfilerModelProxy.bindingLoopDest(modelIndex,ii) >= 0) {
- var xcenter = Math.round(qmlProfilerModelProxy.startTime(modelIndex,ii) +
- qmlProfilerModelProxy.duration(modelIndex,ii) / 2 -
- qmlProfilerModelProxy.traceStartTime()) * spacing;
- var ycenter = Math.round(canvas.bump + canvas.blockHeight * modelIndex +
- canvas.blockHeight / 2);
- ctxt.beginPath();
- ctxt.arc(xcenter, ycenter, radius, 0, 2*Math.PI, true);
- ctxt.stroke();
- }
- }
- }
-}
-
-function drawNotes(canvas, ctxt)
-{
- if ((!qmlProfilerModelProxy) || qmlProfilerModelProxy.noteCount() === 0)
- return;
-
- var spacing = canvas.width / qmlProfilerModelProxy.traceDuration();
- // divide canvas height in 7 parts: margin, 3*line, space, dot, margin
- var vertSpace = (canvas.height - canvas.bump) / 7;
-
- ctxt.strokeStyle = "orange";
- ctxt.lineWidth = 2;
- for (var i = 0; i < qmlProfilerModelProxy.noteCount(); ++i) {
- var timelineModel = qmlProfilerModelProxy.noteTimelineModel(i);
- var timelineIndex = qmlProfilerModelProxy.noteTimelineIndex(i);
- if (timelineIndex === -1)
- continue;
- var traceStart = qmlProfilerModelProxy.traceStartTime();
- var traceEnd = qmlProfilerModelProxy.traceEndTime();
- var start = Math.max(qmlProfilerModelProxy.startTime(timelineModel, timelineIndex),
- traceStart);
- var end = Math.min(qmlProfilerModelProxy.endTime(timelineModel, timelineIndex),
- traceEnd);
- var annoX = Math.round(((start + end) / 2 - traceStart) * spacing);
-
- ctxt.moveTo(annoX, canvas.bump + vertSpace)
- ctxt.lineTo(annoX, canvas.bump + vertSpace * 4)
- ctxt.stroke();
- ctxt.moveTo(annoX, canvas.bump + vertSpace * 5);
- ctxt.lineTo(annoX, canvas.bump + vertSpace * 6);
- ctxt.stroke();
- }
-}
-
-function drawTimeBar(canvas, ctxt)
-{
- if (!qmlProfilerModelProxy)
- return;
-
- var width = canvas.width;
- var height = 10;
- var startTime = qmlProfilerModelProxy.traceStartTime();
- var endTime = qmlProfilerModelProxy.traceEndTime();
-
- var totalTime = qmlProfilerModelProxy.traceDuration();
- var spacing = width / totalTime;
-
- var initialBlockLength = 120;
- var timePerBlock = Math.pow(2, Math.floor( Math.log( totalTime / width *
- initialBlockLength ) / Math.LN2 ) );
- var pixelsPerBlock = timePerBlock * spacing;
- var pixelsPerSection = pixelsPerBlock / 5;
- var blockCount = width / pixelsPerBlock;
-
- var realStartTime = Math.floor(startTime/timePerBlock) * timePerBlock;
- var realStartPos = (startTime-realStartTime) * spacing;
-
- var timePerPixel = timePerBlock/pixelsPerBlock;
-
- ctxt.fillStyle = "#000000";
- ctxt.font = "6px sans-serif";
-
- ctxt.fillStyle = "#cccccc";
- ctxt.fillRect(0, 0, width, height);
- for (var ii = 0; ii < blockCount+1; ii++) {
- var x = Math.floor(ii*pixelsPerBlock - realStartPos);
-
- // block boundary
- ctxt.strokeStyle = "#525252";
- ctxt.beginPath();
- ctxt.moveTo(x, height/2);
- ctxt.lineTo(x, height);
- ctxt.stroke();
-
- // block time label
- ctxt.fillStyle = "#000000";
- var timeString = prettyPrintTime((ii+0.5)*timePerBlock + realStartTime);
- ctxt.textAlign = "center";
- ctxt.fillText(timeString, x + pixelsPerBlock/2, height/2 + 3);
- }
-
- ctxt.fillStyle = "#808080";
- ctxt.fillRect(0, height-1, width, 1);
-}
-
-function prettyPrintTime( t )
-{
- if (t <= 0) return "0";
- if (t<1000) return t+" ns";
- t = t/1000;
- if (t<1000) return t+" μs";
- t = Math.floor(t/100)/10;
- if (t<1000) return t+" ms";
- t = Math.floor(t)/1000;
- if (t<60) return t+" s";
- var m = Math.floor(t/60);
- t = Math.floor(t - m*60);
- return m+"m"+t+"s";
-}
diff --git a/src/plugins/qmlprofiler/qml/Overview.qml b/src/plugins/qmlprofiler/qml/Overview.qml
deleted file mode 100644
index 01375162e4d..00000000000
--- a/src/plugins/qmlprofiler/qml/Overview.qml
+++ /dev/null
@@ -1,207 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-import QtQuick 2.1
-import Monitor 1.0
-import "Overview.js" as Plotter
-
-Canvas {
- id: canvas
- objectName: "Overview"
- contextType: "2d"
-
- readonly property int eventsPerPass: 512
- property int increment: -1
- property int offset: -1
- readonly property int bump: 10;
- readonly property int blockHeight: (height - bump) / qmlProfilerModelProxy.models.length;
-
- // ***** properties
- height: 50
- property bool dataReady: false
- property double startTime : 0
- property double endTime : 0
- property bool recursionGuard: false
-
- onWidthChanged: offset = -1
-
- // ***** functions
- function clear()
- {
- dataReady = false;
- increment = -1;
- offset = -1;
- requestPaint();
- }
-
- function updateRange() {
- if (recursionGuard)
- return;
- var newStartTime = Math.round(rangeMover.rangeLeft * qmlProfilerModelProxy.traceDuration() / width) + qmlProfilerModelProxy.traceStartTime();
- var newEndTime = Math.round(rangeMover.rangeRight * qmlProfilerModelProxy.traceDuration() / width) + qmlProfilerModelProxy.traceStartTime();
- if (startTime !== newStartTime || endTime !== newEndTime)
- zoomControl.setRange(newStartTime, Math.max(newEndTime, newStartTime + 500));
- }
-
- function clamp(val, min, max) {
- return Math.min(Math.max(val, min), max);
- }
-
- // ***** connections to external objects
- Connections {
- target: zoomControl
- onRangeChanged: {
- if (qmlProfilerModelProxy) {
- recursionGuard = true;
- startTime = clamp(zoomControl.startTime(), qmlProfilerModelProxy.traceStartTime(), qmlProfilerModelProxy.traceEndTime());
- endTime = clamp(zoomControl.endTime(), startTime, qmlProfilerModelProxy.traceEndTime());
- var newRangeX = (startTime - qmlProfilerModelProxy.traceStartTime()) * width / qmlProfilerModelProxy.traceDuration();
- var newWidth = (endTime - startTime) * width / qmlProfilerModelProxy.traceDuration();
- var widthChanged = Math.abs(newWidth - rangeMover.rangeWidth) > 1;
- var leftChanged = Math.abs(newRangeX - rangeMover.rangeLeft) > 1;
- if (leftChanged)
- rangeMover.rangeLeft = newRangeX;
-
- if (leftChanged || widthChanged)
- rangeMover.rangeRight = newRangeX + newWidth;
- recursionGuard = false;
- }
- }
- }
-
- Connections {
- target: qmlProfilerModelProxy
- onDataAvailable: {
- dataReady = true;
- increment = 0;
- for (var i = 0; i < qmlProfilerModelProxy.modelCount(); ++i)
- increment += qmlProfilerModelProxy.count(i);
- increment = Math.ceil(increment / eventsPerPass);
- offset = -1;
- requestPaint();
- }
- onNotesChanged: notes.doPaint = true;
- }
-
- Timer {
- id: paintTimer
- repeat: true
- running: offset >= 0
- interval: offset == 0 ? 1000 : 14 // Larger initial delay to avoid flickering on resize
- onTriggered: canvas.requestPaint()
- }
-
- // ***** slots
- onPaint: {
- var context = (canvas.context === null) ? getContext("2d") : canvas.context;
-
- Plotter.qmlProfilerModelProxy = qmlProfilerModelProxy;
-
- if (offset < 0) {
- context.reset();
- Plotter.drawGraph(canvas, context);
- if (dataReady) {
- Plotter.drawTimeBar(canvas, context);
- offset = 0;
- }
- } else if (offset < increment) {
- Plotter.drawData(canvas, context);
- ++offset;
- } else if (offset < 2 * increment) {
- Plotter.drawBindingLoops(canvas, context);
- ++offset;
- } else {
- notes.doPaint = true;
- offset = -1;
- }
- }
-
- Canvas {
- property alias bump: canvas.bump
- property bool doPaint: false
- onDoPaintChanged: {
- if (doPaint)
- requestPaint();
- }
-
- id: notes
- anchors.fill: parent
- onPaint: {
- if (doPaint) {
- var context = (notes.context === null) ? getContext("2d") : notes.context;
- context.reset();
- Plotter.drawNotes(notes, context);
- doPaint = false;
- }
- }
- }
-
- // ***** child items
- MouseArea {
- anchors.fill: canvas
- function jumpTo(posX) {
- var newX = posX - rangeMover.rangeWidth / 2;
- if (newX < 0)
- newX = 0;
- if (newX + rangeMover.rangeWidth > canvas.width)
- newX = canvas.width - rangeMover.rangeWidth;
-
- if (newX < rangeMover.rangeLeft) {
- // Changing left border will change width, so precompute right border here.
- var right = newX + rangeMover.rangeWidth;
- rangeMover.rangeLeft = newX;
- rangeMover.rangeRight = right;
- } else if (newX > rangeMover.rangeLeft) {
- rangeMover.rangeRight = newX + rangeMover.rangeWidth;
- rangeMover.rangeLeft = newX;
- }
- }
-
- onPressed: {
- jumpTo(mouse.x);
- }
- onPositionChanged: {
- jumpTo(mouse.x);
- }
- }
-
- RangeMover {
- id: rangeMover
- visible: dataReady
- onRangeLeftChanged: canvas.updateRange()
- onRangeRightChanged: canvas.updateRange()
- }
-
- Rectangle {
- height: 1
- width: parent.width
- color: "#858585"
- }
-}
diff --git a/src/plugins/qmlprofiler/qml/TimeDisplay.qml b/src/plugins/qmlprofiler/qml/TimeDisplay.qml
deleted file mode 100644
index eb37ea361d2..00000000000
--- a/src/plugins/qmlprofiler/qml/TimeDisplay.qml
+++ /dev/null
@@ -1,129 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-import QtQuick 2.1
-import Monitor 1.0
-
-Canvas {
- id: timeDisplay
- objectName: "TimeDisplay"
- contextType: "2d"
-
- property real startTime : 0
- property real endTime : 0
-
- Connections {
- target: zoomControl
- onRangeChanged: {
- startTime = zoomControl.startTime();
- endTime = zoomControl.endTime();
- requestPaint();
- }
- }
-
- onPaint: {
- var context = (timeDisplay.context === null) ? getContext("2d") : timeDisplay.context;
-
- context.reset();
- context.fillStyle = "white";
- context.fillRect(0, 0, width, height);
-
- var totalTime = Math.max(1, endTime - startTime);
- var spacing = width / totalTime;
-
- var initialBlockLength = 120;
- var timePerBlock = Math.pow(2, Math.floor( Math.log( totalTime / width * initialBlockLength ) / Math.LN2 ) );
- var pixelsPerBlock = timePerBlock * spacing;
- var pixelsPerSection = pixelsPerBlock / 5;
- var blockCount = width / pixelsPerBlock;
-
- var realStartTime = Math.floor(startTime/timePerBlock) * timePerBlock;
- var startPos = (startTime - realStartTime) * spacing;
-
- var timePerPixel = timePerBlock/pixelsPerBlock;
-
- var initialColor = Math.floor(realStartTime/timePerBlock) % 2;
-
- context.fillStyle = "#000000";
- context.font = "8px sans-serif";
- for (var ii = 0; ii < blockCount+1; ii++) {
- var x = Math.floor(ii*pixelsPerBlock - startPos);
-
- context.fillStyle = (ii+initialColor)%2 ? "#E6E6E6":"white";
- context.fillRect(x, 0, pixelsPerBlock, height);
-
- context.strokeStyle = "#B0B0B0";
- context.beginPath();
- context.moveTo(x, 0);
- context.lineTo(x, height);
- context.stroke();
-
- context.fillStyle = "#000000";
- context.fillText(prettyPrintTime(ii*timePerBlock + realStartTime), x + 5, height/2 + 5);
- }
-
- context.strokeStyle = "#525252";
- context.beginPath();
- context.moveTo(0, height-1);
- context.lineTo(width, height-1);
- context.stroke();
- }
-
- function clear()
- {
- startTime = endTime = 0;
- requestPaint();
- }
-
- function prettyPrintTime( t )
- {
- var round = 1;
- var barrier = 1;
- var range = endTime - startTime;
- var units = ["μs", "ms", "s"];
-
- for (var i = 0; i < units.length; ++i) {
- barrier *= 1000;
- if (range < barrier)
- round *= 1000;
- else if (range < barrier * 10)
- round *= 100;
- else if (range < barrier * 100)
- round *= 10;
- if (t < barrier * 1000)
- return Math.floor(t / (barrier / round)) / round + units[i];
- }
-
- t /= barrier;
- var m = Math.floor(t / 60);
- var s = Math.floor((t - m * 60) * round) / round;
- return m + "m" + s + "s";
- }
-}
diff --git a/src/plugins/qmlprofiler/qml/TimeMarks.qml b/src/plugins/qmlprofiler/qml/TimeMarks.qml
deleted file mode 100644
index 9e5b92793ed..00000000000
--- a/src/plugins/qmlprofiler/qml/TimeMarks.qml
+++ /dev/null
@@ -1,196 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-import QtQuick 2.1
-import Monitor 1.0
-
-Canvas {
- id: timeMarks
- objectName: "TimeMarks"
- contextType: "2d"
-
- readonly property int scaleMinHeight: 60
- readonly property int scaleStepping: 30
- readonly property string units: " kMGT"
-
- property real startTime
- property real endTime
- property real timePerPixel
-
- Connections {
- target: labels
- onHeightChanged: requestPaint()
- }
-
- onYChanged: requestPaint()
-
- onPaint: {
- var context = (timeMarks.context === null) ? getContext("2d") : timeMarks.context;
- context.reset();
- drawBackgroundBars( context, region );
-
- var totalTime = endTime - startTime;
- var spacing = width / totalTime;
-
- var initialBlockLength = 120;
- var timePerBlock = Math.pow(2, Math.floor( Math.log( totalTime / width * initialBlockLength ) / Math.LN2 ) );
- var pixelsPerBlock = timePerBlock * spacing;
- var pixelsPerSection = pixelsPerBlock / 5;
- var blockCount = width / pixelsPerBlock;
-
- var realStartTime = Math.floor(startTime/timePerBlock) * timePerBlock;
- var realStartPos = (startTime-realStartTime) * spacing;
-
- timePerPixel = timePerBlock/pixelsPerBlock;
-
- var lineStart = y < 0 ? -y : 0;
- var lineEnd = Math.min(height, labels.height - y);
-
- for (var ii = 0; ii < blockCount+1; ii++) {
- var x = Math.floor(ii*pixelsPerBlock - realStartPos);
- context.strokeStyle = "#B0B0B0";
- context.beginPath();
- context.moveTo(x, lineStart);
- context.lineTo(x, lineEnd);
- context.stroke();
-
- context.strokeStyle = "#CCCCCC";
- for (var jj=1; jj < 5; jj++) {
- var xx = Math.floor(ii*pixelsPerBlock + jj*pixelsPerSection - realStartPos);
- context.beginPath();
- context.moveTo(xx, lineStart);
- context.lineTo(xx, lineEnd);
- context.stroke();
- }
- }
- }
-
- function updateMarks(start, end) {
- if (startTime !== start || endTime !== end) {
- startTime = start;
- endTime = end;
- requestPaint();
- }
- }
-
- function prettyPrintScale(amount) {
- var unitOffset = 0;
- for (unitOffset = 0; amount > (1 << ((unitOffset + 1) * 10)); ++unitOffset) {}
- var result = (amount >> (unitOffset * 10));
- if (result < 100) {
- var comma = Math.round(((amount >> ((unitOffset - 1) * 10)) & 1023) *
- (result < 10 ? 100 : 10) / 1024);
- if (comma < 10 && result < 10)
- return result + ".0" + comma + units[unitOffset];
- else
- return result + "." + comma + units[unitOffset];
- } else {
- return result + units[unitOffset];
- }
- }
-
- function drawBackgroundBars( context, region ) {
- var colorIndex = true;
-
- context.font = "8px sans-serif";
-
- // separators
- var cumulatedHeight = y < 0 ? -y : 0;
- for (var modelIndex = 0; modelIndex < qmlProfilerModelProxy.modelCount(); ++modelIndex) {
- var modelHeight = qmlProfilerModelProxy.models[modelIndex].height;
- if (cumulatedHeight + modelHeight < y) {
- cumulatedHeight += modelHeight;
- if (qmlProfilerModelProxy.rowCount(modelIndex) % 2 !== 0)
- colorIndex = !colorIndex;
- continue;
- }
-
- for (var row = 0; row < qmlProfilerModelProxy.rowCount(modelIndex); ++row) {
- // row background
- var rowHeight = qmlProfilerModelProxy.rowHeight(modelIndex, row)
- cumulatedHeight += rowHeight;
- colorIndex = !colorIndex;
- if (cumulatedHeight < y - rowHeight)
- continue;
- context.strokeStyle = context.fillStyle = colorIndex ? "#f0f0f0" : "white";
- context.fillRect(0, cumulatedHeight - rowHeight - y, width, rowHeight);
-
- if (rowHeight >= scaleMinHeight) {
- var minVal = qmlProfilerModelProxy.rowMinValue(modelIndex, row);
- var maxVal = qmlProfilerModelProxy.rowMaxValue(modelIndex, row);
- if (minVal !== maxVal) {
- context.strokeStyle = context.fillStyle = "#B0B0B0";
-
- var stepValUgly = Math.ceil((maxVal - minVal) /
- Math.floor(rowHeight / scaleStepping));
-
- // align to clean 2**x
- var stepVal = 1;
- while (stepValUgly >>= 1)
- stepVal <<= 1;
-
- var stepHeight = rowHeight / (maxVal - minVal);
-
- for (var step = minVal; step <= maxVal - stepVal; step += stepVal) {
- var offset = cumulatedHeight - step * stepHeight - y;
- context.beginPath();
- context.moveTo(0, offset);
- context.lineTo(width, offset);
- context.stroke();
- context.fillText(prettyPrintScale(step), 5, offset - 2);
- }
- context.beginPath();
- context.moveTo(0, cumulatedHeight - rowHeight - y);
- context.lineTo(width, cumulatedHeight - rowHeight - y);
- context.stroke();
- context.fillText(prettyPrintScale(maxVal), 5,
- cumulatedHeight - rowHeight - y + 8);
-
- }
- }
-
- if (cumulatedHeight > y + height)
- return;
- }
-
- context.strokeStyle = "#B0B0B0";
- context.beginPath();
- context.moveTo(0, cumulatedHeight - y);
- context.lineTo(width, cumulatedHeight - y);
- context.stroke();
- }
-
- // bottom
- if (height > labels.height - y) {
- context.fillStyle = "#f5f5f5";
- context.fillRect(0, labels.height - y, width, height - labels.height + y);
- }
- }
-}
diff --git a/src/plugins/qmlprofiler/qml/bindingloops.frag b/src/plugins/qmlprofiler/qml/bindingloops.frag
new file mode 100644
index 00000000000..8f364adea43
--- /dev/null
+++ b/src/plugins/qmlprofiler/qml/bindingloops.frag
@@ -0,0 +1,35 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+vec4 orange = vec4(1.0, 165.0 / 255.0, 0.0, 1.0);
+void main()
+{
+ gl_FragColor = orange;
+}
diff --git a/src/plugins/qmlprofiler/qml/bindingloops.vert b/src/plugins/qmlprofiler/qml/bindingloops.vert
new file mode 100644
index 00000000000..83cba1879ae
--- /dev/null
+++ b/src/plugins/qmlprofiler/qml/bindingloops.vert
@@ -0,0 +1,43 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+attribute vec4 vertexCoord;
+attribute vec2 postScaleOffset;
+
+uniform mat4 matrix;
+
+void main()
+{
+ gl_Position = matrix * vertexCoord;
+ gl_Position.x += postScaleOffset.x * 0.005;
+ gl_Position.y += postScaleOffset.y * 0.01;
+ gl_Position.z -= 0.1;
+ gl_Position.w = 1.0;
+}
diff --git a/src/plugins/qmlprofiler/qml/qmlprofiler.qrc b/src/plugins/qmlprofiler/qml/qmlprofiler.qrc
index 0e13b920550..9bf29785073 100644
--- a/src/plugins/qmlprofiler/qml/qmlprofiler.qrc
+++ b/src/plugins/qmlprofiler/qml/qmlprofiler.qrc
@@ -1,34 +1,9 @@
<RCC>
<qresource prefix="/qmlprofiler">
- <file>Detail.qml</file>
- <file>CategoryLabel.qml</file>
- <file>MainView.qml</file>
- <file>RangeDetails.qml</file>
- <file>RangeMover.qml</file>
- <file>TimeDisplay.qml</file>
<file>clean_pane_small.png</file>
<file>recordOff.png</file>
<file>recordOn.png</file>
- <file>lock_closed.png</file>
- <file>lock_open.png</file>
- <file>ico_edit.png</file>
- <file>TimeMarks.qml</file>
- <file>Overview.qml</file>
- <file>Overview.js</file>
- <file>SelectionRange.qml</file>
- <file>SelectionRangeDetails.qml</file>
- <file>arrow_down.png</file>
- <file>arrow_right.png</file>
- <file>dialog_shadow.png</file>
- <file>range_handle.png</file>
- <file>ico_selectionmode.png</file>
- <file>ico_zoom.png</file>
- <file>ico_prev.png</file>
- <file>ico_next.png</file>
- <file>ico_rangeselection.png</file>
- <file>ico_rangeselected.png</file>
- <file>ico_note.png</file>
- <file>ButtonsBar.qml</file>
- <file>ico_filter.png</file>
+ <file>bindingloops.vert</file>
+ <file>bindingloops.frag</file>
</qresource>
</RCC>
diff --git a/src/plugins/qmlprofiler/qmlprofiler.pro b/src/plugins/qmlprofiler/qmlprofiler.pro
index f71830c7df1..880b4bae476 100644
--- a/src/plugins/qmlprofiler/qmlprofiler.pro
+++ b/src/plugins/qmlprofiler/qmlprofiler.pro
@@ -5,82 +5,70 @@ QT += network qml quick
include(../../qtcreatorplugin.pri)
SOURCES += \
- qmlprofilerplugin.cpp \
- qmlprofilertool.cpp \
- qmlprofilerengine.cpp \
- qmlprofilerattachdialog.cpp \
localqmlprofilerrunner.cpp \
- qmlprofilereventview.cpp \
- qv8profilereventview.cpp \
+ qmlprofileranimationsmodel.cpp \
+ qmlprofilerattachdialog.cpp \
+ qmlprofilerbasemodel.cpp \
+ qmlprofilerbindingloopsrenderpass.cpp \
+ qmlprofilerclientmanager.cpp \
+ qmlprofilerdatamodel.cpp \
qmlprofilerdetailsrewriter.cpp \
- qmlprofilertraceview.cpp \
- timelinerenderer.cpp \
+ qmlprofilerengine.cpp \
+ qmlprofilereventsmodelproxy.cpp \
+ qmlprofilereventview.cpp \
+ qmlprofilermodelmanager.cpp \
+ qmlprofilernotesmodel.cpp \
+ qmlprofilerplugin.cpp \
+ qmlprofilerrangemodel.cpp \
+ qmlprofilerruncontrolfactory.cpp \
qmlprofilerstatemanager.cpp \
- qv8profilerdatamodel.cpp \
- qmlprofilerclientmanager.cpp \
- qmlprofilerviewmanager.cpp \
qmlprofilerstatewidget.cpp \
- qmlprofilerruncontrolfactory.cpp \
- qmlprofilermodelmanager.cpp \
- qmlprofilereventsmodelproxy.cpp \
- qmlprofilertimelinemodelproxy.cpp \
- qmlprofilertreeview.cpp \
+ qmlprofilertimelinemodel.cpp \
+ qmlprofilertimelinemodelfactory.cpp \
+ qmlprofilertool.cpp \
qmlprofilertracefile.cpp \
- abstracttimelinemodel.cpp \
- timelinemodelaggregator.cpp \
- qmlprofilerpainteventsmodelproxy.cpp \
- sortedtimelinemodel.cpp \
- qmlprofilerbasemodel.cpp \
- qmlprofilerdatamodel.cpp \
- notesmodel.cpp
+ qmlprofilertraceview.cpp \
+ qmlprofilertreeview.cpp \
+ qmlprofilerviewmanager.cpp \
+ qv8profilerdatamodel.cpp \
+ qv8profilereventview.cpp
HEADERS += \
- qmlprofilerconstants.h \
- qmlprofiler_global.h \
- qmlprofilerplugin.h \
- qmlprofilertool.h \
- qmlprofilerengine.h \
- qmlprofilerattachdialog.h \
abstractqmlprofilerrunner.h \
localqmlprofilerrunner.h \
- qmlprofilereventview.h \
- qv8profilereventview.h \
+ qmlprofiler_global.h \
+ qmlprofileranimationsmodel.h \
+ qmlprofilerattachdialog.h \
+ qmlprofilerbasemodel.h \
+ qmlprofilerbasemodel_p.h \
+ qmlprofilerbindingloopsrenderpass.h \
+ qmlprofilerclientmanager.h \
+ qmlprofilerconstants.h \
+ qmlprofilerdatamodel.h \
qmlprofilerdetailsrewriter.h \
- qmlprofilertraceview.h \
- timelinerenderer.h \
+ qmlprofilerengine.h \
+ qmlprofilereventsmodelproxy.h \
+ qmlprofilereventview.h \
+ qmlprofilermodelmanager.h \
+ qmlprofilernotesmodel.h \
+ qmlprofilerplugin.h \
+ qmlprofilerrangemodel.h \
+ qmlprofilerruncontrolfactory.h \
qmlprofilerstatemanager.h \
- qv8profilerdatamodel.h \
- qmlprofilerclientmanager.h \
- qmlprofilerviewmanager.h \
qmlprofilerstatewidget.h \
- qmlprofilerruncontrolfactory.h \
- qmlprofilermodelmanager.h \
- qmlprofilereventsmodelproxy.h \
- qmlprofilertimelinemodelproxy.h \
- qmlprofilertreeview.h \
+ qmlprofilertimelinemodel.h \
+ qmlprofilertimelinemodelfactory.h \
+ qmlprofilertool.h \
qmlprofilertracefile.h \
- abstracttimelinemodel.h \
- timelinemodelaggregator.h \
- qmlprofilerpainteventsmodelproxy.h \
- sortedtimelinemodel.h \
- qmlprofilerbasemodel.h \
- abstracttimelinemodel_p.h \
- qmlprofilerdatamodel.h \
- qmlprofilerbasemodel_p.h \
- notesmodel.h
+ qmlprofilertraceview.h \
+ qmlprofilertreeview.h \
+ qmlprofilerviewmanager.h \
+ qv8profilerdatamodel.h \
+ qv8profilereventview.h
RESOURCES += \
qml/qmlprofiler.qrc
DISTFILES += \
- qml/ButtonsBar.qml \
- qml/Detail.qml \
- qml/CategoryLabel.qml \
- qml/MainView.qml \
- qml/RangeDetails.qml \
- qml/RangeMover.qml \
- qml/TimeDisplay.qml \
- qml/TimeMarks.qml \
- qml/SelectionRange.qml \
- qml/SelectionRangeDetails.qml \
- qml/Overview.qml
+ qml/bindingloops.frag \
+ qml/bindingloops.vert
diff --git a/src/plugins/qmlprofiler/qmlprofiler.qbs b/src/plugins/qmlprofiler/qmlprofiler.qbs
index 198b58b070d..694d52e9f71 100644
--- a/src/plugins/qmlprofiler/qmlprofiler.qbs
+++ b/src/plugins/qmlprofiler/qmlprofiler.qbs
@@ -3,13 +3,13 @@ import qbs 1.0
QtcPlugin {
name: "QmlProfiler"
- Depends { name: "Qt"; submodules: ["widgets", "network"] }
- Depends { name: "Qt.quick"; condition: product.condition; }
+ Depends { name: "Qt"; submodules: ["widgets", "network", "quick"] }
Depends { name: "Aggregation" }
Depends { name: "QmlJS" }
Depends { name: "QmlDebug" }
Depends { name: "QtcSsh" }
Depends { name: "Utils" }
+ Depends { name: "Timeline" }
Depends { name: "Core" }
Depends { name: "AnalyzerBase" }
@@ -21,13 +21,12 @@ QtcPlugin {
name: "General"
files: [
"abstractqmlprofilerrunner.h",
- "abstracttimelinemodel.h", "abstracttimelinemodel_p.h", "abstracttimelinemodel.cpp",
"localqmlprofilerrunner.cpp", "localqmlprofilerrunner.h",
- "notesmodel.cpp",
- "notesmodel.h",
"qmlprofiler_global.h",
+ "qmlprofileranimationsmodel.h", "qmlprofileranimationsmodel.cpp",
"qmlprofilerattachdialog.cpp", "qmlprofilerattachdialog.h",
"qmlprofilerbasemodel.cpp", "qmlprofilerbasemodel.h", "qmlprofilerbasemodel_p.h",
+ "qmlprofilerbindingloopsrenderpass.cpp","qmlprofilerbindingloopsrenderpass.h",
"qmlprofilerclientmanager.cpp", "qmlprofilerclientmanager.h",
"qmlprofilerconstants.h",
"qmlprofilerdatamodel.cpp", "qmlprofilerdatamodel.h",
@@ -36,12 +35,14 @@ QtcPlugin {
"qmlprofilereventsmodelproxy.cpp", "qmlprofilereventsmodelproxy.h",
"qmlprofilereventview.cpp", "qmlprofilereventview.h",
"qmlprofilermodelmanager.cpp", "qmlprofilermodelmanager.h",
- "qmlprofilerpainteventsmodelproxy.h", "qmlprofilerpainteventsmodelproxy.cpp",
+ "qmlprofilernotesmodel.cpp", "qmlprofilernotesmodel.h",
"qmlprofilerplugin.cpp", "qmlprofilerplugin.h",
"qmlprofilerruncontrolfactory.cpp", "qmlprofilerruncontrolfactory.h",
"qmlprofilerstatemanager.cpp", "qmlprofilerstatemanager.h",
"qmlprofilerstatewidget.cpp", "qmlprofilerstatewidget.h",
- "qmlprofilertimelinemodelproxy.cpp", "qmlprofilertimelinemodelproxy.h",
+ "qmlprofilerrangemodel.cpp", "qmlprofilerrangemodel.h",
+ "qmlprofilertimelinemodel.cpp", "qmlprofilertimelinemodel.h",
+ "qmlprofilertimelinemodelfactory.cpp", "qmlprofilertimelinemodelfactory.h",
"qmlprofilertool.cpp", "qmlprofilertool.h",
"qmlprofilertracefile.cpp", "qmlprofilertracefile.h",
"qmlprofilertraceview.cpp", "qmlprofilertraceview.h",
@@ -49,29 +50,12 @@ QtcPlugin {
"qmlprofilerviewmanager.cpp", "qmlprofilerviewmanager.h",
"qv8profilerdatamodel.cpp", "qv8profilerdatamodel.h",
"qv8profilereventview.h", "qv8profilereventview.cpp",
- "sortedtimelinemodel.h", "sortedtimelinemodel.cpp",
- "timelinemodelaggregator.cpp", "timelinemodelaggregator.h",
- "timelinerenderer.cpp", "timelinerenderer.h",
]
}
Group {
name: "QML"
prefix: "qml/"
- files: [
- "ButtonsBar.qml",
- "Detail.qml",
- "CategoryLabel.qml",
- "MainView.qml",
- "Overview.js",
- "Overview.qml",
- "RangeDetails.qml",
- "RangeMover.qml",
- "SelectionRange.qml",
- "SelectionRangeDetails.qml",
- "TimeDisplay.qml",
- "TimeMarks.qml",
- "qmlprofiler.qrc",
- ]
+ files: ["qmlprofiler.qrc"]
}
}
diff --git a/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri b/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri
index f0e4624980d..114c006d9f5 100644
--- a/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri
+++ b/src/plugins/qmlprofiler/qmlprofiler_dependencies.pri
@@ -5,6 +5,7 @@ QTC_LIB_DEPENDS += \
qmldebug \
qmljs \
ssh \
+ timeline \
utils
QTC_PLUGIN_DEPENDS += \
analyzerbase \
diff --git a/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.cpp b/src/plugins/qmlprofiler/qmlprofileranimationsmodel.cpp
index 27d989c287d..7a3cf1d9c94 100644
--- a/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.cpp
+++ b/src/plugins/qmlprofiler/qmlprofileranimationsmodel.cpp
@@ -28,10 +28,9 @@
**
****************************************************************************/
-#include "qmlprofilerpainteventsmodelproxy.h"
+#include "qmlprofileranimationsmodel.h"
#include "qmlprofilermodelmanager.h"
#include "qmlprofilerdatamodel.h"
-#include "abstracttimelinemodel_p.h"
#include <utils/qtcassert.h>
#include <QCoreApplication>
@@ -46,51 +45,33 @@
namespace QmlProfiler {
namespace Internal {
-class PaintEventsModelProxy::PaintEventsModelProxyPrivate : public AbstractTimelineModelPrivate
+QmlProfilerAnimationsModel::QmlProfilerAnimationsModel(QmlProfilerModelManager *manager,
+ QObject *parent) :
+ QmlProfilerTimelineModel(manager,
+ tr(QmlProfilerModelManager::featureName(QmlDebug::ProfileAnimations)),
+ QmlDebug::Event, QmlDebug::MaximumRangeType, parent)
{
-public:
- QVector<PaintEventsModelProxy::QmlPaintEventData> data;
- int maxGuiThreadAnimations;
- int maxRenderThreadAnimations;
- int rowFromThreadId(QmlDebug::AnimationThread threadId) const;
-
-private:
- Q_DECLARE_PUBLIC(PaintEventsModelProxy)
-};
-
-PaintEventsModelProxy::PaintEventsModelProxy(QObject *parent)
- : AbstractTimelineModel(new PaintEventsModelProxyPrivate,
- tr(QmlProfilerModelManager::featureName(QmlDebug::ProfileAnimations)),
- QmlDebug::Event, QmlDebug::MaximumRangeType, parent)
-{
- Q_D(PaintEventsModelProxy);
- d->maxGuiThreadAnimations = d->maxRenderThreadAnimations = 0;
-}
-
-quint64 PaintEventsModelProxy::features() const
-{
- return 1 << QmlDebug::ProfileAnimations;
+ m_maxGuiThreadAnimations = m_maxRenderThreadAnimations = 0;
+ announceFeatures(1 << QmlDebug::ProfileAnimations);
}
-void PaintEventsModelProxy::clear()
+void QmlProfilerAnimationsModel::clear()
{
- Q_D(PaintEventsModelProxy);
- d->maxGuiThreadAnimations = d->maxRenderThreadAnimations = 0;
- d->data.clear();
- AbstractTimelineModel::clear();
+ m_maxGuiThreadAnimations = m_maxRenderThreadAnimations = 0;
+ m_data.clear();
+ QmlProfilerTimelineModel::clear();
}
-bool PaintEventsModelProxy::accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const
+bool QmlProfilerAnimationsModel::accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const
{
- return AbstractTimelineModel::accepted(event) &&
+ return QmlProfilerTimelineModel::accepted(event) &&
event.detailType== QmlDebug::AnimationFrame;
}
-void PaintEventsModelProxy::loadData()
+void QmlProfilerAnimationsModel::loadData()
{
- Q_D(PaintEventsModelProxy);
clear();
- QmlProfilerDataModel *simpleModel = d->modelManager->qmlModel();
+ QmlProfilerDataModel *simpleModel = modelManager()->qmlModel();
if (simpleModel->isEmpty())
return;
@@ -98,6 +79,7 @@ void PaintEventsModelProxy::loadData()
const QVector<QmlProfilerDataModel::QmlEventData> &referenceList = simpleModel->getEvents();
const QVector<QmlProfilerDataModel::QmlEventTypeData> &typeList = simpleModel->getEventTypes();
+ QmlDebug::AnimationThread lastThread;
QmlPaintEventData lastEvent;
qint64 minNextStartTimes[] = {0, 0};
@@ -106,7 +88,7 @@ void PaintEventsModelProxy::loadData()
if (!accepted(type))
continue;
- lastEvent.threadId = (QmlDebug::AnimationThread)event.numericData3;
+ lastThread = (QmlDebug::AnimationThread)event.numericData3;
// initial estimation of the event duration: 1/framerate
qint64 estimatedDuration = event.numericData1 > 0 ? 1e9/event.numericData1 : 1;
@@ -115,7 +97,7 @@ void PaintEventsModelProxy::loadData()
qint64 realEndTime = event.startTime;
// ranges should not overlap. If they do, our estimate wasn't accurate enough
- qint64 realStartTime = qMax(event.startTime - estimatedDuration, minNextStartTimes[lastEvent.threadId]);
+ qint64 realStartTime = qMax(event.startTime - estimatedDuration, minNextStartTimes[lastThread]);
// Sometimes our estimate is far off or the server has miscalculated the frame rate
if (realStartTime >= realEndTime)
@@ -123,68 +105,66 @@ void PaintEventsModelProxy::loadData()
// Don't "fix" the framerate even if we've fixed the duration.
// The server should know better after all and if it doesn't we want to see that.
+ lastEvent.typeId = event.typeIndex;
lastEvent.framerate = (int)event.numericData1;
lastEvent.animationcount = (int)event.numericData2;
QTC_ASSERT(lastEvent.animationcount > 0, continue);
- d->data.insert(insert(realStartTime, realEndTime - realStartTime, event.typeIndex),
- lastEvent);
+ m_data.insert(insert(realStartTime, realEndTime - realStartTime, lastThread), lastEvent);
- if (lastEvent.threadId == QmlDebug::GuiThread)
- d->maxGuiThreadAnimations = qMax(lastEvent.animationcount, d->maxGuiThreadAnimations);
+ if (lastThread == QmlDebug::GuiThread)
+ m_maxGuiThreadAnimations = qMax(lastEvent.animationcount, m_maxGuiThreadAnimations);
else
- d->maxRenderThreadAnimations =
- qMax(lastEvent.animationcount, d->maxRenderThreadAnimations);
+ m_maxRenderThreadAnimations = qMax(lastEvent.animationcount, m_maxRenderThreadAnimations);
- minNextStartTimes[lastEvent.threadId] = event.startTime + 1;
+ minNextStartTimes[lastThread] = event.startTime + 1;
- d->modelManager->modelProxyCountUpdated(d->modelId, count(), referenceList.count());
+ updateProgress(count(), referenceList.count());
}
computeNesting();
- d->expandedRowCount = d->collapsedRowCount =
- (d->maxGuiThreadAnimations == 0 || d->maxRenderThreadAnimations == 0) ? 2 : 3;
- d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1);
+ setExpandedRowCount((m_maxGuiThreadAnimations == 0 || m_maxRenderThreadAnimations == 0) ? 2 : 3);
+ setCollapsedRowCount(expandedRowCount());
+ updateProgress(1, 1);
}
/////////////////// QML interface
-int PaintEventsModelProxy::PaintEventsModelProxyPrivate::rowFromThreadId(
- QmlDebug::AnimationThread threadId) const
+int QmlProfilerAnimationsModel::rowFromThreadId(int threadId) const
{
- return (threadId == QmlDebug::GuiThread || maxGuiThreadAnimations == 0) ? 1 : 2;
+ return (threadId == QmlDebug::GuiThread || m_maxGuiThreadAnimations == 0) ? 1 : 2;
}
-int PaintEventsModelProxy::row(int index) const
+int QmlProfilerAnimationsModel::rowMaxValue(int rowNumber) const
{
- Q_D(const PaintEventsModelProxy);
- return d->rowFromThreadId(d->data[index].threadId);
-}
-
-int PaintEventsModelProxy::rowMaxValue(int rowNumber) const
-{
- Q_D(const PaintEventsModelProxy);
switch (rowNumber) {
case 1:
- return d->maxGuiThreadAnimations > 0 ? d->maxGuiThreadAnimations :
- d->maxRenderThreadAnimations;
+ return m_maxGuiThreadAnimations > 0 ? m_maxGuiThreadAnimations : m_maxRenderThreadAnimations;
case 2:
- return d->maxRenderThreadAnimations;
+ return m_maxRenderThreadAnimations;
default:
- return AbstractTimelineModel::rowMaxValue(rowNumber);
+ return QmlProfilerTimelineModel::rowMaxValue(rowNumber);
}
}
-int PaintEventsModelProxy::selectionId(int index) const
+int QmlProfilerAnimationsModel::typeId(int index) const
{
- Q_D(const PaintEventsModelProxy);
- return d->data[index].threadId;
+ return m_data[index].typeId;
}
-QColor PaintEventsModelProxy::color(int index) const
+int QmlProfilerAnimationsModel::expandedRow(int index) const
{
- Q_D(const PaintEventsModelProxy);
- double fpsFraction = d->data[index].framerate / 60.0;
+ return rowFromThreadId(selectionId(index));
+}
+
+int QmlProfilerAnimationsModel::collapsedRow(int index) const
+{
+ return rowFromThreadId(selectionId(index));
+}
+
+QColor QmlProfilerAnimationsModel::color(int index) const
+{
+ double fpsFraction = m_data[index].framerate / 60.0;
if (fpsFraction > 1.0)
fpsFraction = 1.0;
if (fpsFraction < 0.0)
@@ -192,27 +172,18 @@ QColor PaintEventsModelProxy::color(int index) const
return colorByFraction(fpsFraction);
}
-float PaintEventsModelProxy::relativeHeight(int index) const
+float QmlProfilerAnimationsModel::relativeHeight(int index) const
{
- Q_D(const PaintEventsModelProxy);
- const QmlPaintEventData &data = d->data[index];
-
- // Add some height to the events if we're far from the scale threshold of 2 * DefaultRowHeight.
- // Like that you can see the smaller events more easily.
- int scaleThreshold = 2 * DefaultRowHeight - rowHeight(d->rowFromThreadId(data.threadId));
- float boost = scaleThreshold > 0 ? (0.15 * scaleThreshold / DefaultRowHeight) : 0;
-
- return boost + (1.0 - boost) * (float)data.animationcount /
- (float)(data.threadId == QmlDebug::GuiThread ? d->maxGuiThreadAnimations :
- d->maxRenderThreadAnimations);
+ return (float)m_data[index].animationcount / (float)(selectionId(index) == QmlDebug::GuiThread ?
+ m_maxGuiThreadAnimations :
+ m_maxRenderThreadAnimations);
}
-QVariantList PaintEventsModelProxy::labels() const
+QVariantList QmlProfilerAnimationsModel::labels() const
{
- Q_D(const PaintEventsModelProxy);
QVariantList result;
- if (!d->hidden && d->maxGuiThreadAnimations > 0) {
+ if (m_maxGuiThreadAnimations > 0) {
QVariantMap element;
element.insert(QLatin1String("displayName"), QVariant(tr("Animations")));
element.insert(QLatin1String("description"), QVariant(tr("GUI Thread")));
@@ -220,7 +191,7 @@ QVariantList PaintEventsModelProxy::labels() const
result << element;
}
- if (!d->hidden && d->maxRenderThreadAnimations > 0) {
+ if (m_maxRenderThreadAnimations > 0) {
QVariantMap element;
element.insert(QLatin1String("displayName"), QVariant(tr("Animations")));
element.insert(QLatin1String("description"), QVariant(tr("Render Thread")));
@@ -231,17 +202,16 @@ QVariantList PaintEventsModelProxy::labels() const
return result;
}
-QVariantMap PaintEventsModelProxy::details(int index) const
+QVariantMap QmlProfilerAnimationsModel::details(int index) const
{
- Q_D(const PaintEventsModelProxy);
QVariantMap result;
result.insert(QStringLiteral("displayName"), displayName());
- result.insert(tr("Duration"), QmlProfilerBaseModel::formatTime(range(index).duration));
- result.insert(tr("Framerate"), QString::fromLatin1("%1 FPS").arg(d->data[index].framerate));
- result.insert(tr("Animations"), QString::fromLatin1("%1").arg(d->data[index].animationcount));
- result.insert(tr("Context"), tr(d->data[index].threadId == QmlDebug::GuiThread ?
- "GUI Thread" : "Render Thread"));
+ result.insert(tr("Duration"), QmlProfilerBaseModel::formatTime(duration(index)));
+ result.insert(tr("Framerate"), QString::fromLatin1("%1 FPS").arg(m_data[index].framerate));
+ result.insert(tr("Animations"), QString::fromLatin1("%1").arg(m_data[index].animationcount));
+ result.insert(tr("Context"), tr(selectionId(index) == QmlDebug::GuiThread ? "GUI Thread" :
+ "Render Thread"));
return result;
}
diff --git a/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.h b/src/plugins/qmlprofiler/qmlprofileranimationsmodel.h
index bcc0a8f87e3..80f27d9fe37 100644
--- a/src/plugins/qmlprofiler/qmlprofilerpainteventsmodelproxy.h
+++ b/src/plugins/qmlprofiler/qmlprofileranimationsmodel.h
@@ -29,11 +29,11 @@
****************************************************************************/
-#ifndef QMLPROFILERPAINTEVENTSMODELPROXY_H
-#define QMLPROFILERPAINTEVENTSMODELPROXY_H
+#ifndef QMLPROFILERANIMATIONSMODEL_H
+#define QMLPROFILERANIMATIONSMODEL_H
#include <QObject>
-#include "abstracttimelinemodel.h"
+#include "qmlprofilertimelinemodel.h"
#include <qmldebug/qmlprofilereventtypes.h>
#include <qmldebug/qmlprofilereventlocation.h>
//#include <QHash>
@@ -49,7 +49,7 @@ class QmlProfilerModelManager;
namespace Internal {
-class PaintEventsModelProxy : public AbstractTimelineModel
+class QmlProfilerAnimationsModel : public QmlProfilerTimelineModel
{
Q_OBJECT
public:
@@ -57,22 +57,22 @@ public:
struct QmlPaintEventData {
int framerate;
int animationcount;
- QmlDebug::AnimationThread threadId;
+ int typeId;
};
- PaintEventsModelProxy(QObject *parent = 0);
+ QmlProfilerAnimationsModel(QmlProfilerModelManager *manager, QObject *parent = 0);
int rowMaxValue(int rowNumber) const;
- int selectionId(int index) const;
- int row(int index) const;
+ int typeId(int index) const;
+ Q_INVOKABLE int expandedRow(int index) const;
+ Q_INVOKABLE int collapsedRow(int index) const;
QColor color(int index) const;
float relativeHeight(int index) const;
QVariantList labels() const;
QVariantMap details(int index) const;
- quint64 features() const;
bool accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const;
@@ -81,11 +81,13 @@ protected:
void clear();
private:
- class PaintEventsModelProxyPrivate;
- Q_DECLARE_PRIVATE(PaintEventsModelProxy)
+ QVector<QmlProfilerAnimationsModel::QmlPaintEventData> m_data;
+ int m_maxGuiThreadAnimations;
+ int m_maxRenderThreadAnimations;
+ int rowFromThreadId(int threadId) const;
};
}
}
-#endif
+#endif // QMLPROFILERANIMATIONSMODEL_H
diff --git a/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp b/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp
new file mode 100644
index 00000000000..b75e0ca5032
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.cpp
@@ -0,0 +1,359 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "qmlprofilerbindingloopsrenderpass.h"
+
+namespace QmlProfiler {
+namespace Internal {
+
+class BindingLoopMaterial : public QSGMaterial {
+public:
+ QSGMaterialType *type() const;
+ QSGMaterialShader *createShader() const;
+ BindingLoopMaterial();
+};
+
+struct BindingLoopsRenderPassState : public Timeline::TimelineRenderPass::State {
+ BindingLoopsRenderPassState() : indexFrom(std::numeric_limits<int>::max()), indexTo(-1) {}
+ BindingLoopMaterial material;
+ int indexFrom;
+ int indexTo;
+
+ QVector<QSGNode *> m_expandedRows;
+ const QVector<QSGNode *> &expandedRows() const { return m_expandedRows; }
+
+ QSGNode *m_collapsedOverlay;
+ QSGNode *collapsedOverlay() const { return m_collapsedOverlay; }
+};
+
+struct Point2DWithOffset {
+ float x, y, x2, y2;
+ void set(float nx, float ny, float nx2, float ny2);
+};
+
+struct BindlingLoopsGeometry {
+ static const QSGGeometry::AttributeSet &point2DWithOffset();
+ static const int maxEventsPerNode = 0xffff / 18;
+
+ BindlingLoopsGeometry() : allocatedVertices(0), usedVertices(0), currentY(-1), node(0) {}
+ uint allocatedVertices;
+ uint usedVertices;
+ float currentY;
+
+ QSGGeometryNode *node;
+ Point2DWithOffset *vertexData();
+
+ void allocate(QSGMaterial *material);
+ void addExpandedEvent(float itemCenter);
+ void addCollapsedEvent(float horizontalCenterSource, float horizontalCenterTarget,
+ float verticalCenterSource, float verticalCenterTarget);
+};
+
+const QmlProfilerBindingLoopsRenderPass *QmlProfilerBindingLoopsRenderPass::instance()
+{
+ static const QmlProfilerBindingLoopsRenderPass pass;
+ return &pass;
+}
+
+QmlProfilerBindingLoopsRenderPass::QmlProfilerBindingLoopsRenderPass()
+{
+}
+
+void updateNodes(const QmlProfilerRangeModel *model, int from, int to,
+ const Timeline::TimelineRenderState *parentState,
+ BindingLoopsRenderPassState *state)
+{
+ QVector<BindlingLoopsGeometry> expandedPerRow(model->expandedRowCount());
+ BindlingLoopsGeometry collapsed;
+
+ for (int i = from; i < to; ++i) {
+ int bindingLoopDest = model->bindingLoopDest(i);
+ if (bindingLoopDest == -1)
+ continue;
+
+ qint64 start = qMax(parentState->start(), model->startTime(i));
+ qint64 end = qMin(parentState->end(), model->startTime(i) + model->duration(i));
+
+ if (start > end)
+ continue;
+
+ expandedPerRow[model->expandedRow(i)].usedVertices += 4;
+ collapsed.usedVertices += 18;
+ }
+
+ for (int i = 0; i < model->expandedRowCount(); ++i) {
+ BindlingLoopsGeometry &row = expandedPerRow[i];
+ if (row.usedVertices > 0) {
+ row.allocate(&state->material);
+ state->m_expandedRows[i]->appendChildNode(row.node);
+ }
+ }
+
+ if (collapsed.usedVertices > 0) {
+ collapsed.allocate(&state->material);
+ state->m_collapsedOverlay->appendChildNode(collapsed.node);
+ }
+
+ int rowHeight = Timeline::TimelineModel::defaultRowHeight();
+ for (int i = from; i < to; ++i) {
+ int bindingLoopDest = model->bindingLoopDest(i);
+ if (bindingLoopDest == -1)
+ continue;
+
+ if (model->startTime(i) > parentState->end() || model->endTime(i) < parentState->start())
+ continue;
+
+ qint64 center = qMax(parentState->start(), qMin(parentState->end(),
+ (model->startTime(i) + model->endTime(i)) /
+ (qint64)2));
+
+ float itemCenter = (center - parentState->start()) * parentState->scale();
+ expandedPerRow[model->expandedRow(i)].addExpandedEvent(itemCenter);
+
+ center = qMax(parentState->start(), qMin(parentState->end(),
+ (model->startTime(bindingLoopDest) +
+ model->endTime(bindingLoopDest)) / (qint64)2));
+
+ float itemCenterTarget = (center - parentState->start()) * parentState->scale();
+ collapsed.addCollapsedEvent(itemCenter, itemCenterTarget,
+ (model->collapsedRow(i) + 0.5) * rowHeight,
+ (model->collapsedRow(bindingLoopDest) + 0.5) * rowHeight);
+ }
+}
+
+Timeline::TimelineRenderPass::State *QmlProfilerBindingLoopsRenderPass::update(
+ const Timeline::TimelineAbstractRenderer *renderer,
+ const Timeline::TimelineRenderState *parentState, State *oldState,
+ int indexFrom, int indexTo, bool stateChanged, qreal spacing) const
+{
+ Q_UNUSED(stateChanged);
+ Q_UNUSED(spacing);
+
+ const QmlProfilerRangeModel *model = qobject_cast<const QmlProfilerRangeModel *>(
+ renderer->model());
+
+ if (!model || indexFrom < 0 || indexTo > model->count())
+ return oldState;
+
+ BindingLoopsRenderPassState *state;
+ if (oldState == 0) {
+ state = new BindingLoopsRenderPassState;
+ state->m_expandedRows.reserve(model->expandedRowCount());
+ for (int i = 0; i < model->expandedRowCount(); ++i)
+ state->m_expandedRows << new QSGNode;
+ state->m_collapsedOverlay = new QSGNode;
+ } else {
+ state = static_cast<BindingLoopsRenderPassState *>(oldState);
+ }
+
+ if (state->indexFrom < state->indexTo) {
+ if (indexFrom < state->indexFrom) {
+ for (int i = indexFrom; i < state->indexFrom;
+ i += BindlingLoopsGeometry::maxEventsPerNode)
+ updateNodes(model, i, qMin(i + BindlingLoopsGeometry::maxEventsPerNode,
+ state->indexFrom), parentState, state);
+ }
+ if (indexTo > state->indexTo) {
+ for (int i = state->indexTo; i < indexTo; i+= BindlingLoopsGeometry::maxEventsPerNode)
+ updateNodes(model, i, qMin(i + BindlingLoopsGeometry::maxEventsPerNode, indexTo),
+ parentState, state);
+ }
+ } else {
+ for (int i = indexFrom; i < indexTo; i+= BindlingLoopsGeometry::maxEventsPerNode)
+ updateNodes(model, i, qMin(i + BindlingLoopsGeometry::maxEventsPerNode, indexTo),
+ parentState, state);
+ }
+
+ state->indexFrom = qMin(state->indexFrom, indexFrom);
+ state->indexTo = qMax(state->indexTo, indexTo);
+ return state;
+}
+
+const QSGGeometry::AttributeSet &BindlingLoopsGeometry::point2DWithOffset()
+{
+ static QSGGeometry::Attribute data[] = {
+ QSGGeometry::Attribute::create(0, 2, GL_FLOAT, true),
+ QSGGeometry::Attribute::create(1, 2, GL_FLOAT),
+ };
+ static QSGGeometry::AttributeSet attrs = {
+ 2,
+ sizeof(Point2DWithOffset),
+ data
+ };
+ return attrs;
+}
+
+Point2DWithOffset *BindlingLoopsGeometry::vertexData()
+{
+ QSGGeometry *geometry = node->geometry();
+ Q_ASSERT(geometry->attributeCount() == 2);
+ Q_ASSERT(geometry->sizeOfVertex() == sizeof(Point2DWithOffset));
+ const QSGGeometry::Attribute *attributes = geometry->attributes();
+ Q_ASSERT(attributes[0].position == 0);
+ Q_ASSERT(attributes[0].tupleSize == 2);
+ Q_ASSERT(attributes[0].type == GL_FLOAT);
+ Q_ASSERT(attributes[1].position == 1);
+ Q_ASSERT(attributes[1].tupleSize == 2);
+ Q_ASSERT(attributes[1].type == GL_FLOAT);
+ Q_UNUSED(attributes);
+ return static_cast<Point2DWithOffset *>(geometry->vertexData());
+}
+
+void BindlingLoopsGeometry::allocate(QSGMaterial *material)
+{
+ QSGGeometry *geometry = new QSGGeometry(BindlingLoopsGeometry::point2DWithOffset(),
+ usedVertices);
+ geometry->setIndexDataPattern(QSGGeometry::StaticPattern);
+ geometry->setVertexDataPattern(QSGGeometry::StaticPattern);
+ node = new QSGGeometryNode;
+ node->setGeometry(geometry);
+ node->setFlag(QSGNode::OwnsGeometry, true);
+ node->setMaterial(material);
+ allocatedVertices = usedVertices;
+ usedVertices = 0;
+}
+
+void BindlingLoopsGeometry::addExpandedEvent(float itemCenter)
+{
+ float verticalCenter = Timeline::TimelineModel::defaultRowHeight() / 2.0;
+ Point2DWithOffset *v = vertexData() + usedVertices;
+ v[0].set(itemCenter, verticalCenter, -1.0f, currentY);
+ v[1].set(itemCenter, verticalCenter, +1.0f, currentY);
+ currentY = -currentY;
+ v[2].set(itemCenter, verticalCenter, -1.0f, currentY);
+ v[3].set(itemCenter, verticalCenter, +1.0f, currentY);
+ usedVertices += 4;
+}
+
+void BindlingLoopsGeometry::addCollapsedEvent(float horizontalCenterSource,
+ float horizontalCenterTarget,
+ float verticalCenterSource,
+ float verticalCenterTarget)
+{
+ if (verticalCenterSource < verticalCenterTarget) {
+ qSwap(verticalCenterSource, verticalCenterTarget);
+ qSwap(horizontalCenterSource, horizontalCenterTarget);
+ }
+
+ float tilt = horizontalCenterSource < horizontalCenterTarget ? +0.3 : -0.3;
+
+ Point2DWithOffset *v = vertexData() + usedVertices;
+ v[0].set(horizontalCenterSource, verticalCenterSource, -0.3f, tilt);
+ v[1].set(horizontalCenterSource, verticalCenterSource, -0.3f, tilt);
+ v[2].set(horizontalCenterSource, verticalCenterSource, +0.3f, -tilt);
+
+ v[3].set(horizontalCenterTarget, verticalCenterTarget, -0.3f, tilt);
+ v[4].set(horizontalCenterTarget, verticalCenterTarget, +0.3f, -tilt);
+ v[5].set(horizontalCenterTarget, verticalCenterTarget, -1.0f, -1.0f);
+ v[6].set(horizontalCenterTarget, verticalCenterTarget, +1.0f, -1.0f);
+ v[7].set(horizontalCenterTarget, verticalCenterTarget, -1.0f, +1.0f);
+ v[8].set(horizontalCenterTarget, verticalCenterTarget, +1.0f, +1.0f);
+ v[9].set(horizontalCenterTarget, verticalCenterTarget, -0.3f, tilt);
+ v[10].set(horizontalCenterTarget, verticalCenterTarget, +0.3f, -tilt);
+
+ v[11].set(horizontalCenterSource, verticalCenterSource, -0.3f, tilt);
+ v[12].set(horizontalCenterSource, verticalCenterSource, +0.3f, -tilt);
+ v[13].set(horizontalCenterSource, verticalCenterSource, -1.0f, +1.0f);
+ v[14].set(horizontalCenterSource, verticalCenterSource, +1.0f, +1.0f);
+ v[15].set(horizontalCenterSource, verticalCenterSource, -1.0f, -1.0f);
+ v[16].set(horizontalCenterSource, verticalCenterSource, +1.0f, -1.0f);
+ v[17].set(horizontalCenterSource, verticalCenterSource, +1.0f, -1.0f);
+
+ usedVertices += 18;
+}
+
+class BindingLoopMaterialShader : public QSGMaterialShader
+{
+public:
+ BindingLoopMaterialShader();
+
+ virtual void updateState(const RenderState &state, QSGMaterial *newEffect,
+ QSGMaterial *oldEffect);
+ virtual char const *const *attributeNames() const;
+
+private:
+ virtual void initialize();
+
+ int m_matrix_id;
+ int m_z_range_id;
+};
+
+BindingLoopMaterialShader::BindingLoopMaterialShader()
+ : QSGMaterialShader()
+{
+ setShaderSourceFile(QOpenGLShader::Vertex, QStringLiteral(":/qmlprofiler/bindingloops.vert"));
+ setShaderSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/qmlprofiler/bindingloops.frag"));
+}
+
+void BindingLoopMaterialShader::updateState(const RenderState &state, QSGMaterial *, QSGMaterial *)
+{
+ if (state.isMatrixDirty()) {
+ program()->setUniformValue(m_matrix_id, state.combinedMatrix());
+ program()->setUniformValue(m_z_range_id, GLfloat(1.0));
+ }
+}
+
+char const *const *BindingLoopMaterialShader::attributeNames() const
+{
+ static const char *const attr[] = {"vertexCoord", "postScaleOffset", 0};
+ return attr;
+}
+
+void BindingLoopMaterialShader::initialize()
+{
+ m_matrix_id = program()->uniformLocation("matrix");
+ m_z_range_id = program()->uniformLocation("_qt_zRange");
+}
+
+
+BindingLoopMaterial::BindingLoopMaterial()
+{
+ setFlag(QSGMaterial::Blending, false);
+}
+
+QSGMaterialType *BindingLoopMaterial::type() const
+{
+ static QSGMaterialType type;
+ return &type;
+}
+
+QSGMaterialShader *BindingLoopMaterial::createShader() const
+{
+ return new BindingLoopMaterialShader;
+}
+
+void Point2DWithOffset::set(float nx, float ny, float nx2, float ny2)
+{
+ x = nx; y = ny; x2 = nx2; y2 = ny2;
+}
+
+
+}
+}
diff --git a/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.h b/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.h
new file mode 100644
index 00000000000..712e1d705a1
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilerbindingloopsrenderpass.h
@@ -0,0 +1,59 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 QMLPROFILERBINDINGLOOPSRENDERPASS_H
+#define QMLPROFILERBINDINGLOOPSRENDERPASS_H
+
+#include "timeline/timelineabstractrenderer.h"
+#include "timeline/timelinerenderpass.h"
+#include "timeline/timelinerenderstate.h"
+#include "qmlprofilerrangemodel.h"
+#include <QSGMaterial>
+
+namespace QmlProfiler {
+namespace Internal {
+
+class QmlProfilerBindingLoopsRenderPass : public Timeline::TimelineRenderPass
+{
+public:
+ static const QmlProfilerBindingLoopsRenderPass *instance();
+ State *update(const Timeline::TimelineAbstractRenderer *renderer,
+ const Timeline::TimelineRenderState *parentState,
+ State *oldState, int indexFrom, int indexTo, bool stateChanged,
+ qreal spacing) const;
+protected:
+ QmlProfilerBindingLoopsRenderPass();
+};
+
+}
+}
+
+#endif // QMLPROFILERBINDINGLOOPSRENDERPASS_H
+
diff --git a/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp b/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
index 8e51654bf42..8585211e746 100644
--- a/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
@@ -219,9 +219,9 @@ void QmlProfilerClientManager::disconnectClientSignals()
SLOT(addQmlEvent(int,int,qint64,qint64,QStringList,QmlDebug::QmlEventLocation,
qint64,qint64,qint64,qint64,qint64)));
disconnect(d->qmlclientplugin.data(), SIGNAL(traceFinished(qint64)),
- d->modelManager->traceTime(), SLOT(setEndTime(qint64)));
+ d->modelManager->traceTime(), SLOT(increaseEndTime(qint64)));
disconnect(d->qmlclientplugin.data(), SIGNAL(traceStarted(qint64)),
- d->modelManager->traceTime(), SLOT(setStartTime(qint64)));
+ d->modelManager->traceTime(), SLOT(decreaseStartTime(qint64)));
disconnect(d->qmlclientplugin.data(), SIGNAL(enabledChanged()),
d->qmlclientplugin.data(), SLOT(sendRecordingStatus()));
// fixme: this should be unified for both clients
@@ -339,8 +339,7 @@ void QmlProfilerClientManager::retryMessageBoxFinished(int result)
void QmlProfilerClientManager::qmlComplete(qint64 maximumTime)
{
- if (maximumTime > d->modelManager->traceTime()->endTime())
- d->modelManager->traceTime()->setEndTime(maximumTime);
+ d->modelManager->traceTime()->increaseEndTime(maximumTime);
d->qmlDataReady = true;
if (!d->v8clientplugin ||
d->v8clientplugin.data()->state() != QmlDebug::QmlDebugClient::Enabled ||
diff --git a/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp b/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
index 14618a7cd0f..15495d6c00d 100644
--- a/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
@@ -31,7 +31,7 @@
#include "qmlprofilerdatamodel.h"
#include "qmlprofilerbasemodel_p.h"
#include "qmlprofilermodelmanager.h"
-#include "notesmodel.h"
+#include "qmlprofilernotesmodel.h"
#include <qmldebug/qmlprofilereventtypes.h>
#include <utils/qtcassert.h>
#include <QUrl>
@@ -121,10 +121,12 @@ const QVector<QmlProfilerDataModel::QmlEventNoteData> &QmlProfilerDataModel::get
return d->eventNotes;
}
-void QmlProfilerDataModel::setData(const QVector<QmlProfilerDataModel::QmlEventTypeData> &types,
+void QmlProfilerDataModel::setData(qint64 traceStart, qint64 traceEnd,
+ const QVector<QmlProfilerDataModel::QmlEventTypeData> &types,
const QVector<QmlProfilerDataModel::QmlEventData> &events)
{
Q_D(QmlProfilerDataModel);
+ d->modelManager->traceTime()->setTime(traceStart, traceEnd);
d->eventList = events;
d->eventTypes = types;
for (int id = 0; id < types.count(); ++id)
@@ -260,7 +262,7 @@ void QmlProfilerDataModel::addQmlEvent(QmlDebug::Message message, QmlDebug::Rang
d->eventList.append(eventData);
d->modelManager->modelProxyCountUpdated(d->modelId, startTime,
- d->modelManager->estimatedProfilingTime() * 2);
+ d->modelManager->traceTime()->duration() * 2);
}
qint64 QmlProfilerDataModel::lastTimeMark() const
diff --git a/src/plugins/qmlprofiler/qmlprofilerdatamodel.h b/src/plugins/qmlprofiler/qmlprofilerdatamodel.h
index 0dd37d97022..a9833e397fa 100644
--- a/src/plugins/qmlprofiler/qmlprofilerdatamodel.h
+++ b/src/plugins/qmlprofiler/qmlprofilerdatamodel.h
@@ -72,7 +72,8 @@ public:
const QVector<QmlEventData> &getEvents() const;
const QVector<QmlEventTypeData> &getEventTypes() const;
const QVector<QmlEventNoteData> &getEventNotes() const;
- void setData(const QVector<QmlEventTypeData> &types, const QVector<QmlEventData> &events);
+ void setData(qint64 traceStart, qint64 traceEnd, const QVector<QmlEventTypeData> &types,
+ const QVector<QmlEventData> &events);
void setNoteData(const QVector<QmlEventNoteData> &notes);
int count() const;
diff --git a/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp
index 8a93f8bad1e..b34a510a8cb 100644
--- a/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.cpp
@@ -138,7 +138,7 @@ void QmlProfilerEventsModelProxy::dataChanged()
void QmlProfilerEventsModelProxy::notesChanged(int typeIndex)
{
- const NotesModel *notesModel = d->modelManager->notesModel();
+ const QmlProfilerNotesModel *notesModel = d->modelManager->notesModel();
if (typeIndex == -1) {
d->notes.clear();
for (int noteId = 0; noteId < notesModel->count(); ++noteId) {
diff --git a/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h
index 00458e6a65e..f98f8ea5ec0 100644
--- a/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h
+++ b/src/plugins/qmlprofiler/qmlprofilereventsmodelproxy.h
@@ -33,7 +33,7 @@
#define QMLPROFILEREVENTSMODELPROXY_H
#include "qmlprofilerdatamodel.h"
-#include "notesmodel.h"
+#include "qmlprofilernotesmodel.h"
#include <QObject>
#include <qmldebug/qmlprofilereventtypes.h>
#include <qmldebug/qmlprofilereventlocation.h>
diff --git a/src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp b/src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp
index f06a83bebf1..0174a51090c 100644
--- a/src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilermodelmanager.cpp
@@ -32,7 +32,7 @@
#include "qmlprofilerdatamodel.h"
#include "qv8profilerdatamodel.h"
#include "qmlprofilertracefile.h"
-#include "notesmodel.h"
+#include "qmlprofilernotesmodel.h"
#include <utils/qtcassert.h>
@@ -128,36 +128,33 @@ qint64 QmlProfilerTraceTime::duration() const
void QmlProfilerTraceTime::clear()
{
- setStartTime(-1);
- setEndTime(-1);
+ setTime(-1, -1);
}
-void QmlProfilerTraceTime::setStartTime(qint64 time)
+void QmlProfilerTraceTime::setTime(qint64 startTime, qint64 endTime)
{
- if (time != m_startTime) {
- m_startTime = time;
- emit startTimeChanged(time);
- }
-}
-
-void QmlProfilerTraceTime::setEndTime(qint64 time)
-{
- if (time != m_endTime) {
- m_endTime = time;
- emit endTimeChanged(time);
+ Q_ASSERT(startTime <= endTime);
+ if (startTime != m_startTime || endTime != m_endTime) {
+ m_startTime = startTime;
+ m_endTime = endTime;
+ emit timeChanged(startTime, endTime);
}
}
void QmlProfilerTraceTime::decreaseStartTime(qint64 time)
{
- if (m_startTime > time)
- setStartTime(time);
+ if (m_startTime > time) {
+ m_startTime = time;
+ emit timeChanged(time, m_endTime);
+ }
}
void QmlProfilerTraceTime::increaseEndTime(qint64 time)
{
- if (m_endTime < time)
- setEndTime(time);
+ if (m_endTime < time) {
+ m_endTime = time;
+ emit timeChanged(m_startTime, time);
+ }
}
@@ -174,7 +171,7 @@ public:
QmlProfilerDataModel *model;
QV8ProfilerDataModel *v8Model;
- NotesModel *notesModel;
+ QmlProfilerNotesModel *notesModel;
QmlProfilerDataState *dataState;
QmlProfilerTraceTime *traceTime;
@@ -186,7 +183,6 @@ public:
int totalWeight;
double progress;
double previousProgress;
- qint64 estimatedTime;
// file to load
QString fileName;
@@ -202,7 +198,7 @@ QmlProfilerModelManager::QmlProfilerModelManager(Utils::FileInProjectFinder *fin
d->v8Model = new QV8ProfilerDataModel(finder, this);
d->dataState = new QmlProfilerDataState(this, this);
d->traceTime = new QmlProfilerTraceTime(this);
- d->notesModel = new NotesModel(this);
+ d->notesModel = new QmlProfilerNotesModel(this);
d->notesModel->setModelManager(this);
}
@@ -226,7 +222,7 @@ QV8ProfilerDataModel *QmlProfilerModelManager::v8Model() const
return d->v8Model;
}
-NotesModel *QmlProfilerModelManager::notesModel() const
+QmlProfilerNotesModel *QmlProfilerModelManager::notesModel() const
{
return d->notesModel;
}
@@ -298,14 +294,9 @@ const char *QmlProfilerModelManager::featureName(QmlDebug::ProfileFeature featur
return ProfileFeatureNames[feature];
}
-qint64 QmlProfilerModelManager::estimatedProfilingTime() const
-{
- return d->estimatedTime;
-}
-
void QmlProfilerModelManager::newTimeEstimation(qint64 estimation)
{
- d->estimatedTime = estimation;
+ d->traceTime->increaseEndTime(d->traceTime->startTime() + estimation);
}
void QmlProfilerModelManager::addQmlEvent(QmlDebug::Message message,
@@ -323,7 +314,7 @@ void QmlProfilerModelManager::addQmlEvent(QmlDebug::Message message,
{
// If trace start time was not explicitly set, use the first event
if (d->traceTime->startTime() == -1)
- d->traceTime->setStartTime(startTime);
+ d->traceTime->setTime(startTime, startTime + d->traceTime->duration());
QTC_ASSERT(state() == QmlProfilerDataState::AcquiringData, /**/);
d->model->addQmlEvent(message, rangeType, detailType, startTime, length, data, location,
@@ -346,9 +337,8 @@ void QmlProfilerModelManager::complete()
emit dataAvailable();
break;
case 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());
+ // Make sure the trace fits into the time span.
+ d->traceTime->increaseEndTime(d->model->lastTimeMark());
setState(QmlProfilerDataState::ProcessingData);
d->model->complete();
d->v8Model->complete();
@@ -418,8 +408,6 @@ void QmlProfilerModelManager::load()
QmlProfilerFileReader reader;
connect(&reader, SIGNAL(error(QString)), this, SIGNAL(error(QString)));
- connect(&reader, SIGNAL(traceStartTime(qint64)), traceTime(), SLOT(setStartTime(qint64)));
- connect(&reader, SIGNAL(traceEndTime(qint64)), traceTime(), SLOT(setEndTime(qint64)));
reader.setV8DataModel(d->v8Model);
reader.setQmlDataModel(d->model);
reader.load(&file);
diff --git a/src/plugins/qmlprofiler/qmlprofilermodelmanager.h b/src/plugins/qmlprofiler/qmlprofilermodelmanager.h
index 25049d739db..775e69da9ae 100644
--- a/src/plugins/qmlprofiler/qmlprofilermodelmanager.h
+++ b/src/plugins/qmlprofiler/qmlprofilermodelmanager.h
@@ -43,7 +43,7 @@ namespace QmlProfiler {
class QmlProfilerModelManager;
class QmlProfilerDataModel;
class QV8ProfilerDataModel;
-class NotesModel;
+class QmlProfilerNotesModel;
namespace Internal {
@@ -76,7 +76,7 @@ private:
friend class QmlProfiler::QmlProfilerModelManager;
};
-class QmlProfilerTraceTime : public QObject
+class QMLPROFILER_EXPORT QmlProfilerTraceTime : public QObject
{
Q_OBJECT
public:
@@ -88,14 +88,12 @@ public:
qint64 duration() const;
signals:
- void startTimeChanged(qint64);
- void endTimeChanged(qint64);
+ void timeChanged(qint64,qint64);
public slots:
void clear();
- void setStartTime(qint64 time);
- void setEndTime(qint64 time);
+ void setTime(qint64 startTime, qint64 endTime);
void decreaseStartTime(qint64 time);
void increaseEndTime(qint64 time);
@@ -121,7 +119,7 @@ public:
QmlProfilerTraceTime *traceTime() const;
QmlProfilerDataModel *qmlModel() const;
QV8ProfilerDataModel *v8Model() const;
- NotesModel *notesModel() const;
+ QmlProfilerNotesModel *notesModel() const;
bool isEmpty() const;
int count() const;
@@ -134,8 +132,6 @@ public:
quint64 availableFeatures();
static const char *featureName(QmlDebug::ProfileFeature feature);
- qint64 estimatedProfilingTime() const;
-
signals:
void error(const QString &error);
void stateChanged();
diff --git a/src/plugins/qmlprofiler/qmlprofilernotesmodel.cpp b/src/plugins/qmlprofiler/qmlprofilernotesmodel.cpp
new file mode 100644
index 00000000000..a670771750f
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilernotesmodel.cpp
@@ -0,0 +1,109 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "qmlprofilernotesmodel.h"
+#include "qmlprofilerdatamodel.h"
+
+namespace QmlProfiler {
+
+QmlProfilerNotesModel::QmlProfilerNotesModel(QObject *parent) : TimelineNotesModel(parent),
+ m_modelManager(0)
+{
+}
+
+void QmlProfilerNotesModel::setModelManager(QmlProfilerModelManager *modelManager)
+{
+ m_modelManager = modelManager;
+}
+
+int QmlProfilerNotesModel::add(int typeId, qint64 start, qint64 duration, const QString &text)
+{
+ int timelineModel = -1;
+ int timelineIndex = -1;
+ foreach (const Timeline::TimelineModel *model, timelineModels()) {
+ if (model->handlesTypeId(typeId)) {
+ for (int i = model->firstIndex(start); i <= model->lastIndex(start + duration); ++i) {
+ if (i < 0)
+ continue;
+ if (model->typeId(i) == typeId && model->startTime(i) == start &&
+ model->duration(i) == duration) {
+ timelineModel = model->modelId();
+ timelineIndex = i;
+ break;
+ }
+ }
+ if (timelineIndex != -1)
+ break;
+ }
+ }
+
+ if (timelineModel == -1 || timelineIndex == -1)
+ return -1;
+
+ return TimelineNotesModel::add(timelineModel, timelineIndex, text);
+}
+
+
+void QmlProfilerNotesModel::loadData()
+{
+ blockSignals(true);
+ clear();
+ const QVector<QmlProfilerDataModel::QmlEventNoteData> &notes =
+ m_modelManager->qmlModel()->getEventNotes();
+ for (int i = 0; i != notes.size(); ++i) {
+ const QmlProfilerDataModel::QmlEventNoteData &note = notes[i];
+ add(note.typeIndex, note.startTime, note.duration, note.text);
+ }
+ resetModified();
+ blockSignals(false);
+ emit changed(-1, -1, -1);
+}
+
+void QmlProfilerNotesModel::saveData()
+{
+ QVector<QmlProfilerDataModel::QmlEventNoteData> notes;
+ for (int i = 0; i < count(); ++i) {
+ const Timeline::TimelineModel *model = timelineModelByModelId(timelineModel(i));
+ if (!model)
+ continue;
+
+ int index = timelineIndex(i);
+ QmlProfilerDataModel::QmlEventNoteData save = {
+ model->typeId(index),
+ model->startTime(index),
+ model->duration(index),
+ text(i)
+ };
+ notes.append(save);
+ }
+ m_modelManager->qmlModel()->setNoteData(notes);
+ resetModified();
+}
+}
diff --git a/src/plugins/qmlprofiler/qmlprofilernotesmodel.h b/src/plugins/qmlprofiler/qmlprofilernotesmodel.h
new file mode 100644
index 00000000000..51de44ed7ec
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilernotesmodel.h
@@ -0,0 +1,55 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 QMLPROFILERNOTESMODEL_H
+#define QMLPROFILERNOTESMODEL_H
+
+#include "qmlprofilermodelmanager.h"
+#include "timeline/timelinenotesmodel.h"
+#include <QList>
+#include <QHash>
+
+namespace QmlProfiler {
+class QMLPROFILER_EXPORT QmlProfilerNotesModel : public Timeline::TimelineNotesModel {
+ Q_OBJECT
+public:
+ QmlProfilerNotesModel(QObject *parent);
+
+ void setModelManager(QmlProfilerModelManager *modelManager);
+ void loadData();
+ void saveData();
+
+protected:
+ QmlProfilerModelManager *m_modelManager;
+
+ int add(int typeId, qint64 startTime, qint64 duration, const QString &text);
+};
+} // namespace QmlProfiler
+#endif // QMLPROFILERNOTESMODEL_H
diff --git a/src/plugins/qmlprofiler/qmlprofilerplugin.cpp b/src/plugins/qmlprofiler/qmlprofilerplugin.cpp
index 31755630f1a..9915dabdc7a 100644
--- a/src/plugins/qmlprofiler/qmlprofilerplugin.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerplugin.cpp
@@ -32,7 +32,7 @@
#include "qmlprofilerruncontrolfactory.h"
#include "qmlprofilertool.h"
-#include "abstracttimelinemodel.h"
+#include "qmlprofilertimelinemodel.h"
#include <analyzerbase/analyzermanager.h>
#include <extensionsystem/pluginmanager.h>
@@ -92,7 +92,7 @@ bool QmlProfilerPlugin::initialize(const QStringList &arguments, QString *errorS
void QmlProfilerPlugin::extensionsInitialized()
{
- timelineModels = ExtensionSystem::PluginManager::getObjects<AbstractTimelineModel>();
+ factory = ExtensionSystem::PluginManager::getObject<QmlProfilerTimelineModelFactory>();
}
ExtensionSystem::IPlugin::ShutdownFlag QmlProfilerPlugin::aboutToShutdown()
@@ -103,9 +103,12 @@ ExtensionSystem::IPlugin::ShutdownFlag QmlProfilerPlugin::aboutToShutdown()
return SynchronousShutdown;
}
-QList<AbstractTimelineModel *> QmlProfilerPlugin::getModels() const
+QList<QmlProfilerTimelineModel *> QmlProfilerPlugin::getModels(QmlProfilerModelManager *manager) const
{
- return timelineModels;
+ if (factory)
+ return factory->create(manager);
+ else
+ return QList<QmlProfilerTimelineModel *>();
}
} // namespace Internal
diff --git a/src/plugins/qmlprofiler/qmlprofilerplugin.h b/src/plugins/qmlprofiler/qmlprofilerplugin.h
index 814259cd1d6..b853cbb057e 100644
--- a/src/plugins/qmlprofiler/qmlprofilerplugin.h
+++ b/src/plugins/qmlprofiler/qmlprofilerplugin.h
@@ -32,10 +32,10 @@
#define QMLPROFILERPLUGIN_H
#include "qmlprofiler_global.h"
-
+#include "qmlprofilertimelinemodelfactory.h"
#include <extensionsystem/iplugin.h>
-#include "abstracttimelinemodel.h"
+#include "qmlprofilertimelinemodel.h"
namespace QmlProfiler {
namespace Internal {
@@ -46,7 +46,7 @@ class QmlProfilerPlugin : public ExtensionSystem::IPlugin
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "QmlProfiler.json")
public:
- QmlProfilerPlugin() {}
+ QmlProfilerPlugin() : factory(0) {}
bool initialize(const QStringList &arguments, QString *errorString);
void extensionsInitialized();
@@ -55,10 +55,10 @@ public:
static bool debugOutput;
static QmlProfilerPlugin *instance;
- QList<AbstractTimelineModel *> getModels() const;
+ QList<QmlProfilerTimelineModel *> getModels(QmlProfilerModelManager *manager) const;
private:
- QList<AbstractTimelineModel*> timelineModels;
+ QmlProfilerTimelineModelFactory *factory;
};
} // namespace Internal
diff --git a/src/plugins/qmlprofiler/qmlprofilerrangemodel.cpp b/src/plugins/qmlprofiler/qmlprofilerrangemodel.cpp
new file mode 100644
index 00000000000..4957d384a69
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilerrangemodel.cpp
@@ -0,0 +1,303 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "qmlprofilerrangemodel.h"
+#include "qmlprofilermodelmanager.h"
+#include "qmlprofilerdatamodel.h"
+#include "qmlprofilerbindingloopsrenderpass.h"
+#include "timeline/timelinenotesrenderpass.h"
+#include "timeline/timelineitemsrenderpass.h"
+#include "timeline/timelineselectionrenderpass.h"
+
+#include <QCoreApplication>
+#include <QVector>
+#include <QHash>
+#include <QUrl>
+#include <QString>
+#include <QStack>
+
+#include <QDebug>
+
+namespace QmlProfiler {
+namespace Internal {
+
+
+QmlProfilerRangeModel::QmlProfilerRangeModel(QmlProfilerModelManager *manager,
+ QmlDebug::RangeType range, QObject *parent) :
+ QmlProfilerTimelineModel(manager, categoryLabel(range), QmlDebug::MaximumMessage, range, parent)
+{
+ m_expandedRowTypes << -1;
+ announceFeatures(1ULL << QmlDebug::featureFromRangeType(rangeType()));
+}
+
+void QmlProfilerRangeModel::clear()
+{
+ m_expandedRowTypes.clear();
+ m_expandedRowTypes << -1;
+ m_data.clear();
+ QmlProfilerTimelineModel::clear();
+}
+
+bool QmlProfilerRangeModel::supportsBindingLoops() const
+{
+ return rangeType() == QmlDebug::Binding || rangeType() == QmlDebug::HandlingSignal;
+}
+
+void QmlProfilerRangeModel::loadData()
+{
+ clear();
+ QmlProfilerDataModel *simpleModel = modelManager()->qmlModel();
+ if (simpleModel->isEmpty())
+ return;
+
+ // collect events
+ const QVector<QmlProfilerDataModel::QmlEventData> &eventList = simpleModel->getEvents();
+ const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList = simpleModel->getEventTypes();
+ foreach (const QmlProfilerDataModel::QmlEventData &event, eventList) {
+ const QmlProfilerDataModel::QmlEventTypeData &type = typesList[event.typeIndex];
+ if (!accepted(type))
+ continue;
+
+ // store starttime-based instance
+ m_data.insert(insert(event.startTime, event.duration, event.typeIndex),
+ QmlRangeEventStartInstance());
+ updateProgress(count(), eventList.count() * 6);
+ }
+
+ updateProgress(2, 6);
+
+ // compute range nesting
+ computeNesting();
+
+ // compute nestingLevel - nonexpanded
+ computeNestingContracted();
+
+ updateProgress(3, 6);
+
+ // compute nestingLevel - expanded
+ computeExpandedLevels();
+
+ updateProgress(4, 6);
+
+ if (supportsBindingLoops())
+ findBindingLoops();
+
+ updateProgress(5, 6);
+
+ updateProgress(1, 1);
+}
+
+void QmlProfilerRangeModel::computeNestingContracted()
+{
+ int i;
+ int eventCount = count();
+
+ int nestingLevels = QmlDebug::Constants::QML_MIN_LEVEL;
+ int collapsedRowCount = nestingLevels + 1;
+ QVector<qint64> nestingEndTimes;
+ nestingEndTimes.fill(0, nestingLevels + 1);
+
+ for (i = 0; i < eventCount; i++) {
+ qint64 st = startTime(i);
+
+ // per type
+ if (nestingEndTimes[nestingLevels] > st) {
+ if (++nestingLevels == nestingEndTimes.size())
+ nestingEndTimes << 0;
+ if (nestingLevels == collapsedRowCount)
+ ++collapsedRowCount;
+ } else {
+ while (nestingLevels > QmlDebug::Constants::QML_MIN_LEVEL &&
+ nestingEndTimes[nestingLevels-1] <= st)
+ nestingLevels--;
+ }
+ nestingEndTimes[nestingLevels] = st + duration(i);
+
+ m_data[i].displayRowCollapsed = nestingLevels;
+ }
+ setCollapsedRowCount(collapsedRowCount);
+}
+
+void QmlProfilerRangeModel::computeExpandedLevels()
+{
+ QHash<int, int> eventRow;
+ int eventCount = count();
+ for (int i = 0; i < eventCount; i++) {
+ int eventTypeId = typeId(i);
+ if (!eventRow.contains(eventTypeId)) {
+ eventRow[eventTypeId] = m_expandedRowTypes.size();
+ m_expandedRowTypes << eventTypeId;
+ }
+ m_data[i].displayRowExpanded = eventRow[eventTypeId];
+ }
+ setExpandedRowCount(m_expandedRowTypes.size());
+}
+
+void QmlProfilerRangeModel::findBindingLoops()
+{
+ typedef QPair<int, int> CallStackEntry;
+ QStack<CallStackEntry> callStack;
+
+ for (int i = 0; i < count(); ++i) {
+ int potentialParent = callStack.isEmpty() ? -1 : callStack.top().second;
+
+ while (potentialParent != -1 && !(endTime(potentialParent) > startTime(i))) {
+ callStack.pop();
+ potentialParent = callStack.isEmpty() ? -1 : callStack.top().second;
+ }
+
+ // check whether event is already in stack
+ for (int ii = 0; ii < callStack.size(); ++ii) {
+ if (callStack.at(ii).first == typeId(i)) {
+ m_data[i].bindingLoopHead = callStack.at(ii).second;
+ break;
+ }
+ }
+
+ CallStackEntry newEntry(typeId(i), i);
+ callStack.push(newEntry);
+ }
+
+}
+
+/////////////////// QML interface
+
+QString QmlProfilerRangeModel::categoryLabel(QmlDebug::RangeType rangeType)
+{
+ return QCoreApplication::translate("MainView",
+ QmlProfilerModelManager::featureName(QmlDebug::featureFromRangeType(rangeType)));
+}
+
+int QmlProfilerRangeModel::expandedRow(int index) const
+{
+ return m_data[index].displayRowExpanded;
+}
+
+int QmlProfilerRangeModel::collapsedRow(int index) const
+{
+ return m_data[index].displayRowCollapsed;
+}
+
+int QmlProfilerRangeModel::bindingLoopDest(int index) const
+{
+ return m_data[index].bindingLoopHead;
+}
+
+QColor QmlProfilerRangeModel::color(int index) const
+{
+ return colorBySelectionId(index);
+}
+
+QVariantList QmlProfilerRangeModel::labels() const
+{
+ QVariantList result;
+
+ const QVector<QmlProfilerDataModel::QmlEventTypeData> &types =
+ modelManager()->qmlModel()->getEventTypes();
+ for (int i = 1; i < expandedRowCount(); i++) { // Ignore the -1 for the first row
+ QVariantMap element;
+ int typeId = m_expandedRowTypes[i];
+ element.insert(QLatin1String("displayName"), QVariant(types[typeId].displayName));
+ element.insert(QLatin1String("description"), QVariant(types[typeId].data));
+ element.insert(QLatin1String("id"), QVariant(typeId));
+ result << element;
+ }
+
+ return result;
+}
+
+QVariantMap QmlProfilerRangeModel::details(int index) const
+{
+ QVariantMap result;
+ int id = selectionId(index);
+ const QVector<QmlProfilerDataModel::QmlEventTypeData> &types =
+ modelManager()->qmlModel()->getEventTypes();
+
+ result.insert(QStringLiteral("displayName"), categoryLabel(rangeType()));
+ result.insert(tr("Duration"), QmlProfilerBaseModel::formatTime(duration(index)));
+
+ result.insert(tr("Details"), types[id].data);
+ result.insert(tr("Location"), types[id].displayName);
+ return result;
+}
+
+QVariantMap QmlProfilerRangeModel::location(int index) const
+{
+ QVariantMap result;
+ int id = selectionId(index);
+
+ const QmlDebug::QmlEventLocation &location
+ = modelManager()->qmlModel()->getEventTypes().at(id).location;
+
+ result.insert(QStringLiteral("file"), location.filename);
+ result.insert(QStringLiteral("line"), location.line);
+ result.insert(QStringLiteral("column"), location.column);
+
+ return result;
+}
+
+int QmlProfilerRangeModel::typeId(int index) const
+{
+ return selectionId(index);
+}
+
+int QmlProfilerRangeModel::selectionIdForLocation(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
+ const QVector<QmlProfilerDataModel::QmlEventTypeData> &types =
+ modelManager()->qmlModel()->getEventTypes();
+ for (int i = 1; i < expandedRowCount(); ++i) {
+ int typeId = m_expandedRowTypes[i];
+ const QmlProfilerDataModel::QmlEventTypeData &eventData = types[typeId];
+ if (eventData.location.filename == filename &&
+ eventData.location.line == line &&
+ (column == -1 || eventData.location.column == column))
+ return typeId;
+ }
+ return -1;
+}
+
+QList<const Timeline::TimelineRenderPass *> QmlProfilerRangeModel::supportedRenderPasses() const
+{
+ if (supportsBindingLoops()) {
+ QList<const Timeline::TimelineRenderPass *> passes;
+ passes << Timeline::TimelineItemsRenderPass::instance()
+ << QmlProfilerBindingLoopsRenderPass::instance()
+ << Timeline::TimelineSelectionRenderPass::instance()
+ << Timeline::TimelineNotesRenderPass::instance();
+ return passes;
+ } else {
+ return QmlProfilerTimelineModel::supportedRenderPasses();
+ }
+
+}
+
+}
+}
diff --git a/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.h b/src/plugins/qmlprofiler/qmlprofilerrangemodel.h
index b32465f1c7e..fb8e7fcb67a 100644
--- a/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.h
+++ b/src/plugins/qmlprofiler/qmlprofilerrangemodel.h
@@ -29,10 +29,10 @@
****************************************************************************/
-#ifndef QMLPROFILERTIMELINEMODELPROXY_H
-#define QMLPROFILERTIMELINEMODELPROXY_H
+#ifndef QMLPROFILERRANGEMODEL_H
+#define QMLPROFILERRANGEMODEL_H
-#include "abstracttimelinemodel.h"
+#include "qmlprofilertimelinemodel.h"
#include <qmldebug/qmlprofilereventtypes.h>
#include <qmldebug/qmlprofilereventlocation.h>
#include <QVariantList>
@@ -44,7 +44,7 @@ class QmlProfilerModelManager;
namespace Internal {
-class RangeTimelineModel : public AbstractTimelineModel
+class QmlProfilerRangeModel : public QmlProfilerTimelineModel
{
Q_OBJECT
public:
@@ -61,12 +61,13 @@ public:
int bindingLoopHead;
};
- RangeTimelineModel(QmlDebug::RangeType rangeType, QObject *parent = 0);
+ QmlProfilerRangeModel(QmlProfilerModelManager *manager, QmlDebug::RangeType range,
+ QObject *parent = 0);
static QString categoryLabel(QmlDebug::RangeType categoryIndex);
- quint64 features() const;
- int row(int index) const;
+ Q_INVOKABLE int expandedRow(int index) const;
+ Q_INVOKABLE int collapsedRow(int index) const;
int bindingLoopDest(int index) const;
QColor color(int index) const;
@@ -74,19 +75,27 @@ public:
QVariantMap details(int index) const;
QVariantMap location(int index) const;
- bool isSelectionIdValid(int typeIndex) const;
+ int typeId(int index) const;
int selectionIdForLocation(const QString &filename, int line, int column) const;
+ virtual QList<const Timeline::TimelineRenderPass *> supportedRenderPasses() const;
+
protected:
void loadData();
void clear();
private:
- class RangeTimelineModelPrivate;
- Q_DECLARE_PRIVATE(RangeTimelineModel)
+
+ bool supportsBindingLoops() const;
+ void computeNestingContracted();
+ void computeExpandedLevels();
+ void findBindingLoops();
+
+ QVector<QmlRangeEventStartInstance> m_data;
+ QVector<int> m_expandedRowTypes;
};
}
}
-#endif
+#endif // QMLPROFILERRANGEMODEL_H
diff --git a/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp b/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
index 797c6313950..7789a778149 100644
--- a/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
@@ -31,7 +31,6 @@
#include "qmlprofilerstatewidget.h"
#include <QPainter>
-
#include <QVBoxLayout>
#include <QLabel>
#include <QProgressBar>
@@ -72,7 +71,7 @@ QmlProfilerStateWidget::QmlProfilerStateWidget(QmlProfilerStateManager *stateMan
QVBoxLayout *layout = new QVBoxLayout(this);
resize(200,70);
- d->shadowPic.load(QLatin1String(":/qmlprofiler/dialog_shadow.png"));
+ d->shadowPic.load(QLatin1String(":/timeline/dialog_shadow.png"));
d->text = new QLabel(this);
d->text->setAlignment(Qt::AlignCenter);
@@ -103,7 +102,6 @@ QmlProfilerStateWidget::QmlProfilerStateWidget(QmlProfilerStateManager *stateMan
this, SLOT(profilerStateChanged()));
updateDisplay();
- connect(parent,SIGNAL(resized()),this,SLOT(reposition()));
}
QmlProfilerStateWidget::~QmlProfilerStateWidget()
diff --git a/src/plugins/qmlprofiler/qmlprofilertimelinemodel.cpp b/src/plugins/qmlprofiler/qmlprofilertimelinemodel.cpp
new file mode 100644
index 00000000000..b2411a5da8e
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertimelinemodel.cpp
@@ -0,0 +1,114 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "qmlprofilertimelinemodel.h"
+
+namespace QmlProfiler {
+
+QmlProfilerTimelineModel::QmlProfilerTimelineModel(QmlProfilerModelManager *modelManager,
+ const QString &displayName,
+ QmlDebug::Message message,
+ QmlDebug::RangeType rangeType, QObject *parent) :
+ TimelineModel(modelManager->registerModelProxy(), displayName, parent), m_message(message),
+ m_rangeType(rangeType), m_modelManager(modelManager)
+{
+ connect(modelManager->qmlModel(), &QmlProfilerDataModel::changed,
+ this, &QmlProfilerTimelineModel::dataChanged);
+}
+
+QmlDebug::RangeType QmlProfilerTimelineModel::rangeType() const
+{
+ return m_rangeType;
+}
+
+QmlDebug::Message QmlProfilerTimelineModel::message() const
+{
+ return m_message;
+}
+
+bool QmlProfilerTimelineModel::accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const
+{
+ return (event.rangeType == m_rangeType && event.message == m_message);
+}
+
+bool QmlProfilerTimelineModel::handlesTypeId(int typeIndex) const
+{
+ if (typeIndex < 0)
+ return false;
+
+ return accepted(modelManager()->qmlModel()->getEventTypes().at(typeIndex));
+}
+
+void QmlProfilerTimelineModel::clear()
+{
+ TimelineModel::clear();
+ updateProgress(0, 1);
+}
+
+QmlProfilerModelManager *QmlProfilerTimelineModel::modelManager() const
+{
+ return m_modelManager;
+}
+
+void QmlProfilerTimelineModel::updateProgress(qint64 count, qint64 max) const
+{
+ m_modelManager->modelProxyCountUpdated(modelId(), count, max);
+}
+
+void QmlProfilerTimelineModel::announceFeatures(quint64 features) const
+{
+ m_modelManager->announceFeatures(modelId(), features);
+}
+
+void QmlProfilerTimelineModel::dataChanged()
+{
+
+ switch (m_modelManager->state()) {
+ case QmlProfilerDataState::ProcessingData:
+ loadData();
+ emit emptyChanged();
+ break;
+ case QmlProfilerDataState::ClearingData:
+ clear();
+ break;
+ default:
+ break;
+ }
+
+ emit labelsChanged();
+}
+
+int QmlProfilerTimelineModel::bindingLoopDest(int index) const
+{
+ Q_UNUSED(index);
+ return -1;
+}
+
+}
diff --git a/src/plugins/qmlprofiler/notesmodel.h b/src/plugins/qmlprofiler/qmlprofilertimelinemodel.h
index 9a6f27114fe..1adf1b7f878 100644
--- a/src/plugins/qmlprofiler/notesmodel.h
+++ b/src/plugins/qmlprofiler/qmlprofilertimelinemodel.h
@@ -28,65 +28,52 @@
**
****************************************************************************/
-#ifndef NOTESMODEL_H
-#define NOTESMODEL_H
+#ifndef QMLPROFILERTIMELINEMODEL_H
+#define QMLPROFILERTIMELINEMODEL_H
-#include "abstracttimelinemodel.h"
+#include "qmlprofiler_global.h"
#include "qmlprofilermodelmanager.h"
-#include <QList>
-#include <QHash>
+#include "qmlprofilerdatamodel.h"
+#include "timeline/timelinemodel.h"
namespace QmlProfiler {
-class QMLPROFILER_EXPORT NotesModel : public QObject {
- Q_OBJECT
-public:
- struct Note {
- // Saved properties
- QString text;
-
- // Cache, created on loading
- int timelineModel;
- int timelineIndex;
- };
- NotesModel(QObject *parent);
- int count() const;
-
- void setModelManager(QmlProfilerModelManager *modelManager);
- void addTimelineModel(const AbstractTimelineModel *timelineModel);
+class QMLPROFILER_EXPORT QmlProfilerTimelineModel : public Timeline::TimelineModel {
+ Q_OBJECT
+ Q_PROPERTY(QmlDebug::RangeType rangeType READ rangeType CONSTANT)
+ Q_PROPERTY(QmlDebug::Message message READ message CONSTANT)
+ Q_PROPERTY(QmlProfilerModelManager *modelManager READ modelManager CONSTANT)
- int typeId(int index) const;
- QString text(int index) const;
- int timelineModel(int index) const;
- int timelineIndex(int index) const;
+public:
+ QmlProfilerTimelineModel(QmlProfilerModelManager *modelManager, const QString &displayName,
+ QmlDebug::Message message, QmlDebug::RangeType rangeType,
+ QObject *parent);
- QVariantList byTypeId(int typeId) const;
+ QmlProfilerModelManager *modelManager() const;
- QVariantList byTimelineModel(int timelineModel) const;
+ QmlDebug::RangeType rangeType() const;
+ QmlDebug::Message message() const;
- int get(int timelineModel, int timelineIndex) const;
- int add(int timelineModel, int timelineIndex, const QString &text);
- void update(int index, const QString &text);
- void remove(int index);
- bool isModified() const;
+ virtual bool accepted(const QmlProfilerDataModel::QmlEventTypeData &event) const;
+ bool handlesTypeId(int typeId) const;
+ Q_INVOKABLE virtual int bindingLoopDest(int index) const;
- void loadData();
- void saveData();
+ virtual void loadData() = 0;
void clear();
-signals:
- void changed(int typeId, int timelineModel, int timelineIndex);
-
private slots:
- void removeTimelineModel(QObject *timelineModel);
+ void dataChanged();
protected:
- QmlProfilerModelManager *m_modelManager;
- QList<Note> m_data;
- QHash<int, const AbstractTimelineModel *> m_timelineModels;
- bool m_modified;
+ void updateProgress(qint64 count, qint64 max) const;
+ void announceFeatures(quint64 features) const;
- int add(int typeId, qint64 startTime, qint64 duration, const QString &text);
+private:
+ const QmlDebug::Message m_message;
+ const QmlDebug::RangeType m_rangeType;
+ QmlProfilerModelManager *const m_modelManager;
};
+
}
-#endif // NOTESMODEL_H
+
+#endif // QMLPROFILERTIMELINEMODEL_H
diff --git a/src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.cpp b/src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.cpp
new file mode 100644
index 00000000000..5a40f3b61c8
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.cpp
@@ -0,0 +1,36 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "qmlprofilertimelinemodelfactory.h"
+
+// The presence of this file makes sure that moc generates metadata
+
+namespace QmlProfiler {
+}
diff --git a/src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.h b/src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.h
new file mode 100644
index 00000000000..3cd047d1ad6
--- /dev/null
+++ b/src/plugins/qmlprofiler/qmlprofilertimelinemodelfactory.h
@@ -0,0 +1,48 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 QMLPROFILERTIMELINEMODELFACTORY_H
+#define QMLPROFILERTIMELINEMODELFACTORY_H
+
+#include "qmlprofilertimelinemodel.h"
+#include "qmlprofilermodelmanager.h"
+
+namespace QmlProfiler {
+
+class QMLPROFILER_EXPORT QmlProfilerTimelineModelFactory : public QObject
+{
+ Q_OBJECT
+public:
+ virtual QList<QmlProfilerTimelineModel *> create(QmlProfilerModelManager *manager) = 0;
+};
+
+}
+
+#endif // QMLPROFILERTIMELINEMODELFACTORY_H
diff --git a/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp b/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp
deleted file mode 100644
index 9102d967040..00000000000
--- a/src/plugins/qmlprofiler/qmlprofilertimelinemodelproxy.cpp
+++ /dev/null
@@ -1,324 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "qmlprofilertimelinemodelproxy.h"
-#include "qmlprofilermodelmanager.h"
-#include "qmlprofilerdatamodel.h"
-#include "abstracttimelinemodel_p.h"
-
-#include <QCoreApplication>
-#include <QVector>
-#include <QHash>
-#include <QUrl>
-#include <QString>
-#include <QStack>
-
-#include <QDebug>
-
-namespace QmlProfiler {
-namespace Internal {
-
-class RangeTimelineModel::RangeTimelineModelPrivate : public AbstractTimelineModelPrivate
-{
-public:
- // convenience functions
- void computeNestingContracted();
- void computeExpandedLevels();
- void findBindingLoops();
-
- QVector<QmlRangeEventStartInstance> data;
- QVector<int> expandedRowTypes;
-private:
- Q_DECLARE_PUBLIC(RangeTimelineModel)
-};
-
-RangeTimelineModel::RangeTimelineModel(QmlDebug::RangeType rangeType, QObject *parent)
- : AbstractTimelineModel(new RangeTimelineModelPrivate, categoryLabel(rangeType),
- QmlDebug::MaximumMessage, rangeType, parent)
-{
- Q_D(RangeTimelineModel);
- d->expandedRowTypes << -1;
-}
-
-quint64 RangeTimelineModel::features() const
-{
- Q_D(const RangeTimelineModel);
- return 1ULL << QmlDebug::featureFromRangeType(d->rangeType);
-}
-
-void RangeTimelineModel::clear()
-{
- Q_D(RangeTimelineModel);
- d->expandedRowTypes.clear();
- d->expandedRowTypes << -1;
- d->data.clear();
- AbstractTimelineModel::clear();
-}
-
-void RangeTimelineModel::loadData()
-{
- Q_D(RangeTimelineModel);
- clear();
- QmlProfilerDataModel *simpleModel = d->modelManager->qmlModel();
- if (simpleModel->isEmpty())
- return;
-
- // collect events
- const QVector<QmlProfilerDataModel::QmlEventData> &eventList = simpleModel->getEvents();
- const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList = simpleModel->getEventTypes();
- foreach (const QmlProfilerDataModel::QmlEventData &event, eventList) {
- const QmlProfilerDataModel::QmlEventTypeData &type = typesList[event.typeIndex];
- if (!accepted(type))
- continue;
-
- // store starttime-based instance
- d->data.insert(insert(event.startTime, event.duration, event.typeIndex),
- QmlRangeEventStartInstance());
- d->modelManager->modelProxyCountUpdated(d->modelId, count(), eventList.count() * 6);
- }
-
- d->modelManager->modelProxyCountUpdated(d->modelId, 2, 6);
-
- // compute range nesting
- computeNesting();
-
- // compute nestingLevel - nonexpanded
- d->computeNestingContracted();
-
- d->modelManager->modelProxyCountUpdated(d->modelId, 3, 6);
-
- // compute nestingLevel - expanded
- d->computeExpandedLevels();
-
- d->modelManager->modelProxyCountUpdated(d->modelId, 4, 6);
-
- d->findBindingLoops();
-
- d->modelManager->modelProxyCountUpdated(d->modelId, 5, 6);
-
- d->modelManager->modelProxyCountUpdated(d->modelId, 1, 1);
-}
-
-void RangeTimelineModel::RangeTimelineModelPrivate::computeNestingContracted()
-{
- Q_Q(RangeTimelineModel);
- int i;
- int eventCount = q->count();
-
- int nestingLevels = QmlDebug::Constants::QML_MIN_LEVEL;
- collapsedRowCount = nestingLevels + 1;
- QVector<qint64> nestingEndTimes;
- nestingEndTimes.fill(0, nestingLevels + 1);
-
- for (i = 0; i < eventCount; i++) {
- qint64 st = q->ranges[i].start;
-
- // per type
- if (nestingEndTimes[nestingLevels] > st) {
- if (++nestingLevels == nestingEndTimes.size())
- nestingEndTimes << 0;
- if (nestingLevels == collapsedRowCount)
- ++collapsedRowCount;
- } else {
- while (nestingLevels > QmlDebug::Constants::QML_MIN_LEVEL &&
- nestingEndTimes[nestingLevels-1] <= st)
- nestingLevels--;
- }
- nestingEndTimes[nestingLevels] = st + q->ranges[i].duration;
-
- data[i].displayRowCollapsed = nestingLevels;
- }
-}
-
-void RangeTimelineModel::RangeTimelineModelPrivate::computeExpandedLevels()
-{
- Q_Q(RangeTimelineModel);
- QHash<int, int> eventRow;
- int eventCount = q->count();
- for (int i = 0; i < eventCount; i++) {
- int typeId = q->range(i).typeId;
- if (!eventRow.contains(typeId)) {
- eventRow[typeId] = expandedRowTypes.size();
- expandedRowTypes << typeId;
- }
- data[i].displayRowExpanded = eventRow[typeId];
- }
- expandedRowCount = expandedRowTypes.size();
-}
-
-void RangeTimelineModel::RangeTimelineModelPrivate::findBindingLoops()
-{
- Q_Q(RangeTimelineModel);
- if (rangeType != QmlDebug::Binding && rangeType != QmlDebug::HandlingSignal)
- return;
-
- typedef QPair<int, int> CallStackEntry;
- QStack<CallStackEntry> callStack;
-
- for (int i = 0; i < q->count(); ++i) {
- const Range *potentialParent = callStack.isEmpty()
- ? 0 : &q->ranges[callStack.top().second];
-
- while (potentialParent
- && !(potentialParent->start + potentialParent->duration > q->ranges[i].start)) {
- callStack.pop();
- potentialParent = callStack.isEmpty() ? 0
- : &q->ranges[callStack.top().second];
- }
-
- // check whether event is already in stack
- for (int ii = 0; ii < callStack.size(); ++ii) {
- if (callStack.at(ii).first == q->range(i).typeId) {
- data[i].bindingLoopHead = callStack.at(ii).second;
- break;
- }
- }
-
-
- CallStackEntry newEntry(q->range(i).typeId, i);
- callStack.push(newEntry);
- }
-
-}
-
-/////////////////// QML interface
-
-QString RangeTimelineModel::categoryLabel(QmlDebug::RangeType rangeType)
-{
- return QCoreApplication::translate("MainView",
- QmlProfilerModelManager::featureName(QmlDebug::featureFromRangeType(rangeType)));
-}
-
-int RangeTimelineModel::row(int index) const
-{
- Q_D(const RangeTimelineModel);
- if (d->expanded)
- return d->data[index].displayRowExpanded;
- else
- return d->data[index].displayRowCollapsed;
-}
-
-int RangeTimelineModel::bindingLoopDest(int index) const
-{
- Q_D(const RangeTimelineModel);
- return d->data[index].bindingLoopHead;
-}
-
-QColor RangeTimelineModel::color(int index) const
-{
- return colorBySelectionId(index);
-}
-
-QVariantList RangeTimelineModel::labels() const
-{
- Q_D(const RangeTimelineModel);
- QVariantList result;
-
- if (d->expanded && !d->hidden) {
- const QVector<QmlProfilerDataModel::QmlEventTypeData> &types =
- d->modelManager->qmlModel()->getEventTypes();
- for (int i = 1; i < d->expandedRowCount; i++) { // Ignore the -1 for the first row
- QVariantMap element;
- int typeId = d->expandedRowTypes[i];
- element.insert(QLatin1String("displayName"), QVariant(types[typeId].displayName));
- element.insert(QLatin1String("description"), QVariant(types[typeId].data));
- element.insert(QLatin1String("id"), QVariant(typeId));
- result << element;
- }
- }
-
- return result;
-}
-
-QVariantMap RangeTimelineModel::details(int index) const
-{
- Q_D(const RangeTimelineModel);
- QVariantMap result;
- int id = selectionId(index);
- const QVector<QmlProfilerDataModel::QmlEventTypeData> &types =
- d->modelManager->qmlModel()->getEventTypes();
-
- result.insert(QStringLiteral("displayName"), categoryLabel(d->rangeType));
- result.insert(tr("Duration"), QmlProfilerBaseModel::formatTime(range(index).duration));
-
- result.insert(tr("Details"), types[id].data);
- result.insert(tr("Location"), types[id].displayName);
- return result;
-}
-
-QVariantMap RangeTimelineModel::location(int index) const
-{
- Q_D(const RangeTimelineModel);
- QVariantMap result;
- int id = selectionId(index);
-
- const QmlDebug::QmlEventLocation &location
- = d->modelManager->qmlModel()->getEventTypes().at(id).location;
-
- result.insert(QStringLiteral("file"), location.filename);
- result.insert(QStringLiteral("line"), location.line);
- result.insert(QStringLiteral("column"), location.column);
-
- return result;
-}
-
-bool RangeTimelineModel::isSelectionIdValid(int typeId) const
-{
- Q_D(const RangeTimelineModel);
- if (typeId < 0)
- return false;
- const QmlProfilerDataModel::QmlEventTypeData &type =
- d->modelManager->qmlModel()->getEventTypes().at(typeId);
- if (type.message != d->message || type.rangeType != d->rangeType)
- return false;
- return true;
-}
-
-int RangeTimelineModel::selectionIdForLocation(const QString &filename, int line, int column) const
-{
- Q_D(const RangeTimelineModel);
- // if this is called from v8 view, we don't have the column number, it will be -1
- const QVector<QmlProfilerDataModel::QmlEventTypeData> &types =
- d->modelManager->qmlModel()->getEventTypes();
- for (int i = 1; i < d->expandedRowCount; ++i) {
- int typeId = d->expandedRowTypes[i];
- const QmlProfilerDataModel::QmlEventTypeData &eventData = types[typeId];
- if (eventData.location.filename == filename &&
- eventData.location.line == line &&
- (column == -1 || eventData.location.column == column))
- return typeId;
- }
- return -1;
-}
-
-
-
-}
-}
diff --git a/src/plugins/qmlprofiler/qmlprofilertool.cpp b/src/plugins/qmlprofiler/qmlprofilertool.cpp
index 143db4bf5fd..a7a0e84ef38 100644
--- a/src/plugins/qmlprofiler/qmlprofilertool.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilertool.cpp
@@ -37,8 +37,7 @@
#include "qmlprofilerclientmanager.h"
#include "qmlprofilermodelmanager.h"
#include "qmlprofilerdetailsrewriter.h"
-#include "timelinerenderer.h"
-#include "notesmodel.h"
+#include "qmlprofilernotesmodel.h"
#include <analyzerbase/analyzermanager.h>
#include <analyzerbase/analyzerruncontrol.h>
@@ -128,8 +127,6 @@ QmlProfilerTool::QmlProfilerTool(QObject *parent)
d->m_clearButton = 0;
d->m_timeLabel = 0;
- qmlRegisterType<TimelineRenderer>("Monitor", 1, 0,"TimelineRenderer");
-
d->m_profilerState = new QmlProfilerStateManager(this);
connect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
connect(d->m_profilerState, SIGNAL(clientRecordingChanged()), this, SLOT(clientRecordingChanged()));
diff --git a/src/plugins/qmlprofiler/qmlprofilertracefile.cpp b/src/plugins/qmlprofiler/qmlprofilertracefile.cpp
index bec560e4fbd..acd9c79488e 100644
--- a/src/plugins/qmlprofiler/qmlprofilertracefile.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilertracefile.cpp
@@ -141,6 +141,8 @@ bool QmlProfilerFileReader::load(QIODevice *device)
QXmlStreamReader stream(device);
bool validVersion = true;
+ qint64 traceStart = -1;
+ qint64 traceEnd = -1;
while (validVersion && !stream.atEnd() && !stream.hasError()) {
QXmlStreamReader::TokenType token = stream.readNext();
@@ -155,9 +157,9 @@ bool QmlProfilerFileReader::load(QIODevice *device)
else
validVersion = false;
if (attributes.hasAttribute(_("traceStart")))
- emit traceStartTime(attributes.value(_("traceStart")).toString().toLongLong());
+ traceStart = attributes.value(_("traceStart")).toString().toLongLong();
if (attributes.hasAttribute(_("traceEnd")))
- emit traceEndTime(attributes.value(_("traceEnd")).toString().toLongLong());
+ traceEnd = attributes.value(_("traceEnd")).toString().toLongLong();
}
if (elementName == _("eventData")) {
@@ -191,7 +193,7 @@ bool QmlProfilerFileReader::load(QIODevice *device)
emit error(tr("Error while parsing trace data file: %1").arg(stream.errorString()));
return false;
} else {
- m_qmlModel->setData(m_qmlEvents, m_ranges);
+ m_qmlModel->setData(traceStart, qMax(traceStart, traceEnd), m_qmlEvents, m_ranges);
m_qmlModel->setNoteData(m_notes);
return true;
}
diff --git a/src/plugins/qmlprofiler/qmlprofilertracefile.h b/src/plugins/qmlprofiler/qmlprofilertracefile.h
index 3191c0601a5..9b8c7e671e1 100644
--- a/src/plugins/qmlprofiler/qmlprofilertracefile.h
+++ b/src/plugins/qmlprofiler/qmlprofilertracefile.h
@@ -61,9 +61,6 @@ public:
bool load(QIODevice *device);
signals:
- void traceStartTime(qint64 traceStartTime);
- void traceEndTime(qint64 traceStartTime);
-
void error(const QString &error);
private:
diff --git a/src/plugins/qmlprofiler/qmlprofilertraceview.cpp b/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
index db61f6a66d0..c7a962649c5 100644
--- a/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
@@ -32,15 +32,22 @@
#include "qmlprofilertool.h"
#include "qmlprofilerstatemanager.h"
#include "qmlprofilermodelmanager.h"
-#include "qmlprofilertimelinemodelproxy.h"
-#include "timelinemodelaggregator.h"
-
-// Needed for the load&save actions in the context menu
-#include <analyzerbase/ianalyzertool.h>
+#include "qmlprofilernotesmodel.h"
+#include "qmlprofileranimationsmodel.h"
+#include "qmlprofilerrangemodel.h"
+#include "qmlprofilerplugin.h"
// Communication with the other views (limit events to range)
#include "qmlprofilerviewmanager.h"
+#include "timeline/timelinezoomcontrol.h"
+#include "timeline/timelinemodelaggregator.h"
+#include "timeline/timelinerenderer.h"
+#include "timeline/timelineoverviewrenderer.h"
+
+// Needed for the load&save actions in the context menu
+#include <analyzerbase/ianalyzertool.h>
+
#include <utils/styledbar.h>
#include <QQmlContext>
@@ -62,98 +69,10 @@ namespace QmlProfiler {
namespace Internal {
/////////////////////////////////////////////////////////
-ZoomControl::ZoomControl(const QmlProfilerTraceTime *traceTime, QObject *parent) :
- QObject(parent), m_startTime(traceTime->startTime()), m_endTime(traceTime->endTime()),
- m_windowStart(traceTime->startTime()), m_windowEnd(traceTime->endTime()),
- m_traceTime(traceTime), m_windowLocked(false)
-{
- connect(traceTime, SIGNAL(startTimeChanged(qint64)), this, SLOT(rebuildWindow()));
- connect(traceTime, SIGNAL(endTimeChanged(qint64)), this, SLOT(rebuildWindow()));
- connect(&m_timer, SIGNAL(timeout()), this, SLOT(moveWindow()));
-}
-
-void ZoomControl::setRange(qint64 startTime, qint64 endTime)
-{
- if (m_startTime != startTime || m_endTime != endTime) {
- m_timer.stop();
- m_startTime = startTime;
- m_endTime = endTime;
- rebuildWindow();
- emit rangeChanged();
- }
-}
-
-void ZoomControl::rebuildWindow()
-{
- qint64 minDuration = 1; // qMax needs equal data types, so literal 1 won't do
- qint64 shownDuration = qMax(duration(), minDuration);
-
- qint64 oldWindowStart = m_windowStart;
- qint64 oldWindowEnd = m_windowEnd;
- if (m_traceTime->duration() / shownDuration < MAX_ZOOM_FACTOR) {
- m_windowStart = m_traceTime->startTime();
- m_windowEnd = m_traceTime->endTime();
- } else if (windowLength() / shownDuration > MAX_ZOOM_FACTOR ||
- windowLength() / shownDuration * 2 < MAX_ZOOM_FACTOR) {
- qint64 keep = shownDuration * MAX_ZOOM_FACTOR / 2 - shownDuration;
- m_windowStart = m_startTime - keep;
- if (m_windowStart < m_traceTime->startTime()) {
- keep += m_traceTime->startTime() - m_windowStart;
- m_windowStart = m_traceTime->startTime();
- }
-
- m_windowEnd = m_endTime + keep;
- if (m_windowEnd > m_traceTime->endTime()) {
- m_windowStart = qMax(m_traceTime->startTime(),
- m_windowStart - m_windowEnd - m_traceTime->endTime());
- m_windowEnd = m_traceTime->endTime();
- }
- } else {
- m_timer.start(500);
- }
- if (oldWindowStart != m_windowStart || oldWindowEnd != m_windowEnd)
- emit windowChanged();
-}
-
-void ZoomControl::moveWindow()
-{
- if (m_windowLocked)
- return;
- m_timer.stop();
-
- qint64 offset = (m_endTime - m_windowEnd + m_startTime - m_windowStart) / 2;
- if (offset == 0 || (offset < 0 && m_windowStart == m_traceTime->startTime()) ||
- (offset > 0 && m_windowEnd == m_traceTime->endTime())) {
- return;
- } else if (offset > duration()) {
- offset = (offset + duration()) / 2;
- } else if (offset < -duration()) {
- offset = (offset - duration()) / 2;
- }
- m_windowStart += offset;
- if (m_windowStart < m_traceTime->startTime()) {
- m_windowEnd += m_traceTime->startTime() - m_windowStart;
- m_windowStart = m_traceTime->startTime();
- }
- m_windowEnd += offset;
- if (m_windowEnd > m_traceTime->endTime()) {
- m_windowStart -= m_windowEnd - m_traceTime->endTime();
- m_windowEnd = m_traceTime->endTime();
- }
- emit windowChanged();
- m_timer.start(100);
-}
-
-/////////////////////////////////////////////////////////
class QmlProfilerTraceView::QmlProfilerTraceViewPrivate
{
public:
QmlProfilerTraceViewPrivate(QmlProfilerTraceView *qq) : q(qq) {}
- ~QmlProfilerTraceViewPrivate()
- {
- delete m_mainView;
- }
-
QmlProfilerTraceView *q;
QmlProfilerStateManager *m_profilerState;
@@ -164,10 +83,10 @@ public:
QQuickView *m_mainView;
QmlProfilerModelManager *m_modelManager;
- TimelineModelAggregator *m_modelProxy;
+ Timeline::TimelineModelAggregator *m_modelProxy;
- ZoomControl *m_zoomControl;
+ Timeline::TimelineZoomControl *m_zoomControl;
};
QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerModelManager *modelManager, QmlProfilerStateManager *profilerState)
@@ -175,55 +94,75 @@ QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerT
{
setObjectName(QLatin1String("QML Profiler"));
- d->m_zoomControl = new ZoomControl(modelManager->traceTime(), this);
- connect(d->m_zoomControl, SIGNAL(rangeChanged()), this, SLOT(updateRange()));
+ d->m_zoomControl = new Timeline::TimelineZoomControl(this);
+ connect(modelManager->traceTime(), &QmlProfilerTraceTime::timeChanged,
+ d->m_zoomControl, &Timeline::TimelineZoomControl::setTrace);
QVBoxLayout *groupLayout = new QVBoxLayout;
groupLayout->setContentsMargins(0, 0, 0, 0);
groupLayout->setSpacing(0);
+ qmlRegisterType<Timeline::TimelineRenderer>("TimelineRenderer", 1, 0, "TimelineRenderer");
+ qmlRegisterType<Timeline::TimelineOverviewRenderer>("TimelineOverviewRenderer", 1, 0,
+ "TimelineOverviewRenderer");
+ qmlRegisterType<Timeline::TimelineZoomControl>();
+ qmlRegisterType<Timeline::TimelineModel>();
+ qmlRegisterType<Timeline::TimelineNotesModel>();
+
d->m_mainView = new QmlProfilerQuickView(this);
d->m_mainView->setResizeMode(QQuickView::SizeRootObjectToView);
QWidget *mainViewContainer = QWidget::createWindowContainer(d->m_mainView);
mainViewContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- enableToolbar(false);
-
groupLayout->addWidget(mainViewContainer);
setLayout(groupLayout);
d->m_profilerTool = profilerTool;
d->m_viewContainer = container;
+
+ d->m_modelProxy = new Timeline::TimelineModelAggregator(modelManager->notesModel(), this);
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("qmlProfilerModelProxy"),
- d->m_modelProxy);
+
+ connect(modelManager,SIGNAL(dataAvailable()), d->m_modelProxy,SIGNAL(dataAvailable()));
+
+ // external models pushed on top
+ foreach (QmlProfilerTimelineModel *timelineModel,
+ QmlProfilerPlugin::instance->getModels(modelManager)) {
+ d->m_modelProxy->addModel(timelineModel);
+ }
+
+ d->m_modelProxy->addModel(new QmlProfilerAnimationsModel(modelManager, d->m_modelProxy));
+
+ for (int i = 0; i < QmlDebug::MaximumRangeType; ++i)
+ d->m_modelProxy->addModel(new QmlProfilerRangeModel(modelManager, (QmlDebug::RangeType)i,
+ d->m_modelProxy));
+
+ // Connect this last so that it's executed after the models have updated their data.
+ connect(modelManager->qmlModel(), SIGNAL(changed()), d->m_modelProxy, SIGNAL(stateChanged()));
+ connect(d->m_modelManager, SIGNAL(stateChanged()), this, SLOT(profilerDataModelStateChanged()));
+
d->m_profilerState = profilerState;
// Minimum height: 5 rows of 20 pixels + scrollbar of 50 pixels + 20 pixels margin
setMinimumHeight(170);
+
+ d->m_mainView->rootContext()->setContextProperty(QLatin1String("timelineModelAggregator"),
+ d->m_modelProxy);
+ d->m_mainView->rootContext()->setContextProperty(QLatin1String("zoomControl"),
+ d->m_zoomControl);
+ d->m_mainView->setSource(QUrl(QLatin1String("qrc:/timeline/MainView.qml")));
+
+ QQuickItem *rootObject = d->m_mainView->rootObject();
+ connect(rootObject, SIGNAL(updateCursorPosition()), this, SLOT(updateCursorPosition()));
}
QmlProfilerTraceView::~QmlProfilerTraceView()
{
+ delete d->m_mainView;
delete d;
}
/////////////////////////////////////////////////////////
-// Initialize widgets
-void QmlProfilerTraceView::reset()
-{
- d->m_mainView->rootContext()->setContextProperty(QLatin1String("zoomControl"), d->m_zoomControl);
- d->m_mainView->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/MainView.qml")));
-
- QQuickItem *rootObject = d->m_mainView->rootObject();
- connect(rootObject, SIGNAL(updateCursorPosition()), this, SLOT(updateCursorPosition()));
-}
-
-/////////////////////////////////////////////////////////
bool QmlProfilerTraceView::hasValidSelection() const
{
QQuickItem *rootObject = d->m_mainView->rootObject();
@@ -232,12 +171,6 @@ bool QmlProfilerTraceView::hasValidSelection() const
return false;
}
-void QmlProfilerTraceView::enableToolbar(bool enable)
-{
- QMetaObject::invokeMethod(d->m_mainView->rootObject(), "enableButtonsBar",
- Q_ARG(QVariant,QVariant(enable)));
-}
-
qint64 QmlProfilerTraceView::selectionStart() const
{
QQuickItem *rootObject = d->m_mainView->rootObject();
@@ -264,15 +197,7 @@ void QmlProfilerTraceView::selectByTypeId(int typeId)
QQuickItem *rootObject = d->m_mainView->rootObject();
if (!rootObject)
return;
-
- for (int modelIndex = 0; modelIndex < d->m_modelProxy->modelCount(); ++modelIndex) {
- if (d->m_modelProxy->isSelectionIdValid(modelIndex, typeId)) {
- QMetaObject::invokeMethod(rootObject, "selectBySelectionId",
- Q_ARG(QVariant,QVariant(modelIndex)),
- Q_ARG(QVariant,QVariant(typeId)));
- return;
- }
- }
+ QMetaObject::invokeMethod(rootObject, "selectByTypeId", Q_ARG(QVariant,QVariant(typeId)));
}
void QmlProfilerTraceView::selectBySourceLocation(const QString &filename, int line, int column)
@@ -282,7 +207,8 @@ void QmlProfilerTraceView::selectBySourceLocation(const QString &filename, int l
return;
for (int modelIndex = 0; modelIndex < d->m_modelProxy->modelCount(); ++modelIndex) {
- int typeId = d->m_modelProxy->selectionIdForLocation(modelIndex, filename, line, column);
+ int typeId = d->m_modelProxy->model(modelIndex)->selectionIdForLocation(filename, line,
+ column);
if (typeId != -1) {
QMetaObject::invokeMethod(rootObject, "selectBySelectionId",
Q_ARG(QVariant,QVariant(modelIndex)),
@@ -305,27 +231,6 @@ void QmlProfilerTraceView::updateCursorPosition()
emit typeSelected(rootObject->property("typeId").toInt());
}
-////////////////////////////////////////////////////////
-// Zoom control
-void QmlProfilerTraceView::updateRange()
-{
- if (!d->m_modelManager)
- return;
- qreal duration = d->m_zoomControl->endTime() - d->m_zoomControl->startTime();
- if (duration <= 0)
- return;
- if (d->m_modelManager->traceTime()->duration() <= 0)
- return;
- QMetaObject::invokeMethod(d->m_mainView->rootObject()->findChild<QObject*>(QLatin1String("zoomSliderToolBar")), "updateZoomLevel");
-}
-
-////////////////////////////////////////////////////////
-void QmlProfilerTraceView::resizeEvent(QResizeEvent *event)
-{
- QWidget::resizeEvent(event);
- emit resized();
-}
-
void QmlProfilerTraceView::mousePressEvent(QMouseEvent *event)
{
d->m_zoomControl->setWindowLocked(true);
@@ -365,7 +270,7 @@ void QmlProfilerTraceView::showContextMenu(QPoint position)
if (d->m_viewContainer->hasGlobalStats())
getGlobalStatsAction->setEnabled(false);
- if (!d->m_modelProxy->isEmpty()) {
+ if (d->m_zoomControl->traceDuration() > 0) {
menu.addSeparator();
viewAllAction = menu.addAction(tr("Reset Zoom"));
}
@@ -374,9 +279,8 @@ void QmlProfilerTraceView::showContextMenu(QPoint position)
if (selectedAction) {
if (selectedAction == viewAllAction) {
- d->m_zoomControl->setRange(
- d->m_modelManager->traceTime()->startTime(),
- d->m_modelManager->traceTime()->endTime());
+ d->m_zoomControl->setRange(d->m_zoomControl->traceStart(),
+ d->m_zoomControl->traceEnd());
}
if (selectedAction == getLocalStatsAction) {
d->m_viewContainer->getStatisticsInRange(
@@ -396,12 +300,10 @@ void QmlProfilerTraceView::profilerDataModelStateChanged()
case QmlProfilerDataState::Empty: break;
case QmlProfilerDataState::ClearingData:
d->m_mainView->hide();
- enableToolbar(false);
break;
case QmlProfilerDataState::AcquiringData: break;
case QmlProfilerDataState::ProcessingData: break;
case QmlProfilerDataState::Done:
- enableToolbar(true);
d->m_mainView->show();
break;
default:
diff --git a/src/plugins/qmlprofiler/qmlprofilertraceview.h b/src/plugins/qmlprofiler/qmlprofilertraceview.h
index a8daad7ab80..f428ffb6f38 100644
--- a/src/plugins/qmlprofiler/qmlprofilertraceview.h
+++ b/src/plugins/qmlprofiler/qmlprofilertraceview.h
@@ -46,54 +46,17 @@ namespace Internal {
class QmlProfilerStateManager;
class QmlProfilerViewManager;
-// centralized zoom control
-class ZoomControl : public QObject {
- Q_OBJECT
-public:
- static const qint64 MAX_ZOOM_FACTOR = 1 << 12;
-
- ZoomControl(const QmlProfilerTraceTime *traceTime, QObject *parent = 0);
- ~ZoomControl(){}
-
- Q_INVOKABLE void setRange(qint64 startTime, qint64 endTime);
- Q_INVOKABLE qint64 startTime() const { return m_startTime; }
- Q_INVOKABLE qint64 endTime() const { return m_endTime; }
- Q_INVOKABLE qint64 duration() const { return m_endTime - m_startTime; }
-
- Q_INVOKABLE qint64 windowStart() const { return m_windowStart; }
- Q_INVOKABLE qint64 windowEnd() const { return m_windowEnd; }
- Q_INVOKABLE qint64 windowLength() const { return m_windowEnd - m_windowStart; }
- void setWindowLocked(bool lock) { m_windowLocked = lock; }
-
-signals:
- void rangeChanged();
- void windowChanged();
-
-private slots:
- void rebuildWindow();
- void moveWindow();
-
-private:
- qint64 m_startTime;
- qint64 m_endTime;
- qint64 m_windowStart;
- qint64 m_windowEnd;
-
- const QmlProfilerTraceTime *m_traceTime;
- QTimer m_timer;
- bool m_windowLocked;
-};
-
class QmlProfilerTraceView : public QWidget
{
Q_OBJECT
public:
- explicit QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerModelManager *modelManager, QmlProfilerStateManager *profilerState);
+ explicit QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool,
+ QmlProfilerViewManager *container,
+ QmlProfilerModelManager *modelManager,
+ QmlProfilerStateManager *profilerState);
~QmlProfilerTraceView();
- void reset();
-
bool hasValidSelection() const;
qint64 selectionStart() const;
qint64 selectionEnd() const;
@@ -106,13 +69,9 @@ public slots:
private slots:
void updateCursorPosition();
-
- void updateRange();
-
void profilerDataModelStateChanged();
protected:
- virtual void resizeEvent(QResizeEvent *event);
virtual void contextMenuEvent(QContextMenuEvent *event);
virtual void mousePressEvent(QMouseEvent *event);
virtual void mouseReleaseEvent(QMouseEvent *event);
@@ -120,10 +79,6 @@ protected:
signals:
void gotoSourceLocation(const QString &fileUrl, int lineNumber, int columNumber);
void typeSelected(int typeId);
- void resized();
-
-private:
- void enableToolbar(bool);
private:
class QmlProfilerTraceViewPrivate;
diff --git a/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp b/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
index 6a0247a8902..05bfd5e2913 100644
--- a/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
@@ -100,8 +100,6 @@ void QmlProfilerViewManager::createViews()
d->traceView->setWindowTitle(tr("Timeline"));
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->profilerModelManager);
diff --git a/src/plugins/qmlprofiler/sortedtimelinemodel.cpp b/src/plugins/qmlprofiler/sortedtimelinemodel.cpp
deleted file mode 100644
index 94fbb455b61..00000000000
--- a/src/plugins/qmlprofiler/sortedtimelinemodel.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "sortedtimelinemodel.h"
-namespace QmlProfiler {
-
-/*!
- \class QmlProfiler::SortedTimelineModel
- \brief The SortedTimelineModel class provides a sorted model for timeline data.
-
- The SortedTimelineModel lets you keep range data sorted by both start and end times, so that
- visible ranges can easily be computed. The only precondition for that to work is that the ranges
- must be perfectly nested. A "parent" range of a range R is defined as a range for which the
- start time is smaller than R's start time and the end time is greater than R's end time. A set
- of ranges is perfectly nested if all parent ranges of any given range have a common parent
- range. Mind that you can always make that happen by defining a range that spans the whole
- available time span. That, however, will make any code that uses firstStartTime() and
- lastEndTime() for selecting subsets of the model always select all of it.
-
- \note Indices returned from the various methods are only valid until a new range is inserted
- before them. Inserting a new range before a given index moves the range pointed to by the
- index by one. Incrementing the index by one will make it point to the item again.
-*/
-
-/*!
- \fn SortedTimelineModel::clear()
- Clears the ranges and their end times.
-*/
-void SortedTimelineModel::clear()
-{
- ranges.clear();
- endTimes.clear();
-}
-
-/*!
- \fn int SortedTimelineModel::count() const
- Returns the number of ranges in the model.
-*/
-
-/*!
- \fn qint64 SortedTimelineModel::firstStartTime() const
- Returns the begin of the first range in the model.
-*/
-
-/*!
- \fn qint64 SortedTimelineModel::lastEndTime() const
- Returns the end of the last range in the model.
-*/
-
-/*!
- \fn const SortedTimelineModel::Range &SortedTimelineModel::range(int index) const
- Returns the range data at the specified index.
-*/
-
-/*!
- \fn int SortedTimelineModel::insert(qint64 startTime, qint64 duration)
- Inserts a range at the given time position and returns its index.
-*/
-
-/*!
- \fn int SortedTimelineModel::insertStart(qint64 startTime, const Data &item)
- Inserts the given data as range start at the given time position and
- returns its index. The range end is not set.
-*/
-
-/*!
- \fn int SortedTimelineModel::insertEnd(int index, qint64 duration)
- Adds a range end for the given start index.
-*/
-
-/*!
- \fn int SortedTimelineModel::firstIndexNoParents(qint64 startTime) const
- Looks up the first range with an end time greater than the given time and
- returns its index. If no such range is found, it returns -1.
-*/
-
-/*!
- \fn int SortedTimelineModel::firstIndex(qint64 startTime) const
- Looks up the first range with an end time greater than the given time and
- returns its parent's index. If no such range is found, it returns -1. If there
- is no parent, it returns the found range's index. The parent of a range is the
- range with the lowest start time that completely covers the child range.
- "Completely covers" means:
- parent.startTime <= child.startTime && parent.endTime >= child.endTime
-*/
-
-/*!
- \fn int SortedTimelineModel::lastIndex(qint64 endTime) const
- Looks up the last range with a start time smaller than the given time and
- returns its index. If no such range is found, it returns -1.
-*/
-
-/*!
- \fn void SortedTimelineModel::computeNesting()
- Compute all ranges' parents.
- \sa findFirstIndex
-*/
-void SortedTimelineModel::computeNesting()
-{
- QLinkedList<int> parents;
- for (int range = 0; range != count(); ++range) {
- Range &current = ranges[range];
- for (QLinkedList<int>::iterator parentIt = parents.begin();;) {
- if (parentIt == parents.end()) {
- parents.append(range);
- break;
- }
-
- Range &parent = ranges[*parentIt];
- qint64 parentEnd = parent.start + parent.duration;
- if (parentEnd < current.start) {
- if (parent.start == current.start) {
- if (parent.parent == -1) {
- parent.parent = range;
- } else {
- Range &ancestor = ranges[parent.parent];
- if (ancestor.start == current.start &&
- ancestor.duration < current.duration)
- parent.parent = range;
- }
- // Just switch the old parent range for the new, larger one
- *parentIt = range;
- break;
- } else {
- parentIt = parents.erase(parentIt);
- }
- } else if (parentEnd >= current.start + current.duration) {
- // no need to insert
- current.parent = *parentIt;
- break;
- } else {
- ++parentIt;
- }
- }
- }
-}
-
-}
diff --git a/src/plugins/qmlprofiler/sortedtimelinemodel.h b/src/plugins/qmlprofiler/sortedtimelinemodel.h
deleted file mode 100644
index 3d92fe7e0ea..00000000000
--- a/src/plugins/qmlprofiler/sortedtimelinemodel.h
+++ /dev/null
@@ -1,190 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef SORTEDTIMELINEMODEL_H
-#define SORTEDTIMELINEMODEL_H
-
-#include "qmlprofiler_global.h"
-#include <QObject>
-#include <QVector>
-#include <QLinkedList>
-
-namespace QmlProfiler {
-
-class QMLPROFILER_EXPORT SortedTimelineModel : public QObject {
- Q_OBJECT
-
-public:
- struct Range {
- Range() : start(-1), duration(-1), typeId(-1), parent(-1) {}
- Range(qint64 start, qint64 duration, int typeId) :
- start(start), duration(duration), typeId(typeId), parent(-1) {}
- qint64 start;
- qint64 duration;
- int typeId;
- int parent;
- inline qint64 timestamp() const {return start;}
- };
-
- struct RangeEnd {
- RangeEnd() : startIndex(-1), end(-1) {}
- RangeEnd(int startIndex, qint64 end) :
- startIndex(startIndex), end(end) {}
- int startIndex;
- qint64 end;
- inline qint64 timestamp() const {return end;}
- };
-
- inline int count() const { return ranges.count(); }
-
- qint64 duration(int index) const { return ranges[index].duration; }
- qint64 startTime(int index) const { return ranges[index].start; }
- qint64 endTime(int index) const { return ranges[index].start + ranges[index].duration; }
- int typeId(int index) const { return ranges[index].typeId; }
-
- inline qint64 lastEndTime() const { return endTimes.last().end; }
- inline qint64 firstStartTime() const { return ranges.first().start; }
-
- inline const Range &range(int index) const { return ranges[index]; }
-
- inline int firstIndex(qint64 startTime) const
- {
- int index = firstIndexNoParents(startTime);
- if (index == -1)
- return -1;
- int parent = ranges[index].parent;
- return parent == -1 ? index : parent;
- }
-
- inline int firstIndexNoParents(qint64 startTime) const
- {
- // in the "endtime" list, find the first event that ends after startTime
- if (endTimes.isEmpty())
- return -1;
- if (endTimes.count() == 1 || endTimes.first().end > startTime)
- return endTimes.first().startIndex;
- if (endTimes.last().end <= startTime)
- return -1;
-
- return endTimes[lowerBound(endTimes, startTime) + 1].startIndex;
- }
-
- inline int lastIndex(qint64 endTime) const
- {
- // in the "starttime" list, find the last event that starts before endtime
- if (ranges.isEmpty() || ranges.first().start >= endTime)
- return -1;
- if (ranges.count() == 1)
- return 0;
- if (ranges.last().start < endTime)
- return ranges.count() - 1;
-
- return lowerBound(ranges, endTime);
- }
-
-protected:
-
- SortedTimelineModel(QObject *parent = 0) : QObject(parent) {}
-
- void clear();
-
- inline int insert(qint64 startTime, qint64 duration, int typeId)
- {
- /* Doing insert-sort here is preferable as most of the time the times will actually be
- * presorted in the right way. So usually this will just result in appending. */
- int index = insertSorted(ranges, Range(startTime, duration, typeId));
- if (index < ranges.size() - 1)
- incrementStartIndices(index);
- insertSorted(endTimes, RangeEnd(index, startTime + duration));
- return index;
- }
-
- inline int insertStart(qint64 startTime, int typeId)
- {
- int index = insertSorted(ranges, Range(startTime, 0, typeId));
- if (index < ranges.size() - 1)
- incrementStartIndices(index);
- return index;
- }
-
- inline void insertEnd(int index, qint64 duration)
- {
- ranges[index].duration = duration;
- insertSorted(endTimes, RangeEnd(index, ranges[index].start + duration));
- }
-
- void computeNesting();
-
- void incrementStartIndices(int index)
- {
- for (int i = 0; i < endTimes.size(); ++i) {
- if (endTimes[i].startIndex >= index)
- endTimes[i].startIndex++;
- }
- }
-
- template<typename RangeDelimiter>
- static inline int insertSorted(QVector<RangeDelimiter> &container, const RangeDelimiter &item)
- {
- for (int i = container.count();;) {
- if (i == 0) {
- container.prepend(item);
- return 0;
- }
- if (container[--i].timestamp() <= item.timestamp()) {
- container.insert(++i, item);
- return i;
- }
- }
- }
-
- template<typename RangeDelimiter>
- static inline int lowerBound(const QVector<RangeDelimiter> &container, qint64 time)
- {
- int fromIndex = 0;
- int toIndex = container.count() - 1;
- while (toIndex - fromIndex > 1) {
- int midIndex = (fromIndex + toIndex)/2;
- if (container[midIndex].timestamp() < time)
- fromIndex = midIndex;
- else
- toIndex = midIndex;
- }
-
- return fromIndex;
- }
-
- QVector<Range> ranges;
- QVector<RangeEnd> endTimes;
-};
-
-}
-
-#endif
diff --git a/src/plugins/qmlprofiler/timelinemodelaggregator.cpp b/src/plugins/qmlprofiler/timelinemodelaggregator.cpp
deleted file mode 100644
index 530fb8c2319..00000000000
--- a/src/plugins/qmlprofiler/timelinemodelaggregator.cpp
+++ /dev/null
@@ -1,400 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company 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 "notesmodel.h"
-
-#include <QStringList>
-#include <QVariant>
-
-namespace QmlProfiler {
-namespace Internal {
-
-
-class TimelineModelAggregator::TimelineModelAggregatorPrivate {
-public:
- TimelineModelAggregatorPrivate(TimelineModelAggregator *qq):q(qq) {}
- ~TimelineModelAggregatorPrivate() {}
-
- TimelineModelAggregator *q;
-
- // mapping of modelId assigned by manager to index in our list
- QList <int> modelManagerIndexMapping;
-
- QList <AbstractTimelineModel *> modelList;
- QmlProfilerModelManager *modelManager;
-};
-
-TimelineModelAggregator::TimelineModelAggregator(QObject *parent)
- : QObject(parent), d(new TimelineModelAggregatorPrivate(this))
-{
- connect(this,SIGNAL(modelsChanged(int,int)),this,SIGNAL(heightChanged()));
- connect(this,SIGNAL(stateChanged()),this,SIGNAL(heightChanged()));
-}
-
-TimelineModelAggregator::~TimelineModelAggregator()
-{
- delete d;
-}
-
-int TimelineModelAggregator::height() const
-{
- return modelOffset(d->modelList.length());
-}
-
-void TimelineModelAggregator::setModelManager(QmlProfilerModelManager *modelManager)
-{
- d->modelManager = modelManager;
- connect(modelManager,SIGNAL(stateChanged()),this,SLOT(dataChanged()));
- 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);
-
- for (int i = 0; i < QmlDebug::MaximumRangeType; ++i) {
- RangeTimelineModel *rangeModel = new RangeTimelineModel((QmlDebug::RangeType)i, this);
- rangeModel->setModelManager(modelManager);
- addModel(rangeModel);
- }
-
- // Connect this last so that it's executed after the models have updated their data.
- connect(modelManager->qmlModel(),SIGNAL(changed()),this,SIGNAL(stateChanged()));
- connect(modelManager->notesModel(), SIGNAL(changed(int,int,int)),
- this, SIGNAL(notesChanged(int,int,int)));
-}
-
-void TimelineModelAggregator::addModel(AbstractTimelineModel *m)
-{
- while (d->modelManagerIndexMapping.size() <= m->modelId())
- d->modelManagerIndexMapping.append(-1);
- d->modelManagerIndexMapping[m->modelId()] = d->modelList.size();
- d->modelList << m;
- connect(m,SIGNAL(expandedChanged()),this,SIGNAL(expandedChanged()));
- connect(m,SIGNAL(hiddenChanged()),this,SIGNAL(hiddenChanged()));
- connect(m,SIGNAL(rowHeightChanged()),this,SIGNAL(rowHeightChanged()));
- connect(m,SIGNAL(heightChanged()),this,SIGNAL(heightChanged()));
- d->modelManager->notesModel()->addTimelineModel(m);
- emit modelsChanged(d->modelList.length(), d->modelList.length());
-}
-
-const AbstractTimelineModel *TimelineModelAggregator::model(int modelIndex) const
-{
- return d->modelList[modelIndex];
-}
-
-QVariantList TimelineModelAggregator::models() const
-{
- QVariantList ret;
- foreach (AbstractTimelineModel *model, d->modelList)
- ret << QVariant::fromValue(model);
- return ret;
-}
-
-int TimelineModelAggregator::modelIndexFromManagerIndex(int modelManagerIndex) const
-{
- return d->modelManagerIndexMapping[modelManagerIndex];
-}
-
-NotesModel *TimelineModelAggregator::notes() const
-{
- return d->modelManager->notesModel();
-}
-
-int TimelineModelAggregator::count(int modelIndex) const
-{
- return d->modelList[modelIndex]->count();
-}
-
-bool TimelineModelAggregator::isEmpty() const
-{
- foreach (const AbstractTimelineModel *modelProxy, d->modelList)
- if (!modelProxy->isEmpty())
- return false;
- return true;
-}
-
-int TimelineModelAggregator::modelOffset(int modelIndex) const
-{
- int ret = 0;
- for (int i = 0; i < modelIndex; ++i)
- ret += d->modelList[i]->height();
- return ret;
-}
-
-int TimelineModelAggregator::rowHeight(int modelIndex, int row) const
-{
- return d->modelList[modelIndex]->rowHeight(row);
-}
-
-int TimelineModelAggregator::rowOffset(int modelIndex, int row) const
-{
- return d->modelList[modelIndex]->rowOffset(row);
-}
-
-void TimelineModelAggregator::setRowHeight(int modelIndex, int row, int height)
-{
- d->modelList[modelIndex]->setRowHeight(row, height);
-}
-
-bool TimelineModelAggregator::expanded(int modelIndex) const
-{
- return d->modelList[modelIndex]->expanded();
-}
-
-void TimelineModelAggregator::setExpanded(int modelIndex, bool expanded)
-{
- d->modelList[modelIndex]->setExpanded(expanded);
-}
-
-bool TimelineModelAggregator::hidden(int modelIndex) const
-{
- return d->modelList[modelIndex]->hidden();
-}
-
-void TimelineModelAggregator::setHidden(int modelIndex, bool hidden)
-{
- d->modelList[modelIndex]->setHidden(hidden);
-}
-
-int TimelineModelAggregator::rowCount(int modelIndex) const
-{
- return d->modelList[modelIndex]->rowCount();
-}
-
-QString TimelineModelAggregator::displayName(int modelIndex) const
-{
- return d->modelList[modelIndex]->displayName();
-}
-
-int TimelineModelAggregator::rowMinValue(int modelIndex, int row) const
-{
- return d->modelList[modelIndex]->rowMinValue(row);
-}
-
-int TimelineModelAggregator::rowMaxValue(int modelIndex, int row) const
-{
- return d->modelList[modelIndex]->rowMaxValue(row);
-}
-
-int TimelineModelAggregator::firstIndex(int modelIndex, qint64 startTime) const
-{
- return d->modelList[modelIndex]->firstIndex(startTime);
-}
-
-int TimelineModelAggregator::firstIndexNoParents(int modelIndex, qint64 startTime) const
-{
- return d->modelList[modelIndex]->firstIndexNoParents(startTime);
-}
-
-int TimelineModelAggregator::lastIndex(int modelIndex, qint64 endTime) const
-{
- return d->modelList[modelIndex]->lastIndex(endTime);
-}
-
-int TimelineModelAggregator::row(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->row(index);
-}
-
-qint64 TimelineModelAggregator::duration(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->duration(index);
-}
-
-qint64 TimelineModelAggregator::startTime(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->startTime(index);
-}
-
-qint64 TimelineModelAggregator::endTime(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->endTime(index);
-}
-
-int TimelineModelAggregator::selectionId(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->selectionId(index);
-}
-
-int TimelineModelAggregator::typeId(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->typeId(index);
-}
-
-int TimelineModelAggregator::bindingLoopDest(int modelIndex,int index) const
-{
- return d->modelList[modelIndex]->bindingLoopDest(index);
-}
-
-QColor TimelineModelAggregator::color(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->color(index);
-}
-
-float TimelineModelAggregator::relativeHeight(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->relativeHeight(index);
-}
-
-QVariantList TimelineModelAggregator::labels(int modelIndex) const
-{
- return d->modelList[modelIndex]->labels();
-}
-
-QVariantMap TimelineModelAggregator::details(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->details(index);
-}
-
-QVariantMap TimelineModelAggregator::location(int modelIndex, int index) const
-{
- return d->modelList[modelIndex]->location(index);
-}
-
-bool TimelineModelAggregator::isSelectionIdValid(int modelIndex, int typeIndex) const
-{
- return d->modelList[modelIndex]->isSelectionIdValid(typeIndex);
-}
-
-int TimelineModelAggregator::selectionIdForLocation(int modelIndex, const QString &filename,
- int line, int column) const
-{
- return d->modelList[modelIndex]->selectionIdForLocation(filename, line, column);
-}
-
-void TimelineModelAggregator::swapModels(int modelIndex1, int modelIndex2)
-{
- AbstractTimelineModel *&model1 = d->modelList[modelIndex1];
- AbstractTimelineModel *&model2 = d->modelList[modelIndex2];
- std::swap(d->modelManagerIndexMapping[model1->modelId()],
- d->modelManagerIndexMapping[model2->modelId()]);
- std::swap(model1, model2);
- emit modelsChanged(modelIndex1, modelIndex2);
-}
-
-QString TimelineModelAggregator::noteText(int noteId) const
-{
- return d->modelManager->notesModel()->text(noteId);
-}
-
-QString TimelineModelAggregator::noteText(int modelIndex, int index) const
-{
- int managerId = d->modelList[modelIndex]->modelId();
- int noteId = d->modelManager->notesModel()->get(managerId, index);
- return noteId != -1 ? noteText(noteId) : QString();
-}
-
-void TimelineModelAggregator::setNoteText(int noteId, const QString &text)
-{
- if (text.length() > 0) {
- notes()->update(noteId, text);
- } else {
- notes()->remove(noteId);
- }
-}
-
-void TimelineModelAggregator::setNoteText(int modelIndex, int index, const QString &text)
-{
- int managerId = d->modelList[modelIndex]->modelId();
- NotesModel *notesModel = notes();
- int noteId = notesModel->get(managerId, index);
- if (noteId == -1) {
- if (text.length() > 0)
- notesModel->add(managerId, index, text);
- } else {
- setNoteText(noteId, text);
- }
-}
-
-int TimelineModelAggregator::noteTimelineModel(int noteIndex) const
-{
- return d->modelManagerIndexMapping[notes()->timelineModel(noteIndex)];
-}
-
-int TimelineModelAggregator::noteTimelineIndex(int noteIndex) const
-{
- return notes()->timelineIndex(noteIndex);
-}
-
-QVariantList TimelineModelAggregator::notesByTimelineModel(int modelIndex) const
-{
- int managerId = d->modelList[modelIndex]->modelId();
- return notes()->byTimelineModel(managerId);
-}
-
-QVariantList TimelineModelAggregator::notesByTypeId(int typeId) const
-{
- return notes()->byTypeId(typeId);
-}
-
-int TimelineModelAggregator::noteCount() const
-{
- return notes()->count();
-}
-
-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();
-}
-
-} // namespace Internal
-} // namespace QmlProfiler
diff --git a/src/plugins/qmlprofiler/timelinemodelaggregator.h b/src/plugins/qmlprofiler/timelinemodelaggregator.h
deleted file mode 100644
index 9040f0da547..00000000000
--- a/src/plugins/qmlprofiler/timelinemodelaggregator.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company 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
- Q_PROPERTY(int height READ height NOTIFY heightChanged)
- Q_PROPERTY(QVariantList models READ models NOTIFY modelsChanged)
-public:
- TimelineModelAggregator(QObject *parent = 0);
- ~TimelineModelAggregator();
-
- int height() const;
- void setModelManager(QmlProfilerModelManager *modelManager);
- void addModel(AbstractTimelineModel *m);
- const AbstractTimelineModel *model(int modelIndex) const;
- QVariantList models() const;
- int modelIndexFromManagerIndex(int modelManagerIndex) const;
-
- Q_INVOKABLE NotesModel *notes() const;
- Q_INVOKABLE int count(int modelIndex) 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 bool isEmpty() const;
-
- Q_INVOKABLE int modelOffset(int modelIndex) const;
- Q_INVOKABLE int rowHeight(int modelIndex, int row) const;
- Q_INVOKABLE void setRowHeight(int modelIndex, int row, int height);
- Q_INVOKABLE int rowOffset(int modelIndex, int row) const;
-
- Q_INVOKABLE bool expanded(int modelIndex) const;
- Q_INVOKABLE void setExpanded(int modelIndex, bool expanded);
-
- Q_INVOKABLE bool hidden(int modelIndex) const;
- Q_INVOKABLE void setHidden(int modelIndex, bool hidden);
-
- Q_INVOKABLE int rowCount(int modelIndex) const;
- Q_INVOKABLE QString displayName(int modelIndex) const;
- Q_INVOKABLE int rowMinValue(int modelIndex, int row) const;
- Q_INVOKABLE int rowMaxValue(int modelIndex, int row) const;
-
- Q_INVOKABLE int firstIndex(int modelIndex, qint64 startTime) const;
- Q_INVOKABLE int firstIndexNoParents(int modelIndex, qint64 startTime) const;
- Q_INVOKABLE int lastIndex(int modelIndex, qint64 endTime) const;
-
- Q_INVOKABLE int row(int modelIndex, int index) const;
- Q_INVOKABLE qint64 duration(int modelIndex, int index) const;
- Q_INVOKABLE qint64 startTime(int modelIndex, int index) const;
- Q_INVOKABLE qint64 endTime(int modelIndex, int index) const;
- Q_INVOKABLE int selectionId(int modelIndex, int index) const;
- Q_INVOKABLE int typeId(int modelIndex, int index) const;
- Q_INVOKABLE int bindingLoopDest(int modelIndex, int index) const;
- Q_INVOKABLE QColor color(int modelIndex, int index) const;
- Q_INVOKABLE float relativeHeight(int modelIndex, int index) const;
-
- Q_INVOKABLE QVariantList labels(int modelIndex) const;
-
- Q_INVOKABLE QVariantMap details(int modelIndex, int index) const;
- Q_INVOKABLE QVariantMap location(int modelIndex, int index) const;
-
- Q_INVOKABLE bool isSelectionIdValid(int modelIndex, int typeIndex) const;
- Q_INVOKABLE int selectionIdForLocation(int modelIndex, const QString &filename, int line,
- int column) const;
-
- Q_INVOKABLE void swapModels(int modelIndex1, int modelIndex2);
- Q_INVOKABLE QString noteText(int noteId) const;
- Q_INVOKABLE QString noteText(int modelIndex, int index) const;
- Q_INVOKABLE void setNoteText(int noteId, const QString &text);
- Q_INVOKABLE void setNoteText(int modelIndex, int index, const QString &text);
- Q_INVOKABLE int noteTimelineModel(int noteIndex) const;
- Q_INVOKABLE int noteTimelineIndex(int noteIndex) const;
- Q_INVOKABLE QVariantList notesByTimelineModel(int modelIndex) const;
- Q_INVOKABLE QVariantList notesByTypeId(int typeId) const;
- Q_INVOKABLE int noteCount() const;
-
-signals:
- void dataAvailable();
- void stateChanged();
- void expandedChanged();
- void hiddenChanged();
- void rowHeightChanged();
- void notesChanged(int typeId, int modelIndex, int eventIndex);
- void modelsChanged(int modelIndex1, int modelIndex2);
- void heightChanged();
-
-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
deleted file mode 100644
index 518ed6f0dcb..00000000000
--- a/src/plugins/qmlprofiler/timelinerenderer.cpp
+++ /dev/null
@@ -1,709 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "timelinerenderer.h"
-#include "notesmodel.h"
-
-#include <QQmlContext>
-#include <QQmlProperty>
-#include <QTimer>
-#include <QPixmap>
-#include <QPainter>
-#include <QGraphicsSceneMouseEvent>
-#include <QVarLengthArray>
-
-#include <math.h>
-
-using namespace QmlProfiler::Internal;
-
-TimelineRenderer::TimelineRenderer(QQuickPaintedItem *parent) :
- QQuickPaintedItem(parent), m_startTime(0), m_endTime(0), m_spacing(0), m_spacedDuration(0),
- m_lastStartTime(0), m_lastEndTime(0), m_profilerModelProxy(0), m_selectedItem(-1),
- m_selectedModel(-1), m_selectionLocked(true), m_startDragArea(-1), m_endDragArea(-1)
-{
- resetCurrentSelection();
- setAcceptedMouseButtons(Qt::LeftButton);
- setAcceptHoverEvents(true);
-}
-
-void TimelineRenderer::setProfilerModelProxy(QObject *profilerModelProxy)
-{
- if (m_profilerModelProxy) {
- disconnect(m_profilerModelProxy, SIGNAL(expandedChanged()), this, SLOT(requestPaint()));
- disconnect(m_profilerModelProxy, SIGNAL(hiddenChanged()), this, SLOT(requestPaint()));
- disconnect(m_profilerModelProxy, SIGNAL(rowHeightChanged()), this, SLOT(requestPaint()));
- disconnect(m_profilerModelProxy, SIGNAL(modelsChanged(int,int)),
- this, SLOT(swapSelections(int,int)));
- disconnect(m_profilerModelProxy, SIGNAL(notesChanged()), this, SLOT(requestPaint()));
- }
- m_profilerModelProxy = qobject_cast<TimelineModelAggregator *>(profilerModelProxy);
-
- if (m_profilerModelProxy) {
- connect(m_profilerModelProxy, SIGNAL(expandedChanged()), this, SLOT(requestPaint()));
- connect(m_profilerModelProxy, SIGNAL(hiddenChanged()), this, SLOT(requestPaint()));
- connect(m_profilerModelProxy, SIGNAL(rowHeightChanged()), this, SLOT(requestPaint()));
- connect(m_profilerModelProxy, SIGNAL(modelsChanged(int,int)),
- this, SLOT(swapSelections(int,int)));
- connect(m_profilerModelProxy, SIGNAL(notesChanged(int,int,int)),
- this, SLOT(requestPaint()));
- }
- emit profilerModelProxyChanged(m_profilerModelProxy);
-}
-
-void TimelineRenderer::componentComplete()
-{
- const QMetaObject *metaObject = this->metaObject();
- int propertyCount = metaObject->propertyCount();
- int requestPaintMethod = metaObject->indexOfMethod("requestPaint()");
- for (int ii = TimelineRenderer::staticMetaObject.propertyCount(); ii < propertyCount; ++ii) {
- QMetaProperty p = metaObject->property(ii);
- if (p.hasNotifySignal())
- QMetaObject::connect(this, p.notifySignalIndex(), this, requestPaintMethod, 0, 0);
- }
- QQuickItem::componentComplete();
-}
-
-void TimelineRenderer::requestPaint()
-{
- update();
-}
-
-void TimelineRenderer::swapSelections(int modelIndex1, int modelIndex2)
-{
- // Any hovered event is most likely useless now. Reset it.
- resetCurrentSelection();
-
- // Explicitly selected events can be tracked in a useful way.
- if (m_selectedModel == modelIndex1)
- setSelectedModel(modelIndex2);
- else if (m_selectedModel == modelIndex2)
- setSelectedModel(modelIndex1);
-
- update();
-}
-
-inline void TimelineRenderer::getItemXExtent(int modelIndex, int i, int &currentX, int &itemWidth)
-{
- qint64 start = m_profilerModelProxy->startTime(modelIndex, i) - m_startTime;
-
- // avoid integer overflows by using floating point for width calculations. m_spacing is qreal,
- // too, so for some intermediate calculations we have to use floats anyway.
- qreal rawWidth;
- if (start > 0) {
- currentX = static_cast<int>(start * m_spacing);
- rawWidth = m_profilerModelProxy->duration(modelIndex, i) * m_spacing;
- } else {
- currentX = -OutOfScreenMargin;
- // Explicitly round the "start" part down, away from 0, to match the implicit rounding of
- // currentX in the > 0 case. If we don't do that we get glitches where a pixel is added if
- // the element starts outside the screen and subtracted if it starts inside the screen.
- rawWidth = m_profilerModelProxy->duration(modelIndex, i) * m_spacing +
- floor(start * m_spacing) + OutOfScreenMargin;
- }
- if (rawWidth < MinimumItemWidth) {
- currentX -= static_cast<int>((MinimumItemWidth - rawWidth) / 2);
- itemWidth = MinimumItemWidth;
- } else if (rawWidth > m_spacedDuration - static_cast<qreal>(currentX - OutOfScreenMargin)) {
- itemWidth = static_cast<int>(m_spacedDuration) - currentX + OutOfScreenMargin;
- } else {
- itemWidth = static_cast<int>(rawWidth);
- }
-}
-
-void TimelineRenderer::resetCurrentSelection()
-{
- m_currentSelection.startTime = -1;
- m_currentSelection.endTime = -1;
- m_currentSelection.row = -1;
- m_currentSelection.eventIndex = -1;
- m_currentSelection.modelIndex = -1;
-}
-
-void TimelineRenderer::paint(QPainter *p)
-{
- qint64 windowDuration = m_endTime - m_startTime;
- if (windowDuration <= 0)
- return;
-
- m_spacing = qreal(width()) / windowDuration;
- m_spacedDuration = (m_endTime - m_startTime) * m_spacing + 2 * OutOfScreenMargin;
-
- p->setPen(Qt::transparent);
-
- for (int modelIndex = 0; modelIndex < m_profilerModelProxy->modelCount(); modelIndex++) {
- if (m_profilerModelProxy->hidden(modelIndex))
- continue;
- int lastIndex = m_profilerModelProxy->lastIndex(modelIndex, m_endTime);
- if (lastIndex >= 0 && lastIndex < m_profilerModelProxy->count(modelIndex)) {
- int firstIndex = m_profilerModelProxy->firstIndex(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);
- }
- }
- }
- drawNotes(p);
- m_lastStartTime = m_startTime;
- m_lastEndTime = m_endTime;
-
-}
-
-void TimelineRenderer::drawItemsToPainter(QPainter *p, int modelIndex, int fromIndex, int toIndex)
-{
- p->save();
- p->setPen(Qt::transparent);
- int modelRowStart = 0;
- for (int mi = 0; mi < modelIndex; mi++)
- modelRowStart += m_profilerModelProxy->model(mi)->height();
-
- for (int i = fromIndex; i <= toIndex; i++) {
- int currentX, currentY, itemWidth, itemHeight;
-
- int rowNumber = m_profilerModelProxy->row(modelIndex, i);
- currentY = modelRowStart + m_profilerModelProxy->rowOffset(modelIndex, rowNumber) - y();
- if (currentY >= height())
- continue;
-
- itemHeight = m_profilerModelProxy->rowHeight(modelIndex, rowNumber) *
- m_profilerModelProxy->relativeHeight(modelIndex, i);
-
- currentY += m_profilerModelProxy->rowHeight(modelIndex, rowNumber) - itemHeight;
- if (currentY + itemHeight < 0)
- continue;
-
- getItemXExtent(modelIndex, i, currentX, itemWidth);
-
- // normal events
- p->setBrush(m_profilerModelProxy->color(modelIndex, i));
- p->drawRect(currentX, currentY, itemWidth, itemHeight);
- }
- p->restore();
-}
-
-void TimelineRenderer::drawSelectionBoxes(QPainter *p, int modelIndex, int fromIndex, int toIndex)
-{
- if (m_selectedItem == -1)
- return;
-
-
- int id = m_profilerModelProxy->selectionId(modelIndex, m_selectedItem);
-
- int modelRowStart = 0;
- for (int mi = 0; mi < modelIndex; mi++)
- modelRowStart += m_profilerModelProxy->model(mi)->height();
-
- p->save();
-
- QColor selectionColor = Qt::blue;
- if (m_selectionLocked)
- selectionColor = QColor(96,0,255);
- QPen strongPen(selectionColor, 3);
- QPen lightPen(QBrush(selectionColor.lighter(130)), 2);
- lightPen.setJoinStyle(Qt::MiterJoin);
- p->setPen(lightPen);
- p->setBrush(Qt::transparent);
-
- int currentX, currentY, itemWidth;
- QRect selectedItemRect(0,0,0,0);
- for (int i = fromIndex; i <= toIndex; i++) {
- if (m_profilerModelProxy->selectionId(modelIndex, i) != id)
- continue;
-
- int row = m_profilerModelProxy->row(modelIndex, i);
- int rowHeight = m_profilerModelProxy->rowHeight(modelIndex, row);
- int itemHeight = rowHeight * m_profilerModelProxy->relativeHeight(modelIndex, i);
-
- currentY = modelRowStart + m_profilerModelProxy->rowOffset(modelIndex, row) + rowHeight -
- itemHeight - y();
- if (currentY + itemHeight < 0 || height() < currentY)
- continue;
-
- getItemXExtent(modelIndex, i, currentX, itemWidth);
-
- if (i == m_selectedItem)
- selectedItemRect = QRect(currentX, currentY - 1, itemWidth, itemHeight + 1);
- else
- p->drawRect(currentX, currentY, itemWidth, itemHeight);
- }
-
- // draw the selected item rectangle the last, so that it's overlayed
- if (selectedItemRect.width() != 0) {
- p->setPen(strongPen);
- p->drawRect(selectedItemRect);
- }
-
- p->restore();
-}
-
-void TimelineRenderer::drawBindingLoopMarkers(QPainter *p, int modelIndex, int fromIndex, int toIndex)
-{
- int destindex;
- int xfrom, xto, width;
- int yfrom, yto;
- int radius = 10;
- QPen shadowPen = QPen(QColor("grey"),2);
- QPen markerPen = QPen(QColor("orange"),2);
- QBrush shadowBrush = QBrush(QColor("grey"));
- QBrush markerBrush = QBrush(QColor("orange"));
-
- p->save();
- for (int i = fromIndex; i <= toIndex; i++) {
- destindex = m_profilerModelProxy->bindingLoopDest(modelIndex, i);
- if (destindex >= 0) {
- // to
- getItemXExtent(modelIndex, destindex, xto, width);
- xto += width / 2;
- yto = getYPosition(modelIndex, destindex) + m_profilerModelProxy->rowHeight(modelIndex,
- m_profilerModelProxy->row(modelIndex, destindex)) / 2 - y();
-
- // from
- getItemXExtent(modelIndex, i, xfrom, width);
- xfrom += width / 2;
- yfrom = getYPosition(modelIndex, i) + m_profilerModelProxy->rowHeight(modelIndex,
- m_profilerModelProxy->row(modelIndex, i)) / 2 - y();
-
- // radius (derived from width of origin event)
- radius = 5;
- if (radius * 2 > width)
- radius = width / 2;
- if (radius < 2)
- radius = 2;
-
- int shadowoffset = 2;
- if ((yfrom + radius + shadowoffset < 0 && yto + radius + shadowoffset < 0) ||
- (yfrom - radius >= height() && yto - radius >= height()))
- continue;
-
- // shadow
- p->setPen(shadowPen);
- p->setBrush(shadowBrush);
- p->drawEllipse(QPoint(xfrom, yfrom + shadowoffset), radius, radius);
- p->drawEllipse(QPoint(xto, yto + shadowoffset), radius, radius);
- p->drawLine(QPoint(xfrom, yfrom + shadowoffset), QPoint(xto, yto + shadowoffset));
-
-
- // marker
- p->setPen(markerPen);
- p->setBrush(markerBrush);
- p->drawEllipse(QPoint(xfrom, yfrom), radius, radius);
- p->drawEllipse(QPoint(xto, yto), radius, radius);
- p->drawLine(QPoint(xfrom, yfrom), QPoint(xto, yto));
- }
- }
- p->restore();
-}
-
-void TimelineRenderer::drawNotes(QPainter *p)
-{
- static const QColor shadowBrush("grey");
- static const QColor markerBrush("orange");
- static const int annotationWidth = 4;
- static const int annotationHeight1 = 16;
- static const int annotationHeight2 = 4;
- static const int annotationSpace = 4;
- static const int shadowOffset = 2;
-
- NotesModel *notes = m_profilerModelProxy->notes();
- for (int i = 0; i < notes->count(); ++i) {
- int managerIndex = notes->timelineModel(i);
- if (managerIndex == -1)
- continue;
- int modelIndex = m_profilerModelProxy->modelIndexFromManagerIndex(managerIndex);
- if (m_profilerModelProxy->hidden(modelIndex))
- continue;
- int eventIndex = notes->timelineIndex(i);
- int row = m_profilerModelProxy->row(modelIndex, eventIndex);
- int rowHeight = m_profilerModelProxy->rowHeight(modelIndex, row);
- int currentY = m_profilerModelProxy->rowOffset(modelIndex, row) - y();
- for (int mi = 0; mi < modelIndex; mi++)
- currentY += m_profilerModelProxy->model(mi)->height();
- if (currentY + rowHeight < 0 || height() < currentY)
- continue;
- int currentX;
- int itemWidth;
- getItemXExtent(modelIndex, eventIndex, currentX, itemWidth);
-
- // shadow
- int annoX = currentX + (itemWidth - annotationWidth) / 2;
- int annoY = currentY + rowHeight / 2 -
- (annotationHeight1 + annotationHeight2 + annotationSpace) / 2;
-
- p->setBrush(shadowBrush);
- p->drawRect(annoX, annoY + shadowOffset, annotationWidth, annotationHeight1);
- p->drawRect(annoX, annoY + annotationHeight1 + annotationSpace + shadowOffset,
- annotationWidth, annotationHeight2);
-
- // marker
- p->setBrush(markerBrush);
- p->drawRect(annoX, annoY, annotationWidth, annotationHeight1);
- p->drawRect(annoX, annoY + annotationHeight1 + annotationSpace,
- annotationWidth, annotationHeight2);
- }
-}
-
-int TimelineRenderer::rowFromPosition(int y)
-{
- int ret = 0;
- for (int modelIndex = 0; modelIndex < m_profilerModelProxy->modelCount(); modelIndex++) {
- int modelHeight = m_profilerModelProxy->model(modelIndex)->height();
- if (y < modelHeight) {
- for (int row = 0; row < m_profilerModelProxy->rowCount(modelIndex); ++row) {
- y -= m_profilerModelProxy->rowHeight(modelIndex, row);
- if (y < 0) return ret;
- ++ret;
- }
- } else {
- y -= modelHeight;
- ret += m_profilerModelProxy->rowCount(modelIndex);
- }
- }
- return ret;
-}
-
-int TimelineRenderer::modelFromPosition(int y)
-{
- for (int modelIndex = 0; modelIndex < m_profilerModelProxy->modelCount(); modelIndex++) {
- y -= m_profilerModelProxy->model(modelIndex)->height();
- 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
- if (m_currentSelection.eventIndex == -1 &&
- event->pos().x()+x() >= m_startDragArea &&
- event->pos().x()+x() <= m_endDragArea)
- event->setAccepted(false);
-
-}
-
-void TimelineRenderer::mouseReleaseEvent(QMouseEvent *event)
-{
- Q_UNUSED(event);
- if (!m_profilerModelProxy->isEmpty())
- manageClicked();
-}
-
-void TimelineRenderer::mouseMoveEvent(QMouseEvent *event)
-{
- event->setAccepted(false);
-}
-
-
-void TimelineRenderer::hoverMoveEvent(QHoverEvent *event)
-{
- Q_UNUSED(event);
- manageHovered(event->pos().x(), event->pos().y());
- if (m_currentSelection.eventIndex == -1)
- event->setAccepted(false);
-}
-
-void TimelineRenderer::manageClicked()
-{
- if (m_currentSelection.eventIndex != -1) {
- if (m_currentSelection.eventIndex == m_selectedItem && m_currentSelection.modelIndex == m_selectedModel)
- setSelectionLocked(!m_selectionLocked);
- else
- setSelectionLocked(true);
-
- // itemPressed() will trigger an update of the events and JavaScript views. Make sure the
- // correct event is already selected when that happens, to prevent confusion.
- selectFromEventIndex(m_currentSelection.modelIndex, m_currentSelection.eventIndex);
- emit itemPressed(m_currentSelection.modelIndex, m_currentSelection.eventIndex);
- } else {
- setSelectionLocked(false);
- selectFromEventIndex(m_currentSelection.modelIndex, m_currentSelection.eventIndex);
- }
-}
-
-void TimelineRenderer::manageHovered(int mouseX, int mouseY)
-{
- if (m_endTime - m_startTime <=0 || m_lastEndTime - m_lastStartTime <= 0)
- return;
-
- // Make the "selected" area 3 pixels wide by adding/subtracting 1 to catch very narrow events.
- qint64 startTime = (mouseX - 1) * (m_endTime - m_startTime) / width() + m_startTime;
- qint64 endTime = (mouseX + 1) * (m_endTime - m_startTime) / width() + m_startTime;
- int row = rowFromPosition(mouseY + y());
- int modelIndex = modelFromPosition(mouseY + y());
-
- // already covered? nothing to do
- if (m_currentSelection.eventIndex != -1 &&
- endTime >= m_currentSelection.startTime &&
- startTime <= m_currentSelection.endTime &&
- row == m_currentSelection.row) {
- return;
- }
-
- // find if there's items in the time range
- int eventFrom = m_profilerModelProxy->firstIndex(modelIndex, startTime);
- int eventTo = m_profilerModelProxy->lastIndex(modelIndex, endTime);
- if (eventFrom == -1 ||
- eventTo < eventFrom || eventTo >= m_profilerModelProxy->count(modelIndex)) {
- 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;
- for (int i=eventTo; i>=eventFrom; --i) {
- itemRow = modelRowStart + m_profilerModelProxy->row(modelIndex, i);
-
- if (itemRow == row) {
- // There can be small events that don't reach the cursor position after large events
- // that do but are in a different row.
- qint64 itemEnd = m_profilerModelProxy->endTime(modelIndex, i);
- if (itemEnd < startTime)
- continue;
-
- // match
- m_currentSelection.eventIndex = i;
- m_currentSelection.startTime = m_profilerModelProxy->startTime(modelIndex, i);
- m_currentSelection.endTime = itemEnd;
- m_currentSelection.row = row;
- m_currentSelection.modelIndex = modelIndex;
- if (!m_selectionLocked)
- selectFromEventIndex(modelIndex, i);
- return;
- }
- }
-
- m_currentSelection.eventIndex = -1;
- return;
-}
-
-void TimelineRenderer::clearData()
-{
- m_lastStartTime = 0;
- m_lastEndTime = 0;
- m_spacing = 0;
- m_spacedDuration = 0;
- resetCurrentSelection();
- setStartTime(0);
- setEndTime(0);
- setSelectedItem(-1);
- setSelectedModel(-1);
- setSelectionLocked(true);
- setStartDragArea(-1);
- setEndDragArea(-1);
-}
-
-int TimelineRenderer::getYPosition(int modelIndex, int index) const
-{
- Q_ASSERT(m_profilerModelProxy);
- if (index >= m_profilerModelProxy->count(modelIndex))
- return 0;
-
- int modelRowStart = 0;
- for (int mi = 0; mi < modelIndex; mi++)
- modelRowStart += m_profilerModelProxy->model(mi)->height();
-
- return modelRowStart + m_profilerModelProxy->rowOffset(modelIndex,
- m_profilerModelProxy->row(modelIndex, index));
-}
-
-void TimelineRenderer::selectNext()
-{
- if (m_profilerModelProxy->isEmpty())
- return;
-
- qint64 searchTime = m_startTime;
- if (m_selectedItem != -1)
- searchTime = m_profilerModelProxy->startTime(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->startTime(i, 0) > searchTime)
- itemIndexes[i] = 0;
- else
- itemIndexes[i] = (m_profilerModelProxy->lastIndex(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->startTime(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->startTime(i,0) < candidateStartTime) {
- candidateModelIndex = i;
- itemIndex = 0;
- candidateStartTime = m_profilerModelProxy->startTime(i,0);
- }
- }
-
- selectFromEventIndex(candidateModelIndex, itemIndex);
-}
-
-void TimelineRenderer::selectPrev()
-{
- if (m_profilerModelProxy->isEmpty())
- return;
-
- qint64 searchTime = m_endTime;
- if (m_selectedItem != -1)
- searchTime = m_profilerModelProxy->startTime(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->lastIndex(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->startTime(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->startTime(i,m_profilerModelProxy->count(i)-1) > candidateStartTime) {
- candidateModelIndex = i;
- itemIndex = m_profilerModelProxy->count(candidateModelIndex) - 1;
- candidateStartTime = m_profilerModelProxy->startTime(i,m_profilerModelProxy->count(i)-1);
- }
- }
-
- selectFromEventIndex(candidateModelIndex, itemIndex);
-}
-
-int TimelineRenderer::nextItemFromSelectionId(int modelIndex, int selectionId) const
-{
- int modelCount = m_profilerModelProxy->count(modelIndex);
- if (modelCount == 0)
- return -1;
-
- int ndx = -1;
- if (m_selectedItem == -1 || modelIndex != m_selectedModel)
- ndx = m_profilerModelProxy->firstIndexNoParents(modelIndex, m_startTime);
- else
- ndx = m_selectedItem + 1;
-
- if (ndx < 0 || ndx >= modelCount)
- ndx = 0;
- int startIndex = ndx;
- do {
- if (m_profilerModelProxy->selectionId(modelIndex, ndx) == selectionId)
- return ndx;
- ndx = (ndx + 1) % modelCount;
- } while (ndx != startIndex);
- return -1;
-}
-
-int TimelineRenderer::prevItemFromSelectionId(int modelIndex, int selectionId) const
-{
- int ndx = -1;
- if (m_selectedItem == -1 || modelIndex != m_selectedModel)
- ndx = m_profilerModelProxy->firstIndexNoParents(modelIndex, m_startTime);
- else
- ndx = m_selectedItem - 1;
- if (ndx < 0)
- ndx = m_profilerModelProxy->count(modelIndex) - 1;
- int startIndex = ndx;
- do {
- if (m_profilerModelProxy->selectionId(modelIndex, ndx) == selectionId)
- return ndx;
- if (--ndx < 0)
- ndx = m_profilerModelProxy->count(modelIndex)-1;
- } while (ndx != startIndex);
- return -1;
-}
-
-void TimelineRenderer::selectFromEventIndex(int modelIndex, int eventIndex)
-{
- if (modelIndex != m_selectedModel || eventIndex != m_selectedItem) {
- setSelectedModel(modelIndex);
- setSelectedItem(eventIndex);
- emit selectionChanged(modelIndex, eventIndex);
- }
-}
-
-void TimelineRenderer::selectNextFromSelectionId(int modelIndex, int typeId)
-{
- selectFromEventIndex(modelIndex, nextItemFromSelectionId(modelIndex, typeId));
-}
-
-void TimelineRenderer::selectPrevFromSelectionId(int modelIndex, int typeId)
-{
- selectFromEventIndex(modelIndex, prevItemFromSelectionId(modelIndex, typeId));
-}
diff --git a/src/plugins/qmlprofiler/timelinerenderer.h b/src/plugins/qmlprofiler/timelinerenderer.h
deleted file mode 100644
index 6bc18f23794..00000000000
--- a/src/plugins/qmlprofiler/timelinerenderer.h
+++ /dev/null
@@ -1,238 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef TIMELINERENDERER_H
-#define TIMELINERENDERER_H
-
-#include <QQuickPaintedItem>
-#include <QJSValue>
-#include "qmlprofilertimelinemodelproxy.h"
-#include "timelinemodelaggregator.h"
-
-namespace QmlProfiler {
-namespace Internal {
-
-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 *profilerModelProxy READ profilerModelProxy WRITE setProfilerModelProxy NOTIFY profilerModelProxyChanged)
- Q_PROPERTY(bool selectionLocked READ selectionLocked WRITE setSelectionLocked NOTIFY selectionLockedChanged)
- Q_PROPERTY(int selectedItem READ selectedItem NOTIFY selectedItemChanged)
- Q_PROPERTY(int selectedModel READ selectedModel 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(QQuickPaintedItem *parent = 0);
-
- qint64 startTime() const
- {
- return m_startTime;
- }
-
- qint64 endTime() const
- {
- return m_endTime;
- }
-
- bool selectionLocked() const
- {
- return m_selectionLocked;
- }
-
- int selectedItem() const
- {
- return m_selectedItem;
- }
-
- int selectedModel() const
- {
- return m_selectedModel;
- }
-
- int startDragArea() const
- {
- return m_startDragArea;
- }
-
- int endDragArea() const
- {
- return m_endDragArea;
- }
-
- TimelineModelAggregator *profilerModelProxy() const { return m_profilerModelProxy; }
- void setProfilerModelProxy(QObject *profilerModelProxy);
-
- Q_INVOKABLE int getYPosition(int modelIndex, int index) const;
-
- Q_INVOKABLE void selectNext();
- Q_INVOKABLE void selectPrev();
- Q_INVOKABLE int nextItemFromSelectionId(int modelIndex, int selectionId) const;
- Q_INVOKABLE int prevItemFromSelectionId(int modelIndex, int selectionId) const;
- Q_INVOKABLE void selectFromEventIndex(int modelIndex, int index);
- Q_INVOKABLE void selectNextFromSelectionId(int modelIndex, int selectionId);
- Q_INVOKABLE void selectPrevFromSelectionId(int modelIndex, int selectionId);
-
-signals:
- void startTimeChanged(qint64 arg);
- void endTimeChanged(qint64 arg);
- void profilerModelProxyChanged(TimelineModelAggregator *list);
- void selectionLockedChanged(bool locked);
- void selectedItemChanged(int itemIndex);
- void selectedModelChanged(int modelIndex);
- void selectionChanged(int modelIndex, int itemIndex);
- void startDragAreaChanged(int startDragArea);
- void endDragAreaChanged(int endDragArea);
- void itemPressed(int modelIndex, int pressedItem);
-
-public slots:
- void clearData();
- void requestPaint();
- void swapSelections(int modelIndex1, int modelIndex2);
-
- void setStartTime(qint64 arg)
- {
- if (m_startTime != arg) {
- m_startTime = arg;
- emit startTimeChanged(arg);
- }
- }
-
- void setEndTime(qint64 arg)
- {
- if (m_endTime != arg) {
- m_endTime = arg;
- emit endTimeChanged(arg);
- }
- }
-
- void setSelectionLocked(bool locked)
- {
- if (m_selectionLocked != locked) {
- m_selectionLocked = locked;
- update();
- emit selectionLockedChanged(locked);
- }
- }
-
- void setStartDragArea(int startDragArea)
- {
- if (m_startDragArea != startDragArea) {
- m_startDragArea = startDragArea;
- emit startDragAreaChanged(startDragArea);
- }
- }
-
- void setEndDragArea(int endDragArea)
- {
- if (m_endDragArea != endDragArea) {
- m_endDragArea = endDragArea;
- emit endDragAreaChanged(endDragArea);
- }
- }
-
-protected:
- virtual void paint(QPainter *);
- virtual void componentComplete();
- virtual void mousePressEvent(QMouseEvent *event);
- virtual void mouseReleaseEvent(QMouseEvent *event);
- virtual void mouseMoveEvent(QMouseEvent *event);
- virtual void hoverMoveEvent(QHoverEvent *event);
-
-private:
- 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);
- void drawNotes(QPainter *p);
-
- int modelFromPosition(int y);
- int rowFromPosition(int y);
-
- void manageClicked();
- void manageHovered(int mouseX, int mouseY);
-
- void setSelectedItem(int itemIndex)
- {
- if (m_selectedItem != itemIndex) {
- m_selectedItem = itemIndex;
- update();
- emit selectedItemChanged(itemIndex);
- }
- }
-
- void setSelectedModel(int modelIndex)
- {
- if (m_selectedModel != modelIndex) {
- m_selectedModel = modelIndex;
- update();
- emit selectedModelChanged(modelIndex);
- }
- }
-
-private:
- static const int OutOfScreenMargin = 3; // margin to make sure the rectangles stay invisible
- static const int MinimumItemWidth = 3;
-
- inline void getItemXExtent(int modelIndex, int i, int &currentX, int &itemWidth);
- void resetCurrentSelection();
-
- qint64 m_startTime;
- qint64 m_endTime;
- qreal m_spacing;
- qreal m_spacedDuration;
-
- qint64 m_lastStartTime;
- qint64 m_lastEndTime;
-
- 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;
-};
-
-} // namespace Internal
-} // namespace QmlProfiler
-
-QML_DECLARE_TYPE(QmlProfiler::Internal::TimelineRenderer)
-
-#endif // TIMELINERENDERER_H
diff --git a/src/plugins/qmlprojectmanager/QmlProjectManager.json.in b/src/plugins/qmlprojectmanager/QmlProjectManager.json.in
index b619ad643da..e0c9da40239 100644
--- a/src/plugins/qmlprojectmanager/QmlProjectManager.json.in
+++ b/src/plugins/qmlprojectmanager/QmlProjectManager.json.in
@@ -2,6 +2,7 @@
\"Name\" : \"QmlProjectManager\",
\"Version\" : \"$$QTCREATOR_VERSION\",
\"CompatVersion\" : \"$$QTCREATOR_COMPAT_VERSION\",
+ \"DisabledByDefault\" : true,
\"Vendor\" : \"The Qt Company Ltd\",
\"Copyright\" : \"(C) 2015 The Qt Company Ltd\",
\"License\" : [ \"Commercial Usage\",
diff --git a/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp b/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp
index de7e4abf815..5142197194d 100644
--- a/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp
+++ b/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp
@@ -31,6 +31,7 @@
#include "filefilteritems.h"
#include <utils/filesystemwatcher.h>
+#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -179,7 +180,7 @@ bool FileFilterBaseItem::matchesFile(const QString &filePath) const
return true;
}
- const QString &fileName = QFileInfo(filePath).fileName();
+ const QString &fileName = Utils::FileName::fromString(filePath).fileName();
if (!fileMatches(fileName))
return false;
diff --git a/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp b/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
index 4bae8b3296b..90180aaf7d0 100644
--- a/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
+++ b/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
@@ -89,8 +89,8 @@ Core::BaseFileWizard *QmlApplicationWizard::create(QWidget *parent, const Wizard
{
QmlApplicationWizardDialog *wizardDialog = new QmlApplicationWizardDialog(parent, parameters);
- connect(wizardDialog, SIGNAL(projectParametersChanged(QString,QString)), m_qmlApp,
- SLOT(setProjectNameAndBaseDirectory(QString,QString)));
+ connect(wizardDialog, &QmlApplicationWizardDialog::projectParametersChanged,
+ m_qmlApp, &QmlApp::setProjectNameAndBaseDirectory);
wizardDialog->setPath(parameters.defaultPath());
diff --git a/src/plugins/qmlprojectmanager/qmlproject.cpp b/src/plugins/qmlprojectmanager/qmlproject.cpp
index 1d22deed56b..4647eede622 100644
--- a/src/plugins/qmlprojectmanager/qmlproject.cpp
+++ b/src/plugins/qmlprojectmanager/qmlproject.cpp
@@ -100,7 +100,7 @@ void QmlProject::addedTarget(ProjectExplorer::Target *target)
void QmlProject::onActiveTargetChanged(ProjectExplorer::Target *target)
{
if (m_activeTarget)
- disconnect(m_activeTarget, SIGNAL(kitChanged()), this, SLOT(onKitChanged()));
+ disconnect(m_activeTarget, &ProjectExplorer::Target::kitChanged, this, &QmlProject::onKitChanged);
m_activeTarget = target;
if (m_activeTarget)
connect(target, SIGNAL(kitChanged()), this, SLOT(onKitChanged()));
@@ -397,11 +397,9 @@ bool QmlProject::fromMap(const QVariantMap &map)
foreach (Target *t, targets())
addedTarget(t);
- connect(this, SIGNAL(addedTarget(ProjectExplorer::Target*)),
- this, SLOT(addedTarget(ProjectExplorer::Target*)));
+ connect(this, &QmlProject::addedTarget, this, &QmlProject::addedTarget);
- connect(this, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
- this, SLOT(onActiveTargetChanged(ProjectExplorer::Target*)));
+ connect(this, &QmlProject::activeTargetChanged, this, &QmlProject::onActiveTargetChanged);
onActiveTargetChanged(activeTarget());
diff --git a/src/plugins/qmlprojectmanager/qmlprojectfile.cpp b/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
index 90b3ff9496e..801ef4b16e6 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
@@ -36,7 +36,7 @@
namespace QmlProjectManager {
namespace Internal {
-QmlProjectFile::QmlProjectFile(QmlProject *parent, QString fileName)
+QmlProjectFile::QmlProjectFile(QmlProject *parent, const QString &fileName)
: Core::IDocument(parent),
m_project(parent)
{
@@ -44,7 +44,7 @@ QmlProjectFile::QmlProjectFile(QmlProject *parent, QString fileName)
QTC_CHECK(!fileName.isEmpty());
setId("Qml.ProjectFile");
setMimeType(QLatin1String(Constants::QMLPROJECT_MIMETYPE));
- setFilePath(fileName);
+ setFilePath(Utils::FileName::fromString(fileName));
}
QmlProjectFile::~QmlProjectFile()
diff --git a/src/plugins/qmlprojectmanager/qmlprojectfile.h b/src/plugins/qmlprojectmanager/qmlprojectfile.h
index 534c08f2a09..b9cbbfd9fe9 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectfile.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectfile.h
@@ -44,7 +44,7 @@ class QmlProjectFile : public Core::IDocument
Q_OBJECT
public:
- QmlProjectFile(QmlProject *parent, QString fileName);
+ QmlProjectFile(QmlProject *parent, const QString &fileName);
virtual ~QmlProjectFile();
virtual bool save(QString *errorString, const QString &fileName, bool autoSave);
diff --git a/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp b/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
index 878a79a1f36..bab143e8d47 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
@@ -42,11 +42,11 @@ namespace QmlProjectManager {
namespace Internal {
QmlProjectNode::QmlProjectNode(QmlProject *project, Core::IDocument *projectFile)
- : ProjectExplorer::ProjectNode(QFileInfo(projectFile->filePath()).absoluteFilePath()),
+ : ProjectExplorer::ProjectNode(projectFile->filePath().toString()),
m_project(project),
m_projectFile(projectFile)
{
- setDisplayName(QFileInfo(projectFile->filePath()).completeBaseName());
+ setDisplayName(projectFile->filePath().toFileInfo().completeBaseName());
// make overlay
const QSize desiredSize = QSize(16, 16);
const QIcon projectBaseIcon(QLatin1String(":/qmlproject/images/qmlfolder.png"));
@@ -63,7 +63,7 @@ Core::IDocument *QmlProjectNode::projectFile() const
{ return m_projectFile; }
QString QmlProjectNode::projectFilePath() const
-{ return m_projectFile->filePath(); }
+{ return m_projectFile->filePath().toString(); }
void QmlProjectNode::refresh()
{
diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
index c5ccd6d1042..46c9dffecef 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
@@ -257,7 +257,7 @@ void QmlProjectRunConfiguration::changeCurrentFile(IEditor *editor)
editor = EditorManager::currentEditor();
if (editor)
- m_currentFileFilename = editor->document()->filePath();
+ m_currentFileFilename = editor->document()->filePath().toString();
updateEnabled();
}
@@ -267,7 +267,7 @@ void QmlProjectRunConfiguration::updateEnabled()
if (mainScriptSource() == FileInEditor) {
IDocument *document = EditorManager::currentDocument();
if (document) {
- m_currentFileFilename = document->filePath();
+ m_currentFileFilename = document->filePath().toString();
if (MimeDatabase::findByFile(mainScript()).type() == QLatin1String("application/x-qml"))
qmlFileFound = true;
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp
index 47b03e70f5f..dd1dc400ec9 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp
@@ -71,13 +71,15 @@ QmlProjectRunConfigurationWidget::QmlProjectRunConfigurationWidget(QmlProjectRun
m_fileListCombo = new QComboBox;
m_fileListCombo->setModel(m_fileListModel);
- connect(m_fileListCombo, SIGNAL(activated(int)), this, SLOT(setMainScript(int)));
+ connect(m_fileListCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated),
+ this, &QmlProjectRunConfigurationWidget::setMainScript);
connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(fileListChanged()),
SLOT(updateFileComboBox()));
QLineEdit *qmlViewerArgs = new QLineEdit;
qmlViewerArgs->setText(rc->m_qmlViewerArgs);
- connect(qmlViewerArgs, SIGNAL(textChanged(QString)), this, SLOT(onViewerArgsChanged()));
+ connect(qmlViewerArgs, &QLineEdit::textChanged,
+ this, &QmlProjectRunConfigurationWidget::onViewerArgsChanged);
form->addRow(tr("Arguments:"), qmlViewerArgs);
form->addRow(tr("Main QML file:"), m_fileListCombo);
diff --git a/src/plugins/qnx/bardescriptordocument.cpp b/src/plugins/qnx/bardescriptordocument.cpp
index 2984f35b7e1..7545adfad6f 100644
--- a/src/plugins/qnx/bardescriptordocument.cpp
+++ b/src/plugins/qnx/bardescriptordocument.cpp
@@ -68,7 +68,7 @@ bool BarDescriptorDocument::open(QString *errorString, const QString &fileName)
if (read(fileName, &contents, errorString) != Utils::TextFileFormat::ReadSuccess)
return false;
- setFilePath(fileName);
+ setFilePath(Utils::FileName::fromString(fileName));
const bool result = loadContent(contents, false);
@@ -83,7 +83,7 @@ bool BarDescriptorDocument::save(QString *errorString, const QString &fn, bool a
QTC_ASSERT(!autoSave, return false);
QTC_ASSERT(fn.isEmpty(), return false);
- const bool result = write(filePath(), xmlSource(), errorString);
+ const bool result = write(filePath().toString(), xmlSource(), errorString);
if (!result)
return false;
@@ -94,14 +94,12 @@ bool BarDescriptorDocument::save(QString *errorString, const QString &fn, bool a
QString BarDescriptorDocument::defaultPath() const
{
- QFileInfo fi(filePath());
- return fi.absolutePath();
+ return filePath().toFileInfo().absolutePath();
}
QString BarDescriptorDocument::suggestedFileName() const
{
- QFileInfo fi(filePath());
- return fi.fileName();
+ return filePath().fileName();
}
bool BarDescriptorDocument::shouldAutoSave() const
@@ -135,7 +133,7 @@ bool BarDescriptorDocument::reload(QString *errorString, Core::IDocument::Reload
if (flag == Core::IDocument::FlagIgnore)
return true;
- return open(errorString, filePath());
+ return open(errorString, filePath().toString());
}
QString BarDescriptorDocument::xmlSource() const
diff --git a/src/plugins/qnx/bardescriptoreditor.cpp b/src/plugins/qnx/bardescriptoreditor.cpp
index 86259a5f6e4..863b529b2bf 100644
--- a/src/plugins/qnx/bardescriptoreditor.cpp
+++ b/src/plugins/qnx/bardescriptoreditor.cpp
@@ -112,7 +112,7 @@ bool BarDescriptorEditor::open(QString *errorString, const QString &fileName, co
if (result) {
BarDescriptorEditorWidget *editorWidget = qobject_cast<BarDescriptorEditorWidget *>(widget());
QTC_ASSERT(editorWidget, return false);
- editorWidget->setFilePath(fileName);
+ editorWidget->setFilePath(Utils::FileName::fromString(fileName));
}
return result;
diff --git a/src/plugins/qnx/bardescriptoreditorassetswidget.cpp b/src/plugins/qnx/bardescriptoreditorassetswidget.cpp
index 8a19954984a..c973c347ee3 100644
--- a/src/plugins/qnx/bardescriptoreditorassetswidget.cpp
+++ b/src/plugins/qnx/bardescriptoreditorassetswidget.cpp
@@ -101,7 +101,7 @@ void BarDescriptorEditorAssetsWidget::addAsset(const QString &fullPath)
BarDescriptorAsset asset;
asset.source = fullPath;
- asset.destination = QFileInfo(fullPath).fileName();
+ asset.destination = Utils::FileName::fromString(fullPath).fileName();
asset.entry = false;
addAsset(asset);
}
diff --git a/src/plugins/qnx/bardescriptoreditorentrypointwidget.cpp b/src/plugins/qnx/bardescriptoreditorentrypointwidget.cpp
index 8885135960c..6ed3e6be20e 100644
--- a/src/plugins/qnx/bardescriptoreditorentrypointwidget.cpp
+++ b/src/plugins/qnx/bardescriptoreditorentrypointwidget.cpp
@@ -111,11 +111,11 @@ void BarDescriptorEditorEntryPointWidget::updateWidgetValue(BarDescriptorDocumen
void BarDescriptorEditorEntryPointWidget::emitChanged(BarDescriptorDocument::Tag tag)
{
if (tag == BarDescriptorDocument::icon) {
- emit changed(tag, QFileInfo(m_ui->iconFilePath->path()).fileName());
+ emit changed(tag, Utils::FileName::fromString(m_ui->iconFilePath->path()).fileName());
} else if (tag == BarDescriptorDocument::splashScreens) {
QStringList list;
foreach (const QString &splashScreen, m_splashScreenModel->stringList())
- list << QFileInfo(splashScreen).fileName();
+ list << Utils::FileName::fromString(splashScreen).fileName();
emit changed(tag, list);
} else {
diff --git a/src/plugins/qnx/bardescriptoreditorwidget.cpp b/src/plugins/qnx/bardescriptoreditorwidget.cpp
index 5f6f9260c8c..e7b7fc43a87 100644
--- a/src/plugins/qnx/bardescriptoreditorwidget.cpp
+++ b/src/plugins/qnx/bardescriptoreditorwidget.cpp
@@ -171,9 +171,9 @@ void BarDescriptorEditorWidget::initSourcePage()
{
TextDocumentPtr doc(new TextDocument);
doc->setId(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID); // FIXME: This looks odd.
- doc->setIndenter(new TextEditor::NormalIndenter);
+ doc->setIndenter(new NormalIndenter);
- m_xmlSourceWidget = new TextEditor::TextEditorWidget(this);
+ m_xmlSourceWidget = new TextEditorWidget(this);
m_xmlSourceWidget->setTextDocument(doc);
m_xmlSourceWidget->setupAsPlainEditor();
addWidget(m_xmlSourceWidget);
@@ -187,12 +187,12 @@ void BarDescriptorEditorWidget::initPanelSize(ProjectExplorer::PanelsWidget *pan
panelsWidget->widget()->setMinimumWidth(0);
}
-TextEditor::TextEditorWidget *BarDescriptorEditorWidget::sourceWidget() const
+TextEditorWidget *BarDescriptorEditorWidget::sourceWidget() const
{
return m_xmlSourceWidget;
}
-void BarDescriptorEditorWidget::setFilePath(const QString &filePath)
+void BarDescriptorEditorWidget::setFilePath(const Utils::FileName &filePath)
{
Core::IDocument *doc = m_xmlSourceWidget->textDocument();
if (doc)
@@ -211,7 +211,7 @@ void BarDescriptorEditorWidget::updateDocumentContent()
if (!result) {
ProjectExplorer::TaskHub::addTask(ProjectExplorer::Task::Error, errorMsg, Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR,
- Utils::FileName::fromString(barDescriptorDocument()->filePath()), errorLine);
+ Utils::FileName::fromString(barDescriptorDocument()->filePath().toString()), errorLine);
ProjectExplorer::TaskHub::requestPopup();
}
}
diff --git a/src/plugins/qnx/bardescriptoreditorwidget.h b/src/plugins/qnx/bardescriptoreditorwidget.h
index 41938e75486..82784a01377 100644
--- a/src/plugins/qnx/bardescriptoreditorwidget.h
+++ b/src/plugins/qnx/bardescriptoreditorwidget.h
@@ -64,7 +64,7 @@ public:
TextEditor::TextEditorWidget *sourceWidget() const;
- void setFilePath(const QString &filePath);
+ void setFilePath(const Utils::FileName &filePath);
signals:
void changed(BarDescriptorDocument::Tag tag, const QVariant &value);
diff --git a/src/plugins/qnx/bardescriptorfilenode.h b/src/plugins/qnx/bardescriptorfilenode.h
index cc764565f3f..c9501ecab05 100644
--- a/src/plugins/qnx/bardescriptorfilenode.h
+++ b/src/plugins/qnx/bardescriptorfilenode.h
@@ -40,7 +40,6 @@ namespace Internal {
class BarDescriptorFileNode : public ProjectExplorer::FileNode
{
- Q_OBJECT
public:
explicit BarDescriptorFileNode(const QString &filePath);
diff --git a/src/plugins/qnx/bardescriptorfilenodemanager.cpp b/src/plugins/qnx/bardescriptorfilenodemanager.cpp
index de3e36141a4..559d2f566d3 100644
--- a/src/plugins/qnx/bardescriptorfilenodemanager.cpp
+++ b/src/plugins/qnx/bardescriptorfilenodemanager.cpp
@@ -46,7 +46,8 @@
#include <projectexplorer/buildstep.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
+#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <projectexplorer/buildconfiguration.h>
#include <qmakeprojectmanager/qmakenodes.h>
@@ -65,9 +66,10 @@ const char SKIP_BAR_DESCRIPTOR_CREATION_KEY[] = "Qnx.BlackBerry.BarDescriptorFil
BarDescriptorFileNodeManager::BarDescriptorFileNodeManager(QObject *parent)
: QObject(parent)
{
- connect(ProjectExplorer::ProjectExplorerPlugin::instance(),
- SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
- this, SLOT(setCurrentProject(ProjectExplorer::Project*)));
+ connect(ProjectExplorer::ProjectTree::instance(), &ProjectExplorer::ProjectTree::currentProjectChanged,
+ this, &BarDescriptorFileNodeManager::setCurrentProject);
+ connect(ProjectExplorer::SessionManager::instance(), &ProjectExplorer::SessionManager::startupProjectChanged,
+ this, &BarDescriptorFileNodeManager::setCurrentProject);
}
void BarDescriptorFileNodeManager::setCurrentProject(ProjectExplorer::Project *project)
@@ -171,7 +173,7 @@ void BarDescriptorFileNodeManager::updateBarDescriptorNodes(ProjectExplorer::Pro
Core::MessageManager::write(tr("Cannot save bar descriptor file: %1").arg(errorMessage));
continue;
} else {
- oldDocument->setFilePath(package.appDescriptorPath());
+ oldDocument->setFilePath(Utils::FileName::fromString(package.appDescriptorPath()));
if (!oldDocument->reload(&errorMessage, Core::IDocument::FlagReload, Core::IDocument::TypeContents))
Core::MessageManager::write(tr("Cannot reload bar descriptor file: %1").arg(errorMessage));
@@ -194,7 +196,7 @@ bool BarDescriptorFileNodeManager::createBarDescriptor(ProjectExplorer::Project
const QString projectName = QFileInfo(projectNode->path()).completeBaseName();
QmakeProjectManager::QmakeProFileNode *proFileNode =
- qobject_cast<QmakeProjectManager::QmakeProFileNode*>(projectNode);
+ dynamic_cast<QmakeProjectManager::QmakeProFileNode*>(projectNode);
QTC_ASSERT(proFileNode, return false);
const QString targetName = proFileNode->targetInformation().target;
@@ -325,7 +327,7 @@ BarDescriptorFileNode *BarDescriptorFileNodeManager::findBarDescriptorFileNode(P
QList<ProjectExplorer::FileNode*> fileNodes = parent->fileNodes();
foreach (ProjectExplorer::FileNode *fileNode, fileNodes) {
- BarDescriptorFileNode *barDescriptorNode = qobject_cast<BarDescriptorFileNode*>(fileNode);
+ BarDescriptorFileNode *barDescriptorNode = dynamic_cast<BarDescriptorFileNode*>(fileNode);
if (barDescriptorNode)
return barDescriptorNode;
}
diff --git a/src/plugins/qnx/blackberryapilevelconfiguration.cpp b/src/plugins/qnx/blackberryapilevelconfiguration.cpp
index 581f95a2a03..ce8dc79f9b1 100644
--- a/src/plugins/qnx/blackberryapilevelconfiguration.cpp
+++ b/src/plugins/qnx/blackberryapilevelconfiguration.cpp
@@ -88,7 +88,7 @@ BlackBerryApiLevelConfiguration::BlackBerryApiLevelConfiguration(const ConfigIns
// The QNX_TARGET value is using Unix-like separator on all platforms.
m_targetName = ndkInstallInfo.target.split(sep).first().split(QLatin1Char('/')).last();
m_sysRoot = FileName::fromString(ndkInstallInfo.target);
- m_autoDetectionSource = Utils::FileName::fromString(ndkInstallInfo.installationXmlFilePath);
+ m_autoDetectionSource = FileName::fromString(ndkInstallInfo.installationXmlFilePath);
setVersion(QnxVersionNumber(ndkInstallInfo.version));
ctor();
}
@@ -120,7 +120,7 @@ BlackBerryApiLevelConfiguration::BlackBerryApiLevelConfiguration(const QVariantM
m_targetName = data.value(NDKTargetKey).toString().split(sep).first().split(QLatin1Char('/')).last();
m_sysRoot = FileName::fromString(data.value(NDKTargetKey).toString());
if (data.value(QLatin1String(NDKAutoDetectedKey)).toBool())
- m_autoDetectionSource = Utils::FileName::fromString(data.value(NDKAutoDetectionSourceKey).toString());
+ m_autoDetectionSource = FileName::fromString(data.value(NDKAutoDetectionSourceKey).toString());
ctor();
}
@@ -128,8 +128,8 @@ BlackBerryApiLevelConfiguration::BlackBerryApiLevelConfiguration(const QVariantM
void BlackBerryApiLevelConfiguration::ctor()
{
QString host = qnxHost().toString();
- FileName qmake4Path = FileName::fromString(Utils::HostOsInfo::withExecutableSuffix(host + QLatin1String("/usr/bin/qmake")));
- FileName qmake5Path = FileName::fromString(Utils::HostOsInfo::withExecutableSuffix(host + QLatin1String("/usr/bin/qt5/qmake")));
+ FileName qmake4Path = FileName::fromString(HostOsInfo::withExecutableSuffix(host + QLatin1String("/usr/bin/qmake")));
+ FileName qmake5Path = FileName::fromString(HostOsInfo::withExecutableSuffix(host + QLatin1String("/usr/bin/qt5/qmake")));
if (qmake4Path.exists())
m_qmake4BinaryFile = qmake4Path;
@@ -157,7 +157,7 @@ bool BlackBerryApiLevelConfiguration::isAutoDetected() const
return !m_autoDetectionSource.isEmpty();
}
-Utils::FileName BlackBerryApiLevelConfiguration::autoDetectionSource() const
+FileName BlackBerryApiLevelConfiguration::autoDetectionSource() const
{
return m_autoDetectionSource;
}
diff --git a/src/plugins/qnx/blackberryapplicationrunner.cpp b/src/plugins/qnx/blackberryapplicationrunner.cpp
index 79d49398306..883f4bb643a 100644
--- a/src/plugins/qnx/blackberryapplicationrunner.cpp
+++ b/src/plugins/qnx/blackberryapplicationrunner.cpp
@@ -213,10 +213,10 @@ void BlackBerryApplicationRunner::startFinished(int exitCode, QProcess::ExitStat
}
}
-ProjectExplorer::RunControl::StopResult BlackBerryApplicationRunner::stop()
+RunControl::StopResult BlackBerryApplicationRunner::stop()
{
if (m_stopping)
- return ProjectExplorer::RunControl::AsynchronousStop;
+ return RunControl::AsynchronousStop;
m_stopping = true;
@@ -238,7 +238,7 @@ ProjectExplorer::RunControl::StopResult BlackBerryApplicationRunner::stop()
}
m_stopProcess->start(m_deployCmd, args);
- return ProjectExplorer::RunControl::AsynchronousStop;
+ return RunControl::AsynchronousStop;
}
bool BlackBerryApplicationRunner::isRunning() const
diff --git a/src/plugins/qnx/blackberrydebugsupport.cpp b/src/plugins/qnx/blackberrydebugsupport.cpp
index 1246dea2a2c..7f7fdf8a25f 100644
--- a/src/plugins/qnx/blackberrydebugsupport.cpp
+++ b/src/plugins/qnx/blackberrydebugsupport.cpp
@@ -34,7 +34,6 @@
#include "blackberryapplicationrunner.h"
#include <debugger/debuggerruncontrol.h>
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerstartparameters.h>
using namespace Qnx;
@@ -42,18 +41,19 @@ using namespace Qnx::Internal;
BlackBerryDebugSupport::BlackBerryDebugSupport(BlackBerryRunConfiguration *runConfig,
Debugger::DebuggerRunControl *runControl)
- : QObject(runControl->engine())
- , m_engine(runControl->engine())
+ : QObject(runControl)
+ , m_runControl(runControl)
{
BlackBerryApplicationRunner::LaunchFlags launchFlags;
- if (m_engine->startParameters().languages & Debugger::CppLanguage)
+ if (m_runControl->startParameters().languages & Debugger::CppLanguage)
launchFlags |= BlackBerryApplicationRunner::CppDebugLaunch;
- if (m_engine->startParameters().languages & Debugger::QmlLanguage)
+ if (m_runControl->startParameters().languages & Debugger::QmlLanguage)
launchFlags |= BlackBerryApplicationRunner::QmlDebugLaunch;
m_runner = new BlackBerryApplicationRunner(launchFlags, runConfig, this);
- connect(m_engine, SIGNAL(requestRemoteSetup()), this, SLOT(launchRemoteApplication()));
- connect(m_engine, SIGNAL(stateChanged(Debugger::DebuggerState)),
+ connect(m_runControl, &Debugger::DebuggerRunControl::requestRemoteSetup,
+ this, &BlackBerryDebugSupport::launchRemoteApplication);
+ connect(m_runControl, SIGNAL(stateChanged(Debugger::DebuggerState)),
this, SLOT(handleDebuggerStateChanged(Debugger::DebuggerState)));
connect(m_runner, SIGNAL(started()), this, SLOT(handleStarted()));
@@ -72,13 +72,13 @@ void BlackBerryDebugSupport::launchRemoteApplication()
void BlackBerryDebugSupport::handleStarted()
{
- m_engine->startParameters().attachPID = m_runner->pid(); // FIXME: Is that needed?
+ m_runControl->startParameters().attachPID = m_runner->pid(); // FIXME: Is that needed?
Debugger::RemoteSetupResult result;
result.success = true;
result.inferiorPid = m_runner->pid();
result.gdbServerPort = 8000;
result.qmlServerPort = Debugger::InvalidPort;
- m_engine->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
void BlackBerryDebugSupport::handleStartFailed(const QString &message)
@@ -86,7 +86,7 @@ void BlackBerryDebugSupport::handleStartFailed(const QString &message)
Debugger::RemoteSetupResult result;
result.success = false;
result.reason = message;
- m_engine->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
void BlackBerryDebugSupport::handleDebuggerStateChanged(Debugger::DebuggerState state)
@@ -100,5 +100,5 @@ void BlackBerryDebugSupport::handleDebuggerStateChanged(Debugger::DebuggerState
void BlackBerryDebugSupport::handleApplicationOutput(const QString &msg, Utils::OutputFormat format)
{
Q_UNUSED(format)
- m_engine->showMessage(msg, Debugger::AppOutput);
+ m_runControl->showMessage(msg, Debugger::AppOutput);
}
diff --git a/src/plugins/qnx/blackberrydebugsupport.h b/src/plugins/qnx/blackberrydebugsupport.h
index 05b40109f1a..56741039cc6 100644
--- a/src/plugins/qnx/blackberrydebugsupport.h
+++ b/src/plugins/qnx/blackberrydebugsupport.h
@@ -40,10 +40,7 @@
#include <QObject>
#include <QProcess>
-namespace Debugger {
-class DebuggerEngine;
-class DebuggerRunControl;
-}
+namespace Debugger { class DebuggerRunControl; }
namespace Qnx {
namespace Internal {
@@ -73,8 +70,7 @@ private slots:
void handleApplicationOutput(const QString &msg, Utils::OutputFormat format);
private:
- Debugger::DebuggerEngine *m_engine;
-
+ Debugger::DebuggerRunControl *m_runControl;
BlackBerryApplicationRunner *m_runner;
};
diff --git a/src/plugins/qnx/blackberryruncontrolfactory.cpp b/src/plugins/qnx/blackberryruncontrolfactory.cpp
index 84008ddd496..191137d0c93 100644
--- a/src/plugins/qnx/blackberryruncontrolfactory.cpp
+++ b/src/plugins/qnx/blackberryruncontrolfactory.cpp
@@ -55,16 +55,19 @@
#include <analyzerbase/analyzerruncontrol.h>
#include <coreplugin/messagemanager.h>
-using namespace Qnx;
-using namespace Qnx::Internal;
+using namespace Analyzer;
+using namespace Debugger;
+using namespace ProjectExplorer;
+
+namespace Qnx {
+namespace Internal {
BlackBerryRunControlFactory::BlackBerryRunControlFactory(QObject *parent)
- : ProjectExplorer::IRunControlFactory(parent)
+ : IRunControlFactory(parent)
{
}
-bool BlackBerryRunControlFactory::canRun(ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const
+bool BlackBerryRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
Q_UNUSED(mode);
@@ -80,7 +83,7 @@ bool BlackBerryRunControlFactory::canRun(ProjectExplorer::RunConfiguration *runC
// not launch a second instance. Disable the Run button if the application is already
// running on the device.
if (m_activeRunControls.contains(rc->key())) {
- QPointer<ProjectExplorer::RunControl> activeRunControl = m_activeRunControls[rc->key()];
+ QPointer<RunControl> activeRunControl = m_activeRunControls[rc->key()];
if (activeRunControl && activeRunControl.data()->isRunning())
return false;
else
@@ -92,30 +95,76 @@ bool BlackBerryRunControlFactory::canRun(ProjectExplorer::RunConfiguration *runC
return activeDeployConf != 0;
}
-static void createAnalyzerStartParameters(Analyzer::AnalyzerStartParameters *pStartParameters, BlackBerryRunConfiguration* runConfiguration, ProjectExplorer::RunMode mode)
+static void createAnalyzerStartParameters(AnalyzerStartParameters *pStartParameters, BlackBerryRunConfiguration* runConfiguration, RunMode mode)
{
QTC_ASSERT(pStartParameters, return);
pStartParameters->runMode = mode;
- if (mode == ProjectExplorer::QmlProfilerRunMode)
- pStartParameters->startMode = Analyzer::StartLocal;
+ if (mode == QmlProfilerRunMode)
+ pStartParameters->startMode = StartLocal;
- ProjectExplorer::Target *target = runConfiguration->target();
- ProjectExplorer::Kit *kit = target->kit();
+ Target *target = runConfiguration->target();
+ Kit *kit = target->kit();
- ProjectExplorer::IDevice::ConstPtr device = ProjectExplorer::DeviceKitInformation::device(kit);
+ IDevice::ConstPtr device = DeviceKitInformation::device(kit);
if (device) {
pStartParameters->connParams = device->sshParameters();
pStartParameters->analyzerHost = device->qmlProfilerHost();
}
- pStartParameters->sysroot = ProjectExplorer::SysRootKitInformation::sysRoot(kit).toString();
+ pStartParameters->sysroot = SysRootKitInformation::sysRoot(kit).toString();
- Debugger::DebuggerRunConfigurationAspect *aspect = runConfiguration->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
+ DebuggerRunConfigurationAspect *aspect = runConfiguration->extraAspect<DebuggerRunConfigurationAspect>();
if (aspect)
pStartParameters->analyzerPort = aspect->qmlDebugServerPort();
}
-ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode, QString *errorMessage)
+static DebuggerStartParameters startParameters(BlackBerryRunConfiguration *runConfig)
+{
+ DebuggerStartParameters params;
+ Target *target = runConfig->target();
+ Kit *k = target->kit();
+
+ params.startMode = AttachToRemoteServer;
+ params.debuggerCommand = DebuggerKitInformation::debuggerCommand(k).toString();
+ params.sysRoot = SysRootKitInformation::sysRoot(k).toString();
+ params.useCtrlCStub = true;
+ params.runConfiguration = runConfig;
+
+ if (ToolChain *tc = ToolChainKitInformation::toolChain(k))
+ params.toolChainAbi = tc->targetAbi();
+
+ params.executable = runConfig->localExecutableFilePath();
+ params.displayName = runConfig->displayName();
+ params.remoteSetupNeeded = true;
+
+ DebuggerRunConfigurationAspect *aspect = runConfig->extraAspect<DebuggerRunConfigurationAspect>();
+ if (aspect->useQmlDebugger()) {
+ BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(runConfig->target()->kit());
+ if (device) {
+ params.qmlServerAddress = device->sshParameters().host;
+ params.qmlServerPort = aspect->qmlDebugServerPort();
+ params.languages |= QmlLanguage;
+ }
+ }
+ if (aspect->useCppDebugger())
+ params.languages |= CppLanguage;
+
+ if (const Project *project = runConfig->target()->project()) {
+ params.projectSourceDirectory = project->projectDirectory().toString();
+ if (const BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
+ params.projectBuildDirectory = buildConfig->buildDirectory().toString();
+ params.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
+ }
+
+ BlackBerryQtVersion *qtVersion =
+ dynamic_cast<BlackBerryQtVersion *>(QtSupport::QtKitInformation::qtVersion(k));
+ if (qtVersion)
+ params.solibSearchPath = QnxUtils::searchPaths(qtVersion);
+
+ return params;
+}
+
+RunControl *BlackBerryRunControlFactory::create(RunConfiguration *runConfiguration,
+ RunMode mode, QString *errorMessage)
{
BlackBerryRunConfiguration *rc = qobject_cast<BlackBerryRunConfiguration *>(runConfiguration);
if (!rc)
@@ -129,12 +178,12 @@ ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer
return 0;
}
- if (mode == ProjectExplorer::NormalRunMode) {
+ if (mode == NormalRunMode) {
BlackBerryRunControl *runControl = new BlackBerryRunControl(rc);
m_activeRunControls[rc->key()] = runControl;
return runControl;
}
- if (mode == ProjectExplorer::QmlProfilerRunMode) {
+ if (mode == QmlProfilerRunMode) {
QtSupport::BaseQtVersion *qtVer = QtSupport::QtKitInformation::qtVersion(rc->target()->kit());
if (qtVer && qtVer->qtVersion() <= QtSupport::QtVersionNumber(4, 8, 6))
Core::MessageManager::write(tr("Target Qt version (%1) might not support QML profiling. "
@@ -143,10 +192,10 @@ ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer
.arg(qtVer->qtVersionString()), Core::MessageManager::Flash
);
- Analyzer::AnalyzerStartParameters params;
+ AnalyzerStartParameters params;
createAnalyzerStartParameters(&params, rc, mode);
- Analyzer::AnalyzerRunControl *runControl = Analyzer::AnalyzerManager::createRunControl(params, runConfiguration);
+ AnalyzerRunControl *runControl = AnalyzerManager::createRunControl(params, runConfiguration);
BlackBerryApplicationRunner::LaunchFlags launchFlags(BlackBerryApplicationRunner::QmlDebugLaunch
| BlackBerryApplicationRunner::QmlDebugLaunchBlocking
| BlackBerryApplicationRunner::QmlProfilerLaunch);
@@ -160,8 +209,8 @@ ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer
connect(runControl, SIGNAL(finished()), runner, SLOT(stop()));
return runControl;
}
- Debugger::DebuggerRunControl * const runControl =
- Debugger::DebuggerRunControlFactory::doCreate(startParameters(rc), runConfiguration, errorMessage);
+
+ DebuggerRunControl *runControl = DebuggerRunControlFactory::doCreate(startParameters(rc), errorMessage);
if (!runControl)
return 0;
@@ -170,49 +219,5 @@ ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer
return runControl;
}
-Debugger::DebuggerStartParameters BlackBerryRunControlFactory::startParameters(
- const BlackBerryRunConfiguration *runConfig)
-{
- Debugger::DebuggerStartParameters params;
- ProjectExplorer::Target *target = runConfig->target();
- ProjectExplorer::Kit *k = target->kit();
-
- params.startMode = Debugger::AttachToRemoteServer;
- params.debuggerCommand = Debugger::DebuggerKitInformation::debuggerCommand(k).toString();
- params.sysRoot = ProjectExplorer::SysRootKitInformation::sysRoot(k).toString();
- params.useCtrlCStub = true;
-
- if (ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k))
- params.toolChainAbi = tc->targetAbi();
-
- params.executable = runConfig->localExecutableFilePath();
- params.displayName = runConfig->displayName();
- params.remoteSetupNeeded = true;
-
- Debugger::DebuggerRunConfigurationAspect *aspect
- = runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
- if (aspect->useQmlDebugger()) {
- BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(runConfig->target()->kit());
- if (device) {
- params.qmlServerAddress = device->sshParameters().host;
- params.qmlServerPort = aspect->qmlDebugServerPort();
- params.languages |= Debugger::QmlLanguage;
- }
- }
- if (aspect->useCppDebugger())
- params.languages |= Debugger::CppLanguage;
-
- if (const ProjectExplorer::Project *project = runConfig->target()->project()) {
- params.projectSourceDirectory = project->projectDirectory().toString();
- if (const ProjectExplorer::BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
- params.projectBuildDirectory = buildConfig->buildDirectory().toString();
- params.projectSourceFiles = project->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
- }
-
- BlackBerryQtVersion *qtVersion =
- dynamic_cast<BlackBerryQtVersion *>(QtSupport::QtKitInformation::qtVersion(k));
- if (qtVersion)
- params.solibSearchPath = QnxUtils::searchPaths(qtVersion);
-
- return params;
-}
+} // namespace Internal
+} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryruncontrolfactory.h b/src/plugins/qnx/blackberryruncontrolfactory.h
index 082e83cfbc9..04fcdc2b2bf 100644
--- a/src/plugins/qnx/blackberryruncontrolfactory.h
+++ b/src/plugins/qnx/blackberryruncontrolfactory.h
@@ -58,8 +58,6 @@ public:
QString *errorMessage);
private:
- static Debugger::DebuggerStartParameters startParameters( const BlackBerryRunConfiguration *runConfig);
-
mutable QMap<QString, QPointer<ProjectExplorer::RunControl> > m_activeRunControls;
};
diff --git a/src/plugins/qnx/qnxanalyzesupport.cpp b/src/plugins/qnx/qnxanalyzesupport.cpp
index 3c873a1ce38..2c7eb8619f6 100644
--- a/src/plugins/qnx/qnxanalyzesupport.cpp
+++ b/src/plugins/qnx/qnxanalyzesupport.cpp
@@ -43,8 +43,6 @@
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
-#include <QFileInfo>
-
using namespace ProjectExplorer;
using namespace Qnx;
@@ -69,10 +67,10 @@ QnxAnalyzeSupport::QnxAnalyzeSupport(QnxRunConfiguration *runConfig,
connect(&m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
SLOT(remoteIsRunning()));
- ProjectExplorer::IDevice::ConstPtr dev = ProjectExplorer::DeviceKitInformation::device(runConfig->target()->kit());
+ IDevice::ConstPtr dev = DeviceKitInformation::device(runConfig->target()->kit());
QnxDeviceConfiguration::ConstPtr qnxDevice = dev.dynamicCast<const QnxDeviceConfiguration>();
- const QString applicationId = QFileInfo(runConfig->remoteExecutableFilePath()).fileName();
+ const QString applicationId = Utils::FileName::fromString(runConfig->remoteExecutableFilePath()).fileName();
m_slog2Info = new Slog2InfoRunner(applicationId, qnxDevice, this);
connect(m_slog2Info, SIGNAL(output(QString,Utils::OutputFormat)), this, SLOT(showMessage(QString,Utils::OutputFormat)));
connect(runner, SIGNAL(remoteProcessStarted()), m_slog2Info, SLOT(start()));
diff --git a/src/plugins/qnx/qnxattachdebugsupport.cpp b/src/plugins/qnx/qnxattachdebugsupport.cpp
index b54124c901b..d0d2e51f4ac 100644
--- a/src/plugins/qnx/qnxattachdebugsupport.cpp
+++ b/src/plugins/qnx/qnxattachdebugsupport.cpp
@@ -35,7 +35,6 @@
#include "qnxqtversion.h"
#include "qnxutils.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerkitinformation.h>
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerstartparameters.h>
@@ -58,7 +57,7 @@ using namespace Qnx::Internal;
QnxAttachDebugSupport::QnxAttachDebugSupport(QObject *parent)
: QObject(parent)
, m_kit(0)
- , m_engine(0)
+ , m_runControl(0)
, m_pdebugPort(-1)
{
m_runner = new ProjectExplorer::DeviceApplicationRunner(this);
@@ -133,14 +132,14 @@ void QnxAttachDebugSupport::attachToProcess()
sp.solibSearchPath = QnxUtils::searchPaths(qtVersion);
QString errorMessage;
- Debugger::DebuggerRunControl * const runControl = Debugger::DebuggerRunControlFactory::doCreate(sp, 0, &errorMessage);
+ Debugger::DebuggerRunControl * const runControl = Debugger::DebuggerRunControlFactory::doCreate(sp, &errorMessage);
if (!errorMessage.isEmpty()) {
handleError(errorMessage);
stopPDebug();
return;
}
- m_engine = runControl->engine();
- connect(m_engine, SIGNAL(stateChanged(Debugger::DebuggerState)), this, SLOT(handleDebuggerStateChanged(Debugger::DebuggerState)));
+ connect(runControl, &Debugger::DebuggerRunControl::stateChanged,
+ this, &QnxAttachDebugSupport::handleDebuggerStateChanged);
ProjectExplorer::ProjectExplorerPlugin::startRunControl(runControl, ProjectExplorer::DebugRunMode);
}
@@ -152,20 +151,20 @@ void QnxAttachDebugSupport::handleDebuggerStateChanged(Debugger::DebuggerState s
void QnxAttachDebugSupport::handleError(const QString &message)
{
- if (m_engine)
- m_engine->showMessage(message, Debugger::AppError);
+ if (m_runControl)
+ m_runControl->showMessage(message, Debugger::AppError);
}
void QnxAttachDebugSupport::handleProgressReport(const QString &message)
{
- if (m_engine)
- m_engine->showMessage(message + QLatin1Char('\n'), Debugger::AppStuff);
+ if (m_runControl)
+ m_runControl->showMessage(message + QLatin1Char('\n'), Debugger::AppStuff);
}
void QnxAttachDebugSupport::handleRemoteOutput(const QByteArray &output)
{
- if (m_engine)
- m_engine->showMessage(QString::fromUtf8(output), Debugger::AppOutput);
+ if (m_runControl)
+ m_runControl->showMessage(QString::fromUtf8(output), Debugger::AppOutput);
}
void QnxAttachDebugSupport::stopPDebug()
diff --git a/src/plugins/qnx/qnxattachdebugsupport.h b/src/plugins/qnx/qnxattachdebugsupport.h
index 382e8fcf5e7..a012f8fd8e0 100644
--- a/src/plugins/qnx/qnxattachdebugsupport.h
+++ b/src/plugins/qnx/qnxattachdebugsupport.h
@@ -37,9 +37,7 @@
#include <QObject>
-namespace Debugger {
-class DebuggerEngine;
-}
+namespace Debugger { class DebuggerRunControl; }
namespace ProjectExplorer {
class DeviceApplicationRunner;
@@ -77,7 +75,7 @@ private:
ProjectExplorer::DeviceApplicationRunner *m_runner;
ProjectExplorer::DeviceUsedPortsGatherer *m_portsGatherer;
- Debugger::DebuggerEngine *m_engine;
+ Debugger::DebuggerRunControl *m_runControl;
int m_pdebugPort;
QString m_projectSourceDirectory;
diff --git a/src/plugins/qnx/qnxbaseconfiguration.cpp b/src/plugins/qnx/qnxbaseconfiguration.cpp
index bbb5c05acac..34055d0683a 100644
--- a/src/plugins/qnx/qnxbaseconfiguration.cpp
+++ b/src/plugins/qnx/qnxbaseconfiguration.cpp
@@ -79,32 +79,32 @@ QnxBaseConfiguration::~QnxBaseConfiguration()
{
}
-Utils::FileName QnxBaseConfiguration::envFile() const
+FileName QnxBaseConfiguration::envFile() const
{
return m_envFile;
}
-Utils::FileName QnxBaseConfiguration::qnxTarget() const
+FileName QnxBaseConfiguration::qnxTarget() const
{
return m_qnxTarget;
}
-Utils::FileName QnxBaseConfiguration::qnxHost() const
+FileName QnxBaseConfiguration::qnxHost() const
{
return m_qnxHost;
}
-Utils::FileName QnxBaseConfiguration::qccCompilerPath() const
+FileName QnxBaseConfiguration::qccCompilerPath() const
{
return m_qccCompiler;
}
-Utils::FileName QnxBaseConfiguration::armDebuggerPath() const
+FileName QnxBaseConfiguration::armDebuggerPath() const
{
return m_armlev7Debugger;
}
-Utils::FileName QnxBaseConfiguration::x86DebuggerPath() const
+FileName QnxBaseConfiguration::x86DebuggerPath() const
{
return m_x86Debugger;
}
@@ -142,24 +142,24 @@ void QnxBaseConfiguration::ctor(const FileName &envScript)
#endif
m_envFile = envScript;
m_qnxEnv = QnxUtils::qnxEnvironmentFromEnvFile(m_envFile.toString());
- foreach (const Utils::EnvironmentItem &item, m_qnxEnv) {
+ foreach (const EnvironmentItem &item, m_qnxEnv) {
if (item.name == QLatin1String("QNX_TARGET"))
- m_qnxTarget = Utils::FileName::fromString(item.value);
+ m_qnxTarget = FileName::fromString(item.value);
else if (item.name == QLatin1String("QNX_HOST"))
- m_qnxHost = Utils::FileName::fromString(item.value);
+ m_qnxHost = FileName::fromString(item.value);
}
- FileName qccPath = FileName::fromString(Utils::HostOsInfo::withExecutableSuffix(
+ FileName qccPath = FileName::fromString(HostOsInfo::withExecutableSuffix(
m_qnxHost.toString() + QLatin1String("/usr/bin/qcc")));
- FileName armlev7GdbPath = FileName::fromString(Utils::HostOsInfo::withExecutableSuffix(
+ FileName armlev7GdbPath = FileName::fromString(HostOsInfo::withExecutableSuffix(
m_qnxHost.toString() + QLatin1String("/usr/bin/ntoarm-gdb")));
if (!armlev7GdbPath.exists()) {
- armlev7GdbPath = FileName::fromString(Utils::HostOsInfo::withExecutableSuffix(
+ armlev7GdbPath = FileName::fromString(HostOsInfo::withExecutableSuffix(
m_qnxHost.toString() + QLatin1String("/usr/bin/ntoarmv7-gdb")));
}
- FileName x86GdbPath = FileName::fromString(Utils::HostOsInfo::withExecutableSuffix(
+ FileName x86GdbPath = FileName::fromString(HostOsInfo::withExecutableSuffix(
m_qnxHost.toString() + QLatin1String("/usr/bin/ntox86-gdb")));
if (qccPath.exists())
@@ -175,7 +175,7 @@ void QnxBaseConfiguration::ctor(const FileName &envScript)
QVariant QnxBaseConfiguration::createDebuggerItem(QnxArchitecture arch,
const QString &displayName)
{
- Utils::FileName command = (arch == X86) ? x86DebuggerPath() : armDebuggerPath();
+ FileName command = (arch == X86) ? x86DebuggerPath() : armDebuggerPath();
Debugger::DebuggerItem debugger;
debugger.setCommand(command);
debugger.setEngineType(Debugger::GdbEngineType);
@@ -190,13 +190,13 @@ QnxToolChain *QnxBaseConfiguration::createToolChain(QnxArchitecture arch,
const QString &displayName,
const QString &ndkPath)
{
- QnxToolChain *toolChain = new QnxToolChain(ProjectExplorer::ToolChain::AutoDetection);
+ QnxToolChain *toolChain = new QnxToolChain(ToolChain::AutoDetection);
toolChain->resetToolChain(m_qccCompiler);
toolChain->setTargetAbi(Abi((arch == Qnx::ArmLeV7) ? Abi::ArmArchitecture : Abi::X86Architecture,
Abi::LinuxOS, Abi::GenericLinuxFlavor, Abi::ElfFormat, 32));
toolChain->setDisplayName(displayName);
toolChain->setNdkPath(ndkPath);
- ProjectExplorer::ToolChainManager::registerToolChain(toolChain);
+ ToolChainManager::registerToolChain(toolChain);
return toolChain;
}
diff --git a/src/plugins/qnx/qnxconfiguration.cpp b/src/plugins/qnx/qnxconfiguration.cpp
index 678ac61b0cb..775db6b15db 100644
--- a/src/plugins/qnx/qnxconfiguration.cpp
+++ b/src/plugins/qnx/qnxconfiguration.cpp
@@ -61,7 +61,7 @@ using namespace Debugger;
namespace Qnx {
namespace Internal {
-QnxConfiguration::QnxConfiguration(const Utils::FileName &sdpEnvFile)
+QnxConfiguration::QnxConfiguration(const FileName &sdpEnvFile)
: QnxBaseConfiguration(sdpEnvFile)
{
readInformation();
@@ -120,16 +120,16 @@ void QnxConfiguration::deactivate()
if (!isActive())
return;
- QList<ProjectExplorer::ToolChain *> toolChainsToRemove;
- QList<Debugger::DebuggerItem> debuggersToRemove;
- foreach (ProjectExplorer::ToolChain *tc,
- ProjectExplorer::ToolChainManager::toolChains()) {
+ QList<ToolChain *> toolChainsToRemove;
+ QList<DebuggerItem> debuggersToRemove;
+ foreach (ToolChain *tc,
+ ToolChainManager::toolChains()) {
if (tc->compilerCommand() == qccCompilerPath())
toolChainsToRemove.append(tc);
}
- foreach (Debugger::DebuggerItem debuggerItem,
- Debugger::DebuggerItemManager::debuggers()) {
+ foreach (DebuggerItem debuggerItem,
+ DebuggerItemManager::debuggers()) {
if (debuggerItem.command() == armDebuggerPath() ||
debuggerItem.command() == x86DebuggerPath())
debuggersToRemove.append(debuggerItem);
@@ -142,11 +142,11 @@ void QnxConfiguration::deactivate()
KitManager::deregisterKit(kit);
}
- foreach (ProjectExplorer::ToolChain *tc, toolChainsToRemove)
- ProjectExplorer::ToolChainManager::deregisterToolChain(tc);
+ foreach (ToolChain *tc, toolChainsToRemove)
+ ToolChainManager::deregisterToolChain(tc);
- foreach (Debugger::DebuggerItem debuggerItem, debuggersToRemove)
- Debugger::DebuggerItemManager::
+ foreach (DebuggerItem debuggerItem, debuggersToRemove)
+ DebuggerItemManager::
deregisterDebugger(debuggerItem.id());
}
@@ -154,16 +154,16 @@ bool QnxConfiguration::isActive() const
{
bool hasToolChain = false;
bool hasDebugger = false;
- foreach (ProjectExplorer::ToolChain *tc,
- ProjectExplorer::ToolChainManager::toolChains()) {
+ foreach (ToolChain *tc,
+ ToolChainManager::toolChains()) {
if (tc->compilerCommand() == qccCompilerPath()) {
hasToolChain = true;
break;
}
}
- foreach (Debugger::DebuggerItem debuggerItem,
- Debugger::DebuggerItemManager::debuggers()) {
+ foreach (DebuggerItem debuggerItem,
+ DebuggerItemManager::debuggers()) {
if (debuggerItem.command() == armDebuggerPath() ||
debuggerItem.command() == x86DebuggerPath()) {
hasDebugger = true;
@@ -179,7 +179,7 @@ bool QnxConfiguration::canCreateKits() const
return isValid() && (qnxQtVersion(ArmLeV7) || qnxQtVersion(X86));
}
-Utils::FileName QnxConfiguration::sdpPath() const
+FileName QnxConfiguration::sdpPath() const
{
return envFile().parentDir();
}
@@ -200,7 +200,7 @@ QnxQtVersion* QnxConfiguration::qnxQtVersion(QnxArchitecture arch) const
return 0;
}
-ProjectExplorer::Kit *QnxConfiguration::createKit(QnxArchitecture arch,
+Kit *QnxConfiguration::createKit(QnxArchitecture arch,
QnxToolChain *toolChain,
const QVariant &debuggerItemId,
const QString &displayName)
@@ -210,7 +210,7 @@ ProjectExplorer::Kit *QnxConfiguration::createKit(QnxArchitecture arch,
if (!qnxQt)
return 0;
- Kit *kit = new ProjectExplorer::Kit;
+ Kit *kit = new Kit;
QtKitInformation::setQtVersion(kit, qnxQt);
ToolChainKitInformation::setToolChain(kit, toolChain);
diff --git a/src/plugins/qnx/qnxdebugsupport.cpp b/src/plugins/qnx/qnxdebugsupport.cpp
index abf18cab80d..1ed7b39448c 100644
--- a/src/plugins/qnx/qnxdebugsupport.cpp
+++ b/src/plugins/qnx/qnxdebugsupport.cpp
@@ -36,7 +36,6 @@
#include "qnxrunconfiguration.h"
#include "slog2inforunner.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerrunconfigurationaspect.h>
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerstartparameters.h>
@@ -47,17 +46,15 @@
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
-#include <QFileInfo>
-
using namespace ProjectExplorer;
using namespace RemoteLinux;
using namespace Qnx;
using namespace Qnx::Internal;
-QnxDebugSupport::QnxDebugSupport(QnxRunConfiguration *runConfig, Debugger::DebuggerEngine *engine)
- : QnxAbstractRunSupport(runConfig, engine)
- , m_engine(engine)
+QnxDebugSupport::QnxDebugSupport(QnxRunConfiguration *runConfig, Debugger::DebuggerRunControl *runControl)
+ : QnxAbstractRunSupport(runConfig, runControl)
+ , m_runControl(runControl)
, m_pdebugPort(-1)
, m_qmlPort(-1)
, m_useCppDebugger(runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useCppDebugger())
@@ -71,10 +68,11 @@ QnxDebugSupport::QnxDebugSupport(QnxRunConfiguration *runConfig, Debugger::Debug
connect(runner, SIGNAL(remoteStdout(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
connect(runner, SIGNAL(remoteStderr(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
- connect(m_engine, SIGNAL(requestRemoteSetup()), this, SLOT(handleAdapterSetupRequested()));
+ connect(m_runControl, &Debugger::DebuggerRunControl::requestRemoteSetup,
+ this, &QnxDebugSupport::handleAdapterSetupRequested);
- const QString applicationId = QFileInfo(runConfig->remoteExecutableFilePath()).fileName();
- ProjectExplorer::IDevice::ConstPtr dev = ProjectExplorer::DeviceKitInformation::device(runConfig->target()->kit());
+ const QString applicationId = Utils::FileName::fromString(runConfig->remoteExecutableFilePath()).fileName();
+ IDevice::ConstPtr dev = DeviceKitInformation::device(runConfig->target()->kit());
QnxDeviceConfiguration::ConstPtr qnxDevice = dev.dynamicCast<const QnxDeviceConfiguration>();
m_slog2Info = new Slog2InfoRunner(applicationId, qnxDevice, this);
@@ -88,8 +86,8 @@ void QnxDebugSupport::handleAdapterSetupRequested()
{
QTC_ASSERT(state() == Inactive, return);
- if (m_engine)
- m_engine->showMessage(tr("Preparing remote side...") + QLatin1Char('\n'), Debugger::AppStuff);
+ if (m_runControl)
+ m_runControl->showMessage(tr("Preparing remote side...") + QLatin1Char('\n'), Debugger::AppStuff);
QnxAbstractRunSupport::handleAdapterSetupRequested();
}
@@ -106,13 +104,13 @@ void QnxDebugSupport::startExecution()
setState(StartingRemoteProcess);
if (m_useQmlDebugger)
- m_engine->startParameters().processArgs += QString::fromLatin1(" -qmljsdebugger=port:%1,block").arg(m_qmlPort);
+ m_runControl->startParameters().processArgs += QString::fromLatin1(" -qmljsdebugger=port:%1,block").arg(m_qmlPort);
QStringList arguments;
if (m_useCppDebugger)
arguments << QString::number(m_pdebugPort);
else if (m_useQmlDebugger && !m_useCppDebugger)
- arguments = Utils::QtcProcess::splitArgs(m_engine->startParameters().processArgs);
+ arguments = Utils::QtcProcess::splitArgs(m_runControl->startParameters().processArgs);
appRunner()->setEnvironment(environment());
appRunner()->setWorkingDirectory(workingDirectory());
appRunner()->start(device(), executable(), arguments);
@@ -121,29 +119,29 @@ void QnxDebugSupport::startExecution()
void QnxDebugSupport::handleRemoteProcessStarted()
{
QnxAbstractRunSupport::handleRemoteProcessStarted();
- if (m_engine) {
+ if (m_runControl) {
Debugger::RemoteSetupResult result;
result.success = true;
result.gdbServerPort = m_pdebugPort;
result.qmlServerPort = m_qmlPort;
- m_engine->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
}
void QnxDebugSupport::handleRemoteProcessFinished(bool success)
{
- if (m_engine || state() == Inactive)
+ if (m_runControl || state() == Inactive)
return;
if (state() == Running) {
if (!success)
- m_engine->notifyInferiorIll();
+ m_runControl->notifyInferiorIll();
} else {
Debugger::RemoteSetupResult result;
result.success = false;
result.reason = tr("The %1 process closed unexpectedly.").arg(executable());
- m_engine->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
}
@@ -169,45 +167,45 @@ void QnxDebugSupport::killInferiorProcess()
void QnxDebugSupport::handleProgressReport(const QString &progressOutput)
{
- if (m_engine)
- m_engine->showMessage(progressOutput + QLatin1Char('\n'), Debugger::AppStuff);
+ if (m_runControl)
+ m_runControl->showMessage(progressOutput + QLatin1Char('\n'), Debugger::AppStuff);
}
void QnxDebugSupport::handleRemoteOutput(const QByteArray &output)
{
QTC_ASSERT(state() == Inactive || state() == Running, return);
- if (m_engine)
- m_engine->showMessage(QString::fromUtf8(output), Debugger::AppOutput);
+ if (m_runControl)
+ m_runControl->showMessage(QString::fromUtf8(output), Debugger::AppOutput);
}
void QnxDebugSupport::handleError(const QString &error)
{
if (state() == Running) {
- if (m_engine) {
- m_engine->showMessage(error, Debugger::AppError);
- m_engine->notifyInferiorIll();
+ if (m_runControl) {
+ m_runControl->showMessage(error, Debugger::AppError);
+ m_runControl->notifyInferiorIll();
}
} else if (state() != Inactive) {
setFinished();
- if (m_engine) {
+ if (m_runControl) {
Debugger::RemoteSetupResult result;
result.success = false;
result.reason = tr("Initial setup failed: %1").arg(error);
- m_engine->notifyEngineRemoteSetupFinished(result);
+ m_runControl->notifyEngineRemoteSetupFinished(result);
}
}
}
void QnxDebugSupport::printMissingWarning()
{
- if (m_engine)
- m_engine->showMessage(tr("Warning: \"slog2info\" is not found on the device, debug output not available."), Debugger::AppError);
+ if (m_runControl)
+ m_runControl->showMessage(tr("Warning: \"slog2info\" is not found on the device, debug output not available."), Debugger::AppError);
}
void QnxDebugSupport::handleApplicationOutput(const QString &msg, Utils::OutputFormat outputFormat)
{
Q_UNUSED(outputFormat);
- if (m_engine)
- m_engine->showMessage(msg, Debugger::AppOutput);
+ if (m_runControl)
+ m_runControl->showMessage(msg, Debugger::AppOutput);
}
diff --git a/src/plugins/qnx/qnxdebugsupport.h b/src/plugins/qnx/qnxdebugsupport.h
index f1c64e4afe8..834f00629b9 100644
--- a/src/plugins/qnx/qnxdebugsupport.h
+++ b/src/plugins/qnx/qnxdebugsupport.h
@@ -37,7 +37,7 @@
#include <utils/outputformat.h>
-namespace Debugger { class DebuggerEngine; }
+namespace Debugger { class DebuggerRunControl; }
namespace Qnx {
namespace Internal {
@@ -48,9 +48,10 @@ class Slog2InfoRunner;
class QnxDebugSupport : public QnxAbstractRunSupport
{
Q_OBJECT
+
public:
- explicit QnxDebugSupport(QnxRunConfiguration *runConfig,
- Debugger::DebuggerEngine *engine);
+ QnxDebugSupport(QnxRunConfiguration *runConfig,
+ Debugger::DebuggerRunControl *runControl);
public slots:
void handleDebuggingFinished();
@@ -76,7 +77,7 @@ private:
Slog2InfoRunner *m_slog2Info;
- Debugger::DebuggerEngine *m_engine;
+ Debugger::DebuggerRunControl *m_runControl;
int m_pdebugPort;
int m_qmlPort;
diff --git a/src/plugins/qnx/qnxdeployconfigurationfactory.h b/src/plugins/qnx/qnxdeployconfigurationfactory.h
index 9716324a6bb..444650293f7 100644
--- a/src/plugins/qnx/qnxdeployconfigurationfactory.h
+++ b/src/plugins/qnx/qnxdeployconfigurationfactory.h
@@ -58,7 +58,7 @@ public:
ProjectExplorer::DeployConfiguration *source) const;
ProjectExplorer::DeployConfiguration *clone(ProjectExplorer::Target *parent,
ProjectExplorer::DeployConfiguration *source);
-
+private:
bool canHandle(ProjectExplorer::Target *t) const;
};
diff --git a/src/plugins/qnx/qnxdeviceconfiguration.cpp b/src/plugins/qnx/qnxdeviceconfiguration.cpp
index 004ba096165..2b518dd8fe2 100644
--- a/src/plugins/qnx/qnxdeviceconfiguration.cpp
+++ b/src/plugins/qnx/qnxdeviceconfiguration.cpp
@@ -95,7 +95,7 @@ void QnxDeviceProcess::doSignal(int sig)
}
-class QnxPortsGatheringMethod : public ProjectExplorer::PortsGatheringMethod
+class QnxPortsGatheringMethod : public PortsGatheringMethod
{
// TODO: The command is probably needlessly complicated because the parsing method
// used to be fixed. These two can now be matched to each other.
@@ -177,7 +177,7 @@ int QnxDeviceConfiguration::qnxVersion() const
void QnxDeviceConfiguration::updateVersionNumber() const
{
QEventLoop eventLoop;
- ProjectExplorer::SshDeviceProcess versionNumberProcess(sharedFromThis());
+ SshDeviceProcess versionNumberProcess(sharedFromThis());
QObject::connect(&versionNumberProcess, SIGNAL(finished()), &eventLoop, SLOT(quit()));
QObject::connect(&versionNumberProcess, SIGNAL(error(QProcess::ProcessError)), &eventLoop, SLOT(quit()));
@@ -218,27 +218,27 @@ QVariantMap QnxDeviceConfiguration::toMap() const
return map;
}
-ProjectExplorer::IDevice::Ptr QnxDeviceConfiguration::clone() const
+IDevice::Ptr QnxDeviceConfiguration::clone() const
{
return Ptr(new QnxDeviceConfiguration(*this));
}
-ProjectExplorer::PortsGatheringMethod::Ptr QnxDeviceConfiguration::portsGatheringMethod() const
+PortsGatheringMethod::Ptr QnxDeviceConfiguration::portsGatheringMethod() const
{
- return ProjectExplorer::PortsGatheringMethod::Ptr(new QnxPortsGatheringMethod);
+ return PortsGatheringMethod::Ptr(new QnxPortsGatheringMethod);
}
-ProjectExplorer::DeviceProcessList *QnxDeviceConfiguration::createProcessListModel(QObject *parent) const
+DeviceProcessList *QnxDeviceConfiguration::createProcessListModel(QObject *parent) const
{
return new QnxDeviceProcessList(sharedFromThis(), parent);
}
-ProjectExplorer::DeviceTester *QnxDeviceConfiguration::createDeviceTester() const
+DeviceTester *QnxDeviceConfiguration::createDeviceTester() const
{
return new QnxDeviceTester;
}
-ProjectExplorer::DeviceProcess *QnxDeviceConfiguration::createProcess(QObject *parent) const
+DeviceProcess *QnxDeviceConfiguration::createProcess(QObject *parent) const
{
return new QnxDeviceProcess(sharedFromThis(), parent);
}
@@ -270,9 +270,9 @@ void QnxDeviceConfiguration::executeAction(Core::Id actionId, QWidget *parent)
}
}
-ProjectExplorer::DeviceProcessSignalOperation::Ptr QnxDeviceConfiguration::signalOperation() const
+DeviceProcessSignalOperation::Ptr QnxDeviceConfiguration::signalOperation() const
{
- return ProjectExplorer::DeviceProcessSignalOperation::Ptr(
+ return DeviceProcessSignalOperation::Ptr(
new QnxDeviceProcessSignalOperation(sshParameters()));
}
diff --git a/src/plugins/qnx/qnxplugin.cpp b/src/plugins/qnx/qnxplugin.cpp
index 15bc057cf25..10caf0d2c40 100644
--- a/src/plugins/qnx/qnxplugin.cpp
+++ b/src/plugins/qnx/qnxplugin.cpp
@@ -143,7 +143,7 @@ bool QnxPlugin::initialize(const QStringList &arguments, QString *errorString)
}
addAutoReleasedObject(new BarDescriptorEditorFactory);
- connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsLoaded()),
+ connect(KitManager::instance(), SIGNAL(kitsLoaded()),
BlackBerryConfigurationManager::instance(), SLOT(loadSettings()));
return true;
@@ -151,8 +151,7 @@ bool QnxPlugin::initialize(const QStringList &arguments, QString *errorString)
void QnxPlugin::extensionsInitialized()
{
- ProjectExplorer::TaskHub::addCategory(Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR,
- tr("BAR Descriptor"));
+ TaskHub::addCategory(Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR, tr("BAR Descriptor"));
// Debug support
QnxAttachDebugSupport *debugSupport = new QnxAttachDebugSupport(this);
@@ -169,7 +168,7 @@ void QnxPlugin::extensionsInitialized()
Core::Command *cmd = Core::ActionManager::registerAction(m_attachToQnxApplication, "Debugger.AttachToQnxApplication", globalcontext);
mstart->addAction(cmd, Constants::QNX_DEBUGGING_GROUP);
- connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsChanged()), this, SLOT(updateDebuggerActions()));
+ connect(KitManager::instance(), SIGNAL(kitsChanged()), this, SLOT(updateDebuggerActions()));
}
ExtensionSystem::IPlugin::ShutdownFlag QnxPlugin::aboutToShutdown()
diff --git a/src/plugins/qnx/qnxruncontrol.cpp b/src/plugins/qnx/qnxruncontrol.cpp
index 9d6e2480a09..9e052bca4b9 100644
--- a/src/plugins/qnx/qnxruncontrol.cpp
+++ b/src/plugins/qnx/qnxruncontrol.cpp
@@ -39,8 +39,6 @@
#include <projectexplorer/runconfiguration.h>
#include <projectexplorer/target.h>
-#include <QFileInfo>
-
using namespace Qnx;
using namespace Qnx::Internal;
using namespace RemoteLinux;
@@ -55,7 +53,7 @@ QnxRunControl::QnxRunControl(ProjectExplorer::RunConfiguration *runConfig)
QnxRunConfiguration *qnxRunConfig = qobject_cast<QnxRunConfiguration *>(runConfig);
QTC_CHECK(qnxRunConfig);
- const QString applicationId = QFileInfo(qnxRunConfig->remoteExecutableFilePath()).fileName();
+ const QString applicationId = Utils::FileName::fromString(qnxRunConfig->remoteExecutableFilePath()).fileName();
m_slog2Info = new Slog2InfoRunner(applicationId, qnxDevice, this);
connect(m_slog2Info, SIGNAL(output(QString,Utils::OutputFormat)), this, SLOT(appendMessage(QString,Utils::OutputFormat)));
connect(this, SIGNAL(started()), m_slog2Info, SLOT(start()));
diff --git a/src/plugins/qnx/qnxruncontrolfactory.cpp b/src/plugins/qnx/qnxruncontrolfactory.cpp
index 0c01a73d928..dd52cc799b4 100644
--- a/src/plugins/qnx/qnxruncontrolfactory.cpp
+++ b/src/plugins/qnx/qnxruncontrolfactory.cpp
@@ -40,7 +40,6 @@
#include "qnxutils.h"
#include "qnxdeviceconfiguration.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerrunconfigurationaspect.h>
#include <debugger/debuggerstartparameters.h>
@@ -63,7 +62,7 @@ using namespace ProjectExplorer;
using namespace Qnx;
using namespace Qnx::Internal;
-static DebuggerStartParameters createDebuggerStartParameters(const QnxRunConfiguration *runConfig)
+static DebuggerStartParameters createDebuggerStartParameters(QnxRunConfiguration *runConfig)
{
DebuggerStartParameters params;
Target *target = runConfig->target();
@@ -77,6 +76,7 @@ static DebuggerStartParameters createDebuggerStartParameters(const QnxRunConfigu
params.debuggerCommand = DebuggerKitInformation::debuggerCommand(k).toString();
params.sysRoot = SysRootKitInformation::sysRoot(k).toString();
params.useCtrlCStub = true;
+ params.runConfiguration = runConfig;
if (ToolChain *tc = ToolChainKitInformation::toolChain(k))
params.toolChainAbi = tc->targetAbi();
@@ -89,8 +89,8 @@ static DebuggerStartParameters createDebuggerStartParameters(const QnxRunConfigu
params.closeMode = KillAtClose;
params.processArgs = runConfig->arguments().join(QLatin1Char(' '));
- Debugger::DebuggerRunConfigurationAspect *aspect
- = runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
+ DebuggerRunConfigurationAspect *aspect
+ = runConfig->extraAspect<DebuggerRunConfigurationAspect>();
if (aspect->useQmlDebugger()) {
params.languages |= QmlLanguage;
params.qmlServerAddress = device->sshParameters().host;
@@ -98,13 +98,13 @@ static DebuggerStartParameters createDebuggerStartParameters(const QnxRunConfigu
}
if (aspect->useCppDebugger())
- params.languages |= Debugger::CppLanguage;
+ params.languages |= CppLanguage;
- if (const ProjectExplorer::Project *project = runConfig->target()->project()) {
+ if (const Project *project = runConfig->target()->project()) {
params.projectSourceDirectory = project->projectDirectory().toString();
- if (const ProjectExplorer::BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
+ if (const BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
params.projectBuildDirectory = buildConfig->buildDirectory().toString();
- params.projectSourceFiles = project->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
+ params.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
}
QnxQtVersion *qtVersion =
@@ -180,11 +180,11 @@ RunControl *QnxRunControlFactory::create(RunConfiguration *runConfig, RunMode mo
return new QnxRunControl(rc);
case DebugRunMode: {
const DebuggerStartParameters params = createDebuggerStartParameters(rc);
- DebuggerRunControl * const runControl = DebuggerRunControlFactory::doCreate(params, rc, errorMessage);
+ DebuggerRunControl * const runControl = DebuggerRunControlFactory::doCreate(params, errorMessage);
if (!runControl)
return 0;
- QnxDebugSupport *debugSupport = new QnxDebugSupport(rc, runControl->engine());
+ QnxDebugSupport *debugSupport = new QnxDebugSupport(rc, runControl);
connect(runControl, SIGNAL(finished()), debugSupport, SLOT(handleDebuggingFinished()));
return runControl;
@@ -199,6 +199,7 @@ RunControl *QnxRunControlFactory::create(RunConfiguration *runConfig, RunMode mo
case NoRunMode:
case CallgrindRunMode:
case MemcheckRunMode:
+ case MemcheckWithGdbRunMode:
case ClangStaticAnalyzerMode:
case DebugRunModeWithBreakOnMain:
QTC_ASSERT(false, return 0);
diff --git a/src/plugins/qnx/qnxsettingswidget.ui b/src/plugins/qnx/qnxsettingswidget.ui
index 5e46069d0a0..09ae05cdd04 100644
--- a/src/plugins/qnx/qnxsettingswidget.ui
+++ b/src/plugins/qnx/qnxsettingswidget.ui
@@ -156,7 +156,7 @@
<item>
<widget class="QPushButton" name="addButton">
<property name="text">
- <string>Add</string>
+ <string>Add...</string>
</property>
</widget>
</item>
diff --git a/src/plugins/qnx/qnxutils.cpp b/src/plugins/qnx/qnxutils.cpp
index a816bfad6b8..3472f8ec959 100644
--- a/src/plugins/qnx/qnxutils.cpp
+++ b/src/plugins/qnx/qnxutils.cpp
@@ -58,14 +58,14 @@ QString QnxUtils::addQuotes(const QString &string)
return QLatin1Char('"') + string + QLatin1Char('"');
}
-Qnx::QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir)
+QnxArchitecture QnxUtils::cpudirToArch(const QString &cpuDir)
{
if (cpuDir == QLatin1String("x86"))
- return Qnx::X86;
+ return X86;
else if (cpuDir == QLatin1String("armle-v7"))
- return Qnx::ArmLeV7;
+ return ArmLeV7;
else
- return Qnx::UnknownArch;
+ return UnknownArch;
}
QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion)
@@ -100,7 +100,7 @@ QList<Utils::EnvironmentItem> QnxUtils::qnxEnvironmentFromEnvFile(const QString
// locking creating bbndk-env file wrapper script
QTemporaryFile tmpFile(
- QDir::tempPath() + QDir::separator()
+ QDir::tempPath() + QLatin1Char('/')
+ QLatin1String("bbndk-env-eval-XXXXXX") + QLatin1String(isWindows ? ".bat" : ".sh"));
if (!tmpFile.open())
return items;
diff --git a/src/plugins/qtsupport/baseqtversion.cpp b/src/plugins/qtsupport/baseqtversion.cpp
index 63799cf01f7..f7ab0230d05 100644
--- a/src/plugins/qtsupport/baseqtversion.cpp
+++ b/src/plugins/qtsupport/baseqtversion.cpp
@@ -1570,7 +1570,8 @@ bool BaseQtVersion::isQtQuickCompilerSupported(QString *reason) const
const QString qtQuickCompilerExecutable =
HostOsInfo::withExecutableSuffix(binPath().toString() + QLatin1String("/qtquickcompiler"));
if (!QFileInfo::exists(qtQuickCompilerExecutable)) {
- // TODO: Add reason string in master
+ if (reason)
+ *reason = QCoreApplication::translate("BaseQtVersion", "This Qt Version does not contain Qt Quick Compiler.");
return false;
}
diff --git a/src/plugins/qtsupport/gettingstartedwelcomepage.cpp b/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
index 745dc69ccb6..7a6ab92ff68 100644
--- a/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
+++ b/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
@@ -275,9 +275,9 @@ void ExamplesWelcomePage::facilitateQml(QQmlEngine *engine)
rootContenxt->setContextProperty(QLatin1String("gettingStarted"), this);
}
-ExamplesWelcomePage::Id ExamplesWelcomePage::id() const
+Core::Id ExamplesWelcomePage::id() const
{
- return m_showExamples ? Examples : Tutorials;
+ return m_showExamples ? "Examples" : "Tutorials";
}
void ExamplesWelcomePage::openHelpInExtraWindow(const QUrl &help)
diff --git a/src/plugins/qtsupport/gettingstartedwelcomepage.h b/src/plugins/qtsupport/gettingstartedwelcomepage.h
index 47d4e4b90ce..a4f7e4fc193 100644
--- a/src/plugins/qtsupport/gettingstartedwelcomepage.h
+++ b/src/plugins/qtsupport/gettingstartedwelcomepage.h
@@ -31,7 +31,7 @@
#ifndef GETTINGSTARTEDWELCOMEPAGE_H
#define GETTINGSTARTEDWELCOMEPAGE_H
-#include <utils/iwelcomepage.h>
+#include <coreplugin/iwelcomepage.h>
#include <QStringList>
@@ -45,7 +45,7 @@ namespace Internal {
class ExamplesListModel;
-class ExamplesWelcomePage : public Utils::IWelcomePage
+class ExamplesWelcomePage : public Core::IWelcomePage
{
Q_OBJECT
@@ -58,7 +58,7 @@ public:
int priority() const;
bool hasSearchBar() const;
void facilitateQml(QQmlEngine *);
- Id id() const;
+ Core::Id id() const;
Q_INVOKABLE void openUrl(const QUrl &url);
public slots:
diff --git a/src/plugins/qtsupport/qtoutputformatter.cpp b/src/plugins/qtsupport/qtoutputformatter.cpp
index 0de953b19d6..646e99b76cd 100644
--- a/src/plugins/qtsupport/qtoutputformatter.cpp
+++ b/src/plugins/qtsupport/qtoutputformatter.cpp
@@ -32,6 +32,7 @@
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/project.h>
+#include <utils/ansiescapecodehandler.h>
#include <utils/theme/theme.h>
#include <QPlainTextEdit>
@@ -100,95 +101,77 @@ LinkResult QtOutputFormatter::matchLine(const QString &line) const
void QtOutputFormatter::appendMessage(const QString &txt, Utils::OutputFormat format)
{
- QTextCursor cursor(plainTextEdit()->document());
- cursor.movePosition(QTextCursor::End);
- cursor.beginEditBlock();
+ appendMessage(txt, charFormat(format));
+}
+void QtOutputFormatter::appendMessagePart(QTextCursor &cursor, const QString &txt,
+ const QTextCharFormat &format)
+{
QString deferredText;
- int start = 0;
- int pos = txt.indexOf(QLatin1Char('\n'));
- while (pos != -1) {
- // Line identified
- if (!m_lastLine.isEmpty()) {
- // Line continuation
- const QString newPart = txt.mid(start, pos - start + 1);
- const QString line = m_lastLine + newPart;
- LinkResult lr = matchLine(line);
- if (!lr.href.isEmpty()) {
- // Found something && line continuation
- cursor.insertText(deferredText, charFormat(format));
- deferredText.clear();
+ const int length = txt.length();
+ for (int start = 0, pos = -1; start < length; start = pos + 1) {
+ pos = txt.indexOf(QLatin1Char('\n'), start);
+ const QString newPart = txt.mid(start, (pos == -1) ? -1 : pos - start + 1);
+ const QString line = m_lastLine + newPart;
+
+ LinkResult lr = matchLine(line);
+ if (!lr.href.isEmpty()) {
+ // Found something && line continuation
+ cursor.insertText(deferredText, format);
+ deferredText.clear();
+ if (!m_lastLine.isEmpty())
clearLastLine();
- appendLine(cursor, lr, line, format);
- } else {
- // Found nothing, just emit the new part
- deferredText += newPart;
- }
- // Handled line continuation
- m_lastLine.clear();
+ appendLine(cursor, lr, line, format);
} else {
- const QString line = txt.mid(start, pos - start + 1);
- LinkResult lr = matchLine(line);
- if (!lr.href.isEmpty()) {
- cursor.insertText(deferredText, charFormat(format));
- deferredText.clear();
- appendLine(cursor, lr, line, format);
- } else {
- deferredText += line;
- }
+ // Found nothing, just emit the new part
+ deferredText += newPart;
}
- start = pos + 1;
- pos = txt.indexOf(QLatin1Char('\n'), start);
- }
- // Handle left over stuff
- if (start < txt.length()) {
- if (!m_lastLine.isEmpty()) {
- // Line continuation
- const QString newPart = txt.mid(start);
- const QString line = m_lastLine + newPart;
- LinkResult lr = matchLine(line);
- if (!lr.href.isEmpty()) {
- // Found something && line continuation
- cursor.insertText(deferredText, charFormat(format));
- deferredText.clear();
- clearLastLine();
- appendLine(cursor, lr, line, format);
- } else {
- // Found nothing, just emit the new part
- deferredText += newPart;
- }
+ if (pos == -1) {
m_lastLine = line;
- } else {
- m_lastLine = txt.mid(start);
- LinkResult lr = matchLine(m_lastLine);
- if (!lr.href.isEmpty()) {
- cursor.insertText(deferredText, charFormat(format));
- deferredText.clear();
- appendLine(cursor, lr, m_lastLine, format);
- } else {
- deferredText += m_lastLine;
- }
+ break;
}
+ m_lastLine.clear(); // Handled line continuation
}
- cursor.insertText(deferredText, charFormat(format));
+ cursor.insertText(deferredText, format);
+}
+
+void QtOutputFormatter::appendMessage(const QString &txt, const QTextCharFormat &format)
+{
+ QTextCursor cursor(plainTextEdit()->document());
+ cursor.movePosition(QTextCursor::End);
+ cursor.beginEditBlock();
+
+ foreach (const FormattedText &output, parseAnsi(txt, format))
+ appendMessagePart(cursor, output.text, output.format);
+
cursor.endEditBlock();
}
void QtOutputFormatter::appendLine(QTextCursor &cursor, const LinkResult &lr,
const QString &line, Utils::OutputFormat format)
{
- const QTextCharFormat normalFormat = charFormat(format);
- cursor.insertText(line.left(lr.start), normalFormat);
-
- QTextCharFormat linkFormat = normalFormat;
- linkFormat.setForeground(creatorTheme()->color(Theme::QtOutputFormatter_LinkTextColor));
- linkFormat.setUnderlineStyle(QTextCharFormat::SingleUnderline);
- linkFormat.setAnchor(true);
- linkFormat.setAnchorHref(lr.href);
- cursor.insertText(line.mid(lr.start, lr.end - lr.start), linkFormat);
- cursor.insertText(line.mid(lr.end), normalFormat);
+ appendLine(cursor, lr, line, charFormat(format));
+}
+
+static QTextCharFormat linkFormat(const QTextCharFormat &inputFormat, const QString &href)
+{
+ QTextCharFormat result = inputFormat;
+ result.setForeground(creatorTheme()->color(Theme::QtOutputFormatter_LinkTextColor));
+ result.setUnderlineStyle(QTextCharFormat::SingleUnderline);
+ result.setAnchor(true);
+ result.setAnchorHref(href);
+
+ return result;
+}
+
+void QtOutputFormatter::appendLine(QTextCursor &cursor, const LinkResult &lr,
+ const QString &line, const QTextCharFormat &format)
+{
+ cursor.insertText(line.left(lr.start), format);
+ cursor.insertText(line.mid(lr.start, lr.end - lr.start), linkFormat(format, lr.href));
+ cursor.insertText(line.mid(lr.end), format);
}
void QtOutputFormatter::handleLink(const QString &href)
@@ -274,6 +257,8 @@ void QtOutputFormatter::updateProjectFileList()
using namespace QtSupport::Internal;
+Q_DECLARE_METATYPE(QTextCharFormat);
+
class TestQtOutputFormatter : public QtOutputFormatter
{
public:
@@ -359,4 +344,87 @@ void QtSupportPlugin::testQtOutputFormatter()
QCOMPARE(formatter.column, column);
}
+static QTextCharFormat blueFormat()
+{
+ QTextCharFormat result;
+ result.setForeground(QColor(0, 0, 127));
+ return result;
+}
+
+void QtSupportPlugin::testQtOutputFormatter_appendMessage_data()
+{
+ QTest::addColumn<QString>("inputText");
+ QTest::addColumn<QString>("outputText");
+ QTest::addColumn<QTextCharFormat>("inputFormat");
+ QTest::addColumn<QTextCharFormat>("outputFormat");
+
+ QTest::newRow("pass through")
+ << QString::fromLatin1("test\n123")
+ << QString::fromLatin1("test\n123")
+ << QTextCharFormat()
+ << QTextCharFormat();
+ QTest::newRow("Qt error")
+ << QString::fromLatin1("Object::Test in test.cpp:123")
+ << QString::fromLatin1("Object::Test in test.cpp:123")
+ << QTextCharFormat()
+ << linkFormat(QTextCharFormat(), QLatin1String("test.cpp:123"));
+ QTest::newRow("colored")
+ << QString::fromLatin1("blue da ba dee")
+ << QString::fromLatin1("blue da ba dee")
+ << blueFormat()
+ << blueFormat();
+ QTest::newRow("ANSI color change")
+ << QString::fromLatin1("\x1b[38;2;0;0;127mHello")
+ << QString::fromLatin1("Hello")
+ << QTextCharFormat()
+ << blueFormat();
+}
+
+void QtSupportPlugin::testQtOutputFormatter_appendMessage()
+{
+ QPlainTextEdit edit;
+ TestQtOutputFormatter formatter;
+ formatter.setPlainTextEdit(&edit);
+
+ QFETCH(QString, inputText);
+ QFETCH(QString, outputText);
+ QFETCH(QTextCharFormat, inputFormat);
+ QFETCH(QTextCharFormat, outputFormat);
+
+ formatter.appendMessage(inputText, inputFormat);
+
+ QCOMPARE(edit.toPlainText(), outputText);
+ QCOMPARE(edit.currentCharFormat(), outputFormat);
+}
+
+void QtSupportPlugin::testQtOutputFormatter_appendMixedAssertAndAnsi()
+{
+ QPlainTextEdit edit;
+ TestQtOutputFormatter formatter;
+ formatter.setPlainTextEdit(&edit);
+
+ const QString inputText = QString::fromLatin1(
+ "\x1b[38;2;0;0;127mHello\n"
+ "Object::Test in test.cpp:123\n"
+ "\x1b[38;2;0;0;127mHello\n");
+ const QString outputText = QString::fromLatin1(
+ "Hello\n"
+ "Object::Test in test.cpp:123\n"
+ "Hello\n");
+
+ formatter.appendMessage(inputText, QTextCharFormat());
+
+ QCOMPARE(edit.toPlainText(), outputText);
+
+ edit.moveCursor(QTextCursor::Start);
+ QCOMPARE(edit.currentCharFormat(), blueFormat());
+
+ edit.moveCursor(QTextCursor::Down);
+ edit.moveCursor(QTextCursor::EndOfLine);
+ QCOMPARE(edit.currentCharFormat(), linkFormat(QTextCharFormat(), QLatin1String("test.cpp:123")));
+
+ edit.moveCursor(QTextCursor::End);
+ QCOMPARE(edit.currentCharFormat(), blueFormat());
+}
+
#endif // WITH_TESTS
diff --git a/src/plugins/qtsupport/qtoutputformatter.h b/src/plugins/qtsupport/qtoutputformatter.h
index f83705c1227..4cdf79be7f0 100644
--- a/src/plugins/qtsupport/qtoutputformatter.h
+++ b/src/plugins/qtsupport/qtoutputformatter.h
@@ -63,8 +63,8 @@ class QTSUPPORT_EXPORT QtOutputFormatter
public:
explicit QtOutputFormatter(ProjectExplorer::Project *project);
- void appendMessage(const QString &text,
- Utils::OutputFormat format);
+ void appendMessage(const QString &text, Utils::OutputFormat format);
+ void appendMessage(const QString &text, const QTextCharFormat &format);
void handleLink(const QString &href);
protected:
@@ -76,8 +76,11 @@ private slots:
private:
LinkResult matchLine(const QString &line) const;
+ void appendMessagePart(QTextCursor &cursor, const QString &txt, const QTextCharFormat &format);
void appendLine(QTextCursor &cursor, const LinkResult &lr, const QString &line,
Utils::OutputFormat);
+ void appendLine(QTextCursor &cursor, const LinkResult &lr, const QString &line,
+ const QTextCharFormat &format);
mutable QRegExp m_qmlError;
mutable QRegExp m_qtError;
diff --git a/src/plugins/qtsupport/qtsupportplugin.cpp b/src/plugins/qtsupport/qtsupportplugin.cpp
index 1b37e0e26ae..902f1d58f84 100644
--- a/src/plugins/qtsupport/qtsupportplugin.cpp
+++ b/src/plugins/qtsupport/qtsupportplugin.cpp
@@ -49,7 +49,7 @@
#include <coreplugin/jsexpander.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/target.h>
#include <utils/macroexpander.h>
@@ -102,7 +102,7 @@ bool QtSupportPlugin::initialize(const QStringList &arguments, QString *errorMes
static QString qmakeProperty(const char *propertyName)
{
- ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ ProjectExplorer::Project *project = ProjectExplorer::ProjectTree::currentProject();
if (!project || !project->activeTarget())
return QString();
diff --git a/src/plugins/qtsupport/qtsupportplugin.h b/src/plugins/qtsupport/qtsupportplugin.h
index aa4ca015e7e..309efab73c6 100644
--- a/src/plugins/qtsupport/qtsupportplugin.h
+++ b/src/plugins/qtsupport/qtsupportplugin.h
@@ -54,6 +54,9 @@ private slots:
void testQtOutputParser();
void testQtOutputFormatter_data();
void testQtOutputFormatter();
+ void testQtOutputFormatter_appendMessage_data();
+ void testQtOutputFormatter_appendMessage();
+ void testQtOutputFormatter_appendMixedAssertAndAnsi();
#endif
};
diff --git a/src/plugins/qtsupport/screenshotcropper.cpp b/src/plugins/qtsupport/screenshotcropper.cpp
index 18b370d1c01..77618510a12 100644
--- a/src/plugins/qtsupport/screenshotcropper.cpp
+++ b/src/plugins/qtsupport/screenshotcropper.cpp
@@ -30,12 +30,13 @@
#include "screenshotcropper.h"
+#include <utils/fileutils.h>
+
#include <coreplugin/icore.h>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QDebug>
#include <QFile>
-#include <QFileInfo>
namespace QtSupport {
namespace Internal {
@@ -57,7 +58,7 @@ Q_GLOBAL_STATIC(AreasOfInterest, welcomeScreenAreas)
static inline QString fileNameForPath(const QString &path)
{
- return QFileInfo(path).fileName();
+ return Utils::FileName::fromString(path).fileName();
}
static QRect cropRectForAreaOfInterest(const QSize &imageSize, const QSize &cropSize, const QRect &areaOfInterest)
diff --git a/src/plugins/qtsupport/uicodemodelsupport.cpp b/src/plugins/qtsupport/uicodemodelsupport.cpp
index de918526fc2..445dc1048d2 100644
--- a/src/plugins/qtsupport/uicodemodelsupport.cpp
+++ b/src/plugins/qtsupport/uicodemodelsupport.cpp
@@ -411,7 +411,7 @@ void UiCodeModelManager::editorIsAboutToClose(Core::IEditor *editor)
if (isFormWindowDocument(m_lastEditor->document())) {
disconnect(m_lastEditor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsHasChanged()));
if (m_dirty) {
- updateContents(m_lastEditor->document()->filePath(),
+ updateContents(m_lastEditor->document()->filePath().toString(),
formWindowEditorContents(m_lastEditor));
m_dirty = false;
}
@@ -427,7 +427,7 @@ void UiCodeModelManager::editorWasChanged(Core::IEditor *editor)
disconnect(m_lastEditor->document(), SIGNAL(changed()), this, SLOT(uiDocumentContentsHasChanged()));
if (m_dirty) {
- updateContents(m_lastEditor->document()->filePath(),
+ updateContents(m_lastEditor->document()->filePath().toString(),
formWindowEditorContents(m_lastEditor));
m_dirty = false;
}
diff --git a/src/plugins/remotelinux/abstractpackagingstep.cpp b/src/plugins/remotelinux/abstractpackagingstep.cpp
index 4bd2674a014..e41486ed797 100644
--- a/src/plugins/remotelinux/abstractpackagingstep.cpp
+++ b/src/plugins/remotelinux/abstractpackagingstep.cpp
@@ -78,7 +78,8 @@ void AbstractPackagingStep::ctor()
connect(target(), SIGNAL(deploymentDataChanged()), SLOT(setDeploymentDataModified()));
setDeploymentDataModified();
- connect(this, SIGNAL(unmodifyDeploymentData()), this, SLOT(setDeploymentDataUnmodified()));
+ connect(this, &AbstractPackagingStep::unmodifyDeploymentData,
+ this, &AbstractPackagingStep::setDeploymentDataUnmodified);
}
AbstractPackagingStep::~AbstractPackagingStep()
@@ -92,8 +93,8 @@ void AbstractPackagingStep::handleBuildConfigurationChanged()
disconnect(d->currentBuildConfiguration, 0, this, 0);
d->currentBuildConfiguration = target()->activeBuildConfiguration();
if (d->currentBuildConfiguration) {
- connect(d->currentBuildConfiguration, SIGNAL(buildDirectoryChanged()), this,
- SIGNAL(packageFilePathChanged()));
+ connect(d->currentBuildConfiguration, &BuildConfiguration::buildDirectoryChanged,
+ this, &AbstractPackagingStep::packageFilePathChanged);
}
emit packageFilePathChanged();
}
diff --git a/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp b/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
index 604a5d5de0e..4beb300217e 100644
--- a/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
+++ b/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
@@ -274,12 +274,13 @@ void AbstractRemoteLinuxDeployService::handleDeviceSetupDone(bool success)
d->state = Connecting;
d->connection = QSsh::acquireConnection(deviceConfiguration()->sshParameters());
- connect(d->connection, SIGNAL(error(QSsh::SshError)),
- SLOT(handleConnectionFailure()));
+ connect(d->connection, &SshConnection::error,
+ this, &AbstractRemoteLinuxDeployService::handleConnectionFailure);
if (d->connection->state() == SshConnection::Connected) {
handleConnected();
} else {
- connect(d->connection, SIGNAL(connected()), SLOT(handleConnected()));
+ connect(d->connection, &SshConnection::connected,
+ this, &AbstractRemoteLinuxDeployService::handleConnected);
emit progressMessage(tr("Connecting to device..."));
if (d->connection->state() == SshConnection::Unconnected)
d->connection->connectToHost();
diff --git a/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp b/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp
index 6652dc98990..010fb6f0be4 100644
--- a/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp
+++ b/src/plugins/remotelinux/abstractremotelinuxrunsupport.cpp
@@ -59,7 +59,7 @@ public:
AbstractRemoteLinuxRunSupport::State state;
DeviceApplicationRunner appRunner;
DeviceUsedPortsGatherer portsGatherer;
- const ProjectExplorer::IDevice::ConstPtr device;
+ const IDevice::ConstPtr device;
Utils::PortList portList;
const QString remoteFilePath;
const QStringList arguments;
@@ -97,8 +97,10 @@ void AbstractRemoteLinuxRunSupport::handleRemoteSetupRequested()
{
QTC_ASSERT(d->state == Inactive, return);
d->state = GatheringPorts;
- connect(&d->portsGatherer, SIGNAL(error(QString)), SLOT(handlePortsGathererError(QString)));
- connect(&d->portsGatherer, SIGNAL(portListReady()), SLOT(handlePortListReady()));
+ connect(&d->portsGatherer, &DeviceUsedPortsGatherer::error,
+ this, &AbstractRemoteLinuxRunSupport::handlePortsGathererError);
+ connect(&d->portsGatherer, &DeviceUsedPortsGatherer::portListReady,
+ this, &AbstractRemoteLinuxRunSupport::handlePortListReady);
d->portsGatherer.start(d->device);
}
diff --git a/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp b/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp
index b2aaac2e537..2df7ac663f3 100644
--- a/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp
+++ b/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp
@@ -36,7 +36,6 @@
#include <projectexplorer/deployablefile.h>
#include <utils/qtcassert.h>
-#include <QFileInfo>
#include <QString>
using namespace ProjectExplorer;
@@ -115,10 +114,12 @@ void AbstractUploadAndInstallPackageService::doDeploy()
QTC_ASSERT(d->state == Inactive, return);
d->state = Uploading;
- const QString fileName = QFileInfo(packageFilePath()).fileName();
+ const QString fileName = Utils::FileName::fromString(packageFilePath()).fileName();
const QString remoteFilePath = uploadDir() + QLatin1Char('/') + fileName;
- connect(d->uploader, SIGNAL(progress(QString)), SIGNAL(progressMessage(QString)));
- connect(d->uploader, SIGNAL(uploadFinished(QString)), SLOT(handleUploadFinished(QString)));
+ connect(d->uploader, &PackageUploader::progress,
+ this, &AbstractUploadAndInstallPackageService::progressMessage);
+ connect(d->uploader, &PackageUploader::uploadFinished,
+ this, &AbstractUploadAndInstallPackageService::handleUploadFinished);
d->uploader->uploadPackage(connection(), packageFilePath(), remoteFilePath);
}
@@ -151,7 +152,7 @@ void AbstractUploadAndInstallPackageService::handleUploadFinished(const QString
emit progressMessage(tr("Successfully uploaded package file."));
const QString remoteFilePath = uploadDir() + QLatin1Char('/')
- + QFileInfo(packageFilePath()).fileName();
+ + Utils::FileName::fromString(packageFilePath()).fileName();
d->state = Installing;
emit progressMessage(tr("Installing package to device..."));
connect(packageInstaller(), SIGNAL(stdoutData(QString)), SIGNAL(stdOutData(QString)));
diff --git a/src/plugins/remotelinux/genericdirectuploadservice.cpp b/src/plugins/remotelinux/genericdirectuploadservice.cpp
index 4928b572548..dd9d1f93a7d 100644
--- a/src/plugins/remotelinux/genericdirectuploadservice.cpp
+++ b/src/plugins/remotelinux/genericdirectuploadservice.cpp
@@ -156,7 +156,7 @@ void GenericDirectUploadService::handleSftpChannelError(const QString &message)
handleDeploymentDone();
}
-void GenericDirectUploadService::handleUploadFinished(QSsh::SftpJobId jobId, const QString &errorMsg)
+void GenericDirectUploadService::handleUploadFinished(SftpJobId jobId, const QString &errorMsg)
{
Q_UNUSED(jobId);
diff --git a/src/plugins/remotelinux/genericdirectuploadstep.cpp b/src/plugins/remotelinux/genericdirectuploadstep.cpp
index 7c585162af1..a635b0271bc 100644
--- a/src/plugins/remotelinux/genericdirectuploadstep.cpp
+++ b/src/plugins/remotelinux/genericdirectuploadstep.cpp
@@ -96,13 +96,13 @@ public:
} // namespace Internal
-GenericDirectUploadStep::GenericDirectUploadStep(ProjectExplorer::BuildStepList *bsl, Core::Id id)
+GenericDirectUploadStep::GenericDirectUploadStep(BuildStepList *bsl, Core::Id id)
: AbstractRemoteLinuxDeployStep(bsl, id)
{
ctor();
}
-GenericDirectUploadStep::GenericDirectUploadStep(ProjectExplorer::BuildStepList *bsl, GenericDirectUploadStep *other)
+GenericDirectUploadStep::GenericDirectUploadStep(BuildStepList *bsl, GenericDirectUploadStep *other)
: AbstractRemoteLinuxDeployStep(bsl, other)
{
ctor();
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
index 394c12df637..fc52da5a44b 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
@@ -63,6 +63,8 @@ GenericLinuxDeviceConfigurationWidget::GenericLinuxDeviceConfigurationWidget(
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()));
+ connect(m_ui->hostKeyCheckBox, &QCheckBox::toggled, this,
+ &GenericLinuxDeviceConfigurationWidget::hostKeyCheckingChanged);
initGui();
}
@@ -158,6 +160,14 @@ void GenericLinuxDeviceConfigurationWidget::createNewKey()
setPrivateKey(dialog.privateKeyFilePath());
}
+void GenericLinuxDeviceConfigurationWidget::hostKeyCheckingChanged(bool doCheck)
+{
+ SshConnectionParameters sshParams = device()->sshParameters();
+ sshParams.hostKeyCheckingMode
+ = doCheck ? SshHostKeyCheckingAllowNoMatch : SshHostKeyCheckingNone;
+ device()->setSshParameters(sshParams);
+}
+
void GenericLinuxDeviceConfigurationWidget::updateDeviceFromUi()
{
hostNameEditingFinished();
@@ -200,6 +210,7 @@ void GenericLinuxDeviceConfigurationWidget::initGui()
m_ui->timeoutSpinBox->setValue(sshParams.timeout);
m_ui->hostLineEdit->setEnabled(!device()->isAutoDetected());
m_ui->sshPortSpinBox->setEnabled(!device()->isAutoDetected());
+ m_ui->hostKeyCheckBox->setChecked(sshParams.hostKeyCheckingMode != SshHostKeyCheckingNone);
m_ui->hostLineEdit->setText(sshParams.host);
m_ui->sshPortSpinBox->setValue(sshParams.port);
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h
index 2d355c8f42f..1c07ddfc08f 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.h
@@ -62,6 +62,7 @@ private slots:
void handleFreePortsChanged();
void setPrivateKey(const QString &path);
void createNewKey();
+ void hostKeyCheckingChanged(bool doCheck);
private:
void updateDeviceFromUi();
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui
index 2b38ed1ecd3..3074e469dad 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>393</width>
- <height>321</height>
+ <width>556</width>
+ <height>309</height>
</rect>
</property>
<property name="windowTitle">
@@ -123,6 +123,13 @@
</property>
</widget>
</item>
+ <item>
+ <widget class="QCheckBox" name="hostKeyCheckBox">
+ <property name="text">
+ <string>&amp;Check host key</string>
+ </property>
+ </widget>
+ </item>
</layout>
</item>
<item row="3" column="0">
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
index 3dd5feca986..0b19491d5a0 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
@@ -75,7 +75,7 @@ GenericLinuxDeviceConfigurationWizard::~GenericLinuxDeviceConfigurationWizard()
IDevice::Ptr GenericLinuxDeviceConfigurationWizard::device()
{
- QSsh::SshConnectionParameters sshParams;
+ SshConnectionParameters sshParams;
sshParams.options &= ~SshConnectionOptions(SshEnableStrictConformanceChecks); // For older SSH servers.
sshParams.host = d->setupPage.hostName();
sshParams.userName = d->setupPage.userName();
diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp
index 162adf43d40..65bd0b0d226 100644
--- a/src/plugins/remotelinux/linuxdevice.cpp
+++ b/src/plugins/remotelinux/linuxdevice.cpp
@@ -123,7 +123,7 @@ private:
}
};
-class LinuxPortsGatheringMethod : public ProjectExplorer::PortsGatheringMethod
+class LinuxPortsGatheringMethod : public PortsGatheringMethod
{
QByteArray commandLine(QAbstractSocket::NetworkLayerProtocol protocol) const
{
@@ -175,7 +175,7 @@ QString LinuxDevice::displayType() const
return tr("Generic Linux");
}
-ProjectExplorer::IDeviceWidget *LinuxDevice::createWidget()
+IDeviceWidget *LinuxDevice::createWidget()
{
return new GenericLinuxDeviceConfigurationWidget(sharedFromThis());
}
@@ -224,7 +224,7 @@ LinuxDevice::Ptr LinuxDevice::create()
return Ptr(new LinuxDevice);
}
-ProjectExplorer::IDevice::Ptr LinuxDevice::clone() const
+IDevice::Ptr LinuxDevice::clone() const
{
return Ptr(new LinuxDevice(*this));
}
diff --git a/src/plugins/remotelinux/linuxdevicetester.cpp b/src/plugins/remotelinux/linuxdevicetester.cpp
index b1bf93d5b0a..5b7f58ee061 100644
--- a/src/plugins/remotelinux/linuxdevicetester.cpp
+++ b/src/plugins/remotelinux/linuxdevicetester.cpp
@@ -78,9 +78,10 @@ void GenericLinuxDeviceTester::testDevice(const IDevice::ConstPtr &deviceConfigu
d->deviceConfiguration = deviceConfiguration;
d->connection = new SshConnection(deviceConfiguration->sshParameters(), this);
- connect(d->connection, SIGNAL(connected()), SLOT(handleConnected()));
- connect(d->connection, SIGNAL(error(QSsh::SshError)),
- SLOT(handleConnectionFailure()));
+ connect(d->connection, &SshConnection::connected,
+ this, &GenericLinuxDeviceTester::handleConnected);
+ connect(d->connection, &SshConnection::error,
+ this, &GenericLinuxDeviceTester::handleConnectionFailure);
emit progressMessage(tr("Connecting to host..."));
d->state = Connecting;
@@ -147,8 +148,10 @@ void GenericLinuxDeviceTester::handleProcessFinished(int exitStatus)
emit progressMessage(QString::fromUtf8(d->process->readAllStandardOutput()));
}
- connect(&d->portsGatherer, SIGNAL(error(QString)), SLOT(handlePortsGatheringError(QString)));
- connect(&d->portsGatherer, SIGNAL(portListReady()), SLOT(handlePortListReady()));
+ connect(&d->portsGatherer, &DeviceUsedPortsGatherer::error,
+ this, &GenericLinuxDeviceTester::handlePortsGatheringError);
+ connect(&d->portsGatherer, &DeviceUsedPortsGatherer::portListReady,
+ this, &GenericLinuxDeviceTester::handlePortListReady);
emit progressMessage(tr("Checking if specified ports are available..."));
d->state = TestingPorts;
diff --git a/src/plugins/remotelinux/packageuploader.cpp b/src/plugins/remotelinux/packageuploader.cpp
index 67d879c3b6c..2b1e5d62428 100644
--- a/src/plugins/remotelinux/packageuploader.cpp
+++ b/src/plugins/remotelinux/packageuploader.cpp
@@ -59,7 +59,8 @@ void PackageUploader::uploadPackage(SshConnection *connection,
m_localFilePath = localFilePath;
m_remoteFilePath = remoteFilePath;
m_connection = connection;
- connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(handleConnectionFailure()));
+ connect(m_connection, &SshConnection::error,
+ this, &PackageUploader::handleConnectionFailure);
m_uploader = m_connection->createSftpChannel();
connect(m_uploader.data(), SIGNAL(initialized()), this,
SLOT(handleSftpChannelInitialized()));
diff --git a/src/plugins/remotelinux/publickeydeploymentdialog.cpp b/src/plugins/remotelinux/publickeydeploymentdialog.cpp
index ff47851a6eb..fd7346dbca5 100644
--- a/src/plugins/remotelinux/publickeydeploymentdialog.cpp
+++ b/src/plugins/remotelinux/publickeydeploymentdialog.cpp
@@ -75,9 +75,12 @@ PublicKeyDeploymentDialog::PublicKeyDeploymentDialog(const IDevice::ConstPtr &de
d->done = false;
setLabelText(tr("Deploying..."));
setValue(0);
- connect(this, SIGNAL(canceled()), SLOT(handleCanceled()));
- connect(&d->keyDeployer, SIGNAL(error(QString)), SLOT(handleDeploymentError(QString)));
- connect(&d->keyDeployer, SIGNAL(finishedSuccessfully()), SLOT(handleDeploymentSuccess()));
+ connect(this, &PublicKeyDeploymentDialog::canceled,
+ this, &PublicKeyDeploymentDialog::handleCanceled);
+ connect(&d->keyDeployer, &SshKeyDeployer::error,
+ this, &PublicKeyDeploymentDialog::handleDeploymentError);
+ connect(&d->keyDeployer, &SshKeyDeployer::finishedSuccessfully,
+ this, &PublicKeyDeploymentDialog::handleDeploymentSuccess);
d->keyDeployer.deployPublicKey(deviceConfig->sshParameters(), publicKeyFileName);
}
diff --git a/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp b/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp
index 29c46100fcb..d9a32264459 100644
--- a/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp
+++ b/src/plugins/remotelinux/remotelinuxanalyzesupport.cpp
@@ -96,8 +96,8 @@ RemoteLinuxAnalyzeSupport::RemoteLinuxAnalyzeSupport(AbstractRemoteLinuxRunConfi
{
connect(d->runControl, SIGNAL(starting(const Analyzer::AnalyzerRunControl*)),
SLOT(handleRemoteSetupRequested()));
- connect(&d->outputParser, SIGNAL(waitingForConnectionOnPort(quint16)),
- SLOT(remoteIsRunning()));
+ connect(&d->outputParser, &QmlDebug::QmlOutputParser::waitingForConnectionOnPort,
+ this, &RemoteLinuxAnalyzeSupport::remoteIsRunning);
}
RemoteLinuxAnalyzeSupport::~RemoteLinuxAnalyzeSupport()
@@ -133,12 +133,18 @@ void RemoteLinuxAnalyzeSupport::startExecution()
setState(StartingRunner);
DeviceApplicationRunner *runner = appRunner();
- connect(runner, SIGNAL(remoteStderr(QByteArray)), SLOT(handleRemoteErrorOutput(QByteArray)));
- connect(runner, SIGNAL(remoteStdout(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
- connect(runner, SIGNAL(remoteProcessStarted()), SLOT(handleRemoteProcessStarted()));
- connect(runner, SIGNAL(finished(bool)), SLOT(handleAppRunnerFinished(bool)));
- connect(runner, SIGNAL(reportProgress(QString)), SLOT(handleProgressReport(QString)));
- connect(runner, SIGNAL(reportError(QString)), SLOT(handleAppRunnerError(QString)));
+ connect(runner, &DeviceApplicationRunner::remoteStderr,
+ this, &RemoteLinuxAnalyzeSupport::handleRemoteErrorOutput);
+ connect(runner, &DeviceApplicationRunner::remoteStdout,
+ this, &RemoteLinuxAnalyzeSupport::handleRemoteOutput);
+ connect(runner, &DeviceApplicationRunner::remoteProcessStarted,
+ this, &RemoteLinuxAnalyzeSupport::handleRemoteProcessStarted);
+ connect(runner, &DeviceApplicationRunner::finished,
+ this, &RemoteLinuxAnalyzeSupport::handleAppRunnerFinished);
+ connect(runner, &DeviceApplicationRunner::reportProgress,
+ this, &RemoteLinuxAnalyzeSupport::handleProgressReport);
+ connect(runner, &DeviceApplicationRunner::reportError,
+ this, &RemoteLinuxAnalyzeSupport::handleAppRunnerError);
const QStringList args = arguments()
<< QString::fromLatin1("-qmljsdebugger=port:%1,block").arg(d->qmlPort);
diff --git a/src/plugins/remotelinux/remotelinuxcheckforfreediskspaceservice.cpp b/src/plugins/remotelinux/remotelinuxcheckforfreediskspaceservice.cpp
index cbc284ab561..a4b8b6e04e9 100644
--- a/src/plugins/remotelinux/remotelinuxcheckforfreediskspaceservice.cpp
+++ b/src/plugins/remotelinux/remotelinuxcheckforfreediskspaceservice.cpp
@@ -129,8 +129,10 @@ bool RemoteLinuxCheckForFreeDiskSpaceService::isDeploymentPossible(QString *whyN
void RemoteLinuxCheckForFreeDiskSpaceService::doDeploy()
{
d->processRunner = new QSsh::SshRemoteProcessRunner;
- connect(d->processRunner, SIGNAL(processClosed(int)), SLOT(handleProcessFinished()));
- connect(d->processRunner, SIGNAL(readyReadStandardError()), SLOT(handleStdErr()));
+ connect(d->processRunner, &QSsh::SshRemoteProcessRunner::processClosed,
+ this, &RemoteLinuxCheckForFreeDiskSpaceService::handleProcessFinished);
+ connect(d->processRunner, &QSsh::SshRemoteProcessRunner::readyReadStandardError,
+ this, &RemoteLinuxCheckForFreeDiskSpaceService::handleStdErr);
const QString command = QString::fromLatin1("df -k %1 |tail -n 1 |sed 's/ */ /g' "
"|cut -d ' ' -f 4").arg(d->pathToCheck);
d->processRunner->run(command.toUtf8(), deviceConfiguration()->sshParameters());
diff --git a/src/plugins/remotelinux/remotelinuxdebugsupport.cpp b/src/plugins/remotelinux/remotelinuxdebugsupport.cpp
index 159344f7754..f9bf98e4917 100644
--- a/src/plugins/remotelinux/remotelinuxdebugsupport.cpp
+++ b/src/plugins/remotelinux/remotelinuxdebugsupport.cpp
@@ -32,10 +32,11 @@
#include "remotelinuxrunconfiguration.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerrunconfigurationaspect.h>
+#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerstartparameters.h>
#include <debugger/debuggerkitinformation.h>
+
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
@@ -58,15 +59,15 @@ class LinuxDeviceDebugSupportPrivate
{
public:
LinuxDeviceDebugSupportPrivate(const AbstractRemoteLinuxRunConfiguration *runConfig,
- DebuggerEngine *engine)
- : engine(engine),
- qmlDebugging(runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useQmlDebugger()),
- cppDebugging(runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>()->useCppDebugger()),
+ DebuggerRunControl *runControl)
+ : runControl(runControl),
+ qmlDebugging(runConfig->extraAspect<DebuggerRunConfigurationAspect>()->useQmlDebugger()),
+ cppDebugging(runConfig->extraAspect<DebuggerRunConfigurationAspect>()->useCppDebugger()),
gdbServerPort(-1), qmlPort(-1)
{
}
- const QPointer<DebuggerEngine> engine;
+ const QPointer<DebuggerRunControl> runControl;
bool qmlDebugging;
bool cppDebugging;
QByteArray gdbserverOutput;
@@ -92,8 +93,8 @@ DebuggerStartParameters LinuxDeviceDebugSupport::startParameters(const AbstractR
if (ToolChain *tc = ToolChainKitInformation::toolChain(k))
params.toolChainAbi = tc->targetAbi();
- Debugger::DebuggerRunConfigurationAspect *aspect
- = runConfig->extraAspect<Debugger::DebuggerRunConfigurationAspect>();
+ DebuggerRunConfigurationAspect *aspect
+ = runConfig->extraAspect<DebuggerRunConfigurationAspect>();
if (aspect->useQmlDebugger()) {
params.languages |= QmlLanguage;
params.qmlServerAddress = device->sshParameters().host;
@@ -127,11 +128,12 @@ DebuggerStartParameters LinuxDeviceDebugSupport::startParameters(const AbstractR
}
LinuxDeviceDebugSupport::LinuxDeviceDebugSupport(AbstractRemoteLinuxRunConfiguration *runConfig,
- DebuggerEngine *engine)
- : AbstractRemoteLinuxRunSupport(runConfig, engine),
- d(new LinuxDeviceDebugSupportPrivate(static_cast<AbstractRemoteLinuxRunConfiguration *>(runConfig), engine))
+ DebuggerRunControl *runControl)
+ : AbstractRemoteLinuxRunSupport(runConfig, runControl),
+ d(new LinuxDeviceDebugSupportPrivate(static_cast<AbstractRemoteLinuxRunConfiguration *>(runConfig), runControl))
{
- connect(d->engine, SIGNAL(requestRemoteSetup()), this, SLOT(handleRemoteSetupRequested()));
+ connect(runControl, &DebuggerRunControl::requestRemoteSetup,
+ this, &LinuxDeviceDebugSupport::handleRemoteSetupRequested);
}
LinuxDeviceDebugSupport::~LinuxDeviceDebugSupport()
@@ -141,8 +143,8 @@ LinuxDeviceDebugSupport::~LinuxDeviceDebugSupport()
void LinuxDeviceDebugSupport::showMessage(const QString &msg, int channel)
{
- if (state() != Inactive && d->engine)
- d->engine->showMessage(msg, channel);
+ if (state() != Inactive && d->runControl)
+ d->runControl->showMessage(msg, channel);
}
void LinuxDeviceDebugSupport::handleRemoteSetupRequested()
@@ -166,10 +168,13 @@ void LinuxDeviceDebugSupport::startExecution()
d->gdbserverOutput.clear();
DeviceApplicationRunner *runner = appRunner();
- connect(runner, SIGNAL(remoteStderr(QByteArray)), SLOT(handleRemoteErrorOutput(QByteArray)));
- connect(runner, SIGNAL(remoteStdout(QByteArray)), SLOT(handleRemoteOutput(QByteArray)));
+ connect(runner, &DeviceApplicationRunner::remoteStderr,
+ this, &LinuxDeviceDebugSupport::handleRemoteErrorOutput);
+ connect(runner, &DeviceApplicationRunner::remoteStdout,
+ this, &LinuxDeviceDebugSupport::handleRemoteOutput);
if (d->qmlDebugging && !d->cppDebugging)
- connect(runner, SIGNAL(remoteProcessStarted()), SLOT(handleRemoteProcessStarted()));
+ connect(runner, &DeviceApplicationRunner::remoteProcessStarted,
+ this, &LinuxDeviceDebugSupport::handleRemoteProcessStarted);
QStringList args = arguments();
QString command;
@@ -188,9 +193,12 @@ void LinuxDeviceDebugSupport::startExecution()
args.append(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)));
+ connect(runner, &DeviceApplicationRunner::finished,
+ this, &LinuxDeviceDebugSupport::handleAppRunnerFinished);
+ connect(runner, &DeviceApplicationRunner::reportProgress,
+ this, &LinuxDeviceDebugSupport::handleProgressReport);
+ connect(runner, &DeviceApplicationRunner::reportError,
+ this, &LinuxDeviceDebugSupport::handleAppRunnerError);
runner->setEnvironment(environment());
runner->setWorkingDirectory(workingDirectory());
runner->start(device(), command, args);
@@ -200,8 +208,8 @@ void LinuxDeviceDebugSupport::handleAppRunnerError(const QString &error)
{
if (state() == Running) {
showMessage(error, AppError);
- if (d->engine)
- d->engine->notifyInferiorIll();
+ if (d->runControl)
+ d->runControl->notifyInferiorIll();
} else if (state() != Inactive) {
handleAdapterSetupFailed(error);
}
@@ -209,21 +217,21 @@ void LinuxDeviceDebugSupport::handleAppRunnerError(const QString &error)
void LinuxDeviceDebugSupport::handleAppRunnerFinished(bool success)
{
- if (!d->engine || state() == Inactive)
+ if (!d->runControl || state() == Inactive)
return;
if (state() == Running) {
// The QML engine does not realize on its own that the application has finished.
if (d->qmlDebugging && !d->cppDebugging)
- d->engine->quitDebugger();
+ d->runControl->quitDebugger();
else if (!success)
- d->engine->notifyInferiorIll();
+ d->runControl->notifyInferiorIll();
} else if (state() == StartingRunner) {
RemoteSetupResult result;
result.success = false;
result.reason = tr("Debugging failed.");
- d->engine->notifyEngineRemoteSetupFinished(result);
+ d->runControl->notifyEngineRemoteSetupFinished(result);
}
reset();
}
@@ -245,7 +253,7 @@ void LinuxDeviceDebugSupport::handleRemoteErrorOutput(const QByteArray &output)
{
QTC_ASSERT(state() != GatheringPorts, return);
- if (!d->engine)
+ if (!d->runControl)
return;
showMessage(QString::fromUtf8(output), AppError);
@@ -270,7 +278,7 @@ void LinuxDeviceDebugSupport::handleAdapterSetupFailed(const QString &error)
RemoteSetupResult result;
result.success = false;
result.reason = tr("Initial setup failed: %1").arg(error);
- d->engine->notifyEngineRemoteSetupFinished(result);
+ d->runControl->notifyEngineRemoteSetupFinished(result);
}
void LinuxDeviceDebugSupport::handleAdapterSetupDone()
@@ -281,7 +289,7 @@ void LinuxDeviceDebugSupport::handleAdapterSetupDone()
result.success = true;
result.gdbServerPort = d->gdbServerPort;
result.qmlServerPort = d->qmlPort;
- d->engine->notifyEngineRemoteSetupFinished(result);
+ d->runControl->notifyEngineRemoteSetupFinished(result);
}
void LinuxDeviceDebugSupport::handleRemoteProcessStarted()
diff --git a/src/plugins/remotelinux/remotelinuxdebugsupport.h b/src/plugins/remotelinux/remotelinuxdebugsupport.h
index a2d27f68b38..b45a1e9e367 100644
--- a/src/plugins/remotelinux/remotelinuxdebugsupport.h
+++ b/src/plugins/remotelinux/remotelinuxdebugsupport.h
@@ -34,7 +34,7 @@
#include "abstractremotelinuxrunsupport.h"
namespace Debugger {
-class DebuggerEngine;
+class DebuggerRunControl;
class DebuggerStartParameters;
}
@@ -50,7 +50,7 @@ public:
static Debugger::DebuggerStartParameters startParameters(const AbstractRemoteLinuxRunConfiguration *runConfig);
LinuxDeviceDebugSupport(AbstractRemoteLinuxRunConfiguration *runConfig,
- Debugger::DebuggerEngine *engine);
+ Debugger::DebuggerRunControl *runControl);
~LinuxDeviceDebugSupport();
protected:
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp b/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp
index bf8273682d0..cba52a98354 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp
+++ b/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp
@@ -37,14 +37,14 @@ namespace RemoteLinux {
using namespace Internal;
-RemoteLinuxDeployConfiguration::RemoteLinuxDeployConfiguration(ProjectExplorer::Target *target,
+RemoteLinuxDeployConfiguration::RemoteLinuxDeployConfiguration(Target *target,
const Core::Id id, const QString &defaultDisplayName)
: DeployConfiguration(target, id)
{
setDefaultDisplayName(defaultDisplayName);
}
-RemoteLinuxDeployConfiguration::RemoteLinuxDeployConfiguration(ProjectExplorer::Target *target,
+RemoteLinuxDeployConfiguration::RemoteLinuxDeployConfiguration(Target *target,
RemoteLinuxDeployConfiguration *source)
: DeployConfiguration(target, source)
{ }
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
index 85492571233..d274cdb2dbb 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
+++ b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
@@ -115,6 +115,11 @@ DeployConfiguration *RemoteLinuxDeployConfigurationFactory::restore(Target *pare
return dc;
}
+bool RemoteLinuxDeployConfigurationFactory::canClone(Target *parent, DeployConfiguration *product) const
+{
+ return canCreate(parent, product->id());
+}
+
DeployConfiguration *RemoteLinuxDeployConfigurationFactory::clone(Target *parent,
DeployConfiguration *product)
{
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.h b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.h
index d26271d21fc..66266a1aa71 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.h
+++ b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.h
@@ -48,6 +48,7 @@ public:
ProjectExplorer::DeployConfiguration *create(ProjectExplorer::Target *parent, Core::Id id);
bool canRestore(ProjectExplorer::Target *parent, const QVariantMap &map) const;
ProjectExplorer::DeployConfiguration *restore(ProjectExplorer::Target *parent, const QVariantMap &map);
+ bool canClone(ProjectExplorer::Target *parent, ProjectExplorer::DeployConfiguration *product) const;
ProjectExplorer::DeployConfiguration *clone(ProjectExplorer::Target *parent,
ProjectExplorer::DeployConfiguration *product);
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp b/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp
index 5d9ea4db7e3..bb1b21cad40 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp
+++ b/src/plugins/remotelinux/remotelinuxenvironmentaspectwidget.cpp
@@ -50,9 +50,11 @@ RemoteLinuxEnvironmentAspectWidget::RemoteLinuxEnvironmentAspectWidget(RemoteLin
{
QPushButton *button = fetchButton();
button->setText(FetchEnvButtonText);
- connect(button, SIGNAL(clicked()), this, SLOT(fetchEnvironment()));
- connect(deviceEnvReader, SIGNAL(finished()), this, SLOT(fetchEnvironmentFinished()));
- connect(deviceEnvReader, SIGNAL(error(QString)), this, SLOT(fetchEnvironmentError(QString)));
+ connect(button, &QPushButton::clicked, this, &RemoteLinuxEnvironmentAspectWidget::fetchEnvironment);
+ connect(deviceEnvReader, &Internal::RemoteLinuxEnvironmentReader::finished,
+ this, &RemoteLinuxEnvironmentAspectWidget::fetchEnvironmentFinished);
+ connect(deviceEnvReader, &Internal::RemoteLinuxEnvironmentReader::error,
+ this, &RemoteLinuxEnvironmentAspectWidget::fetchEnvironmentError);
}
RemoteLinuxEnvironmentAspect *RemoteLinuxEnvironmentAspectWidget::aspect() const
@@ -68,8 +70,10 @@ QPushButton *RemoteLinuxEnvironmentAspectWidget::fetchButton() const
void RemoteLinuxEnvironmentAspectWidget::fetchEnvironment()
{
QPushButton *button = fetchButton();
- disconnect(button, SIGNAL(clicked()), this, SLOT(fetchEnvironment()));
- connect(button, SIGNAL(clicked()), this, SLOT(stopFetchEnvironment()));
+ disconnect(button, &QPushButton::clicked,
+ this, &RemoteLinuxEnvironmentAspectWidget::fetchEnvironment);
+ connect(button, &QPushButton::clicked,
+ this, &RemoteLinuxEnvironmentAspectWidget::stopFetchEnvironment);
button->setText(tr("Cancel Fetch Operation"));
deviceEnvReader->start();
}
@@ -77,8 +81,10 @@ void RemoteLinuxEnvironmentAspectWidget::fetchEnvironment()
void RemoteLinuxEnvironmentAspectWidget::fetchEnvironmentFinished()
{
QPushButton *button = fetchButton();
- disconnect(button, SIGNAL(clicked()), this, SLOT(stopFetchEnvironment()));
- connect(button, SIGNAL(clicked()), this, SLOT(fetchEnvironment()));
+ disconnect(button, &QPushButton::clicked,
+ this, &RemoteLinuxEnvironmentAspectWidget::stopFetchEnvironment);
+ connect(button, &QPushButton::clicked,
+ this, &RemoteLinuxEnvironmentAspectWidget::fetchEnvironment);
button->setText(FetchEnvButtonText);
aspect()->setRemoteEnvironment(deviceEnvReader->remoteEnvironment());
}
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp b/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
index 4e065f7da9e..834300a17d9 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
+++ b/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
@@ -58,8 +58,10 @@ void RemoteLinuxEnvironmentReader::start()
return;
m_stop = false;
m_deviceProcess = device->createProcess(this);
- connect(m_deviceProcess, SIGNAL(error(QProcess::ProcessError)), SLOT(handleError()));
- connect(m_deviceProcess, SIGNAL(finished()), SLOT(remoteProcessFinished()));
+ connect(m_deviceProcess, &DeviceProcess::error,
+ this, &RemoteLinuxEnvironmentReader::handleError);
+ connect(m_deviceProcess, &DeviceProcess::finished,
+ this, &RemoteLinuxEnvironmentReader::remoteProcessFinished);
m_deviceProcess->start(QLatin1String("env"));
}
diff --git a/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp b/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp
index f3cb49c0a6d..2146d4f3655 100644
--- a/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp
+++ b/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp
@@ -45,8 +45,8 @@ public:
bool isRunning;
IDevice::ConstPtr deviceConfig;
- QSsh::SshRemoteProcessRunner *installer;
- QSsh::SshRemoteProcessRunner *killProcess;
+ SshRemoteProcessRunner *installer;
+ SshRemoteProcessRunner *killProcess;
};
} // namespace Internal
@@ -70,10 +70,14 @@ void AbstractRemoteLinuxPackageInstaller::installPackage(const IDevice::ConstPtr
prepareInstallation();
if (!d->installer)
d->installer = new SshRemoteProcessRunner(this);
- connect(d->installer, SIGNAL(connectionError()), SLOT(handleConnectionError()));
- connect(d->installer, SIGNAL(readyReadStandardOutput()), SLOT(handleInstallerOutput()));
- connect(d->installer, SIGNAL(readyReadStandardError()), SLOT(handleInstallerErrorOutput()));
- connect(d->installer, SIGNAL(processClosed(int)), SLOT(handleInstallationFinished(int)));
+ connect(d->installer, &SshRemoteProcessRunner::connectionError,
+ this, &AbstractRemoteLinuxPackageInstaller::handleConnectionError);
+ connect(d->installer, &SshRemoteProcessRunner::readyReadStandardOutput,
+ this, &AbstractRemoteLinuxPackageInstaller::handleInstallerOutput);
+ connect(d->installer, &SshRemoteProcessRunner::readyReadStandardError,
+ this, &AbstractRemoteLinuxPackageInstaller::handleInstallerErrorOutput);
+ connect(d->installer, &SshRemoteProcessRunner::processClosed,
+ this, &AbstractRemoteLinuxPackageInstaller::handleInstallationFinished);
QString cmdLine = installCommandLine(packageFilePath);
if (removePackageFile)
diff --git a/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp b/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
index a7e10c7a07f..38a08e9af24 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
+++ b/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
@@ -90,7 +90,7 @@ RemoteLinuxRunConfiguration::RemoteLinuxRunConfiguration(Target *parent, Core::I
init();
}
-RemoteLinuxRunConfiguration::RemoteLinuxRunConfiguration(ProjectExplorer::Target *parent,
+RemoteLinuxRunConfiguration::RemoteLinuxRunConfiguration(Target *parent,
RemoteLinuxRunConfiguration *source)
: AbstractRemoteLinuxRunConfiguration(parent, source),
d(new RemoteLinuxRunConfigurationPrivate(source->d))
diff --git a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
index f90a02c158e..a6f4fea7da3 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
+++ b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
@@ -88,8 +88,8 @@ RemoteLinuxRunConfigurationWidget::RemoteLinuxRunConfigurationWidget(RemoteLinux
mainLayout->setMargin(0);
addGenericWidgets(mainLayout);
- connect(d->runConfiguration, SIGNAL(enabledChanged()),
- SLOT(runConfigurationEnabledChange()));
+ connect(d->runConfiguration, &RemoteLinuxRunConfiguration::enabledChanged,
+ this, &RemoteLinuxRunConfigurationWidget::runConfigurationEnabledChange);
runConfigurationEnabledChange();
}
@@ -157,16 +157,18 @@ void RemoteLinuxRunConfigurationWidget::addGenericWidgets(QVBoxLayout *mainLayou
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->runConfiguration, SIGNAL(deploySpecsChanged()), SLOT(handleDeploySpecsChanged()));
- connect(&d->useAlternateCommandBox, SIGNAL(toggled(bool)),
- SLOT(handleUseAlternateCommandChanged()));
- connect(&d->alternateCommand, SIGNAL(textEdited(QString)),
- SLOT(handleAlternateCommandChanged()));
- connect(&d->workingDirLineEdit, SIGNAL(textEdited(QString)),
- SLOT(handleWorkingDirectoryChanged()));
+ connect(&d->argsLineEdit, &QLineEdit::textEdited,
+ this, &RemoteLinuxRunConfigurationWidget::argumentsEdited);
+ connect(d->runConfiguration, &RemoteLinuxRunConfiguration::targetInformationChanged,
+ this, &RemoteLinuxRunConfigurationWidget::updateTargetInformation);
+ connect(d->runConfiguration, &RemoteLinuxRunConfiguration::deploySpecsChanged,
+ this, &RemoteLinuxRunConfigurationWidget::handleDeploySpecsChanged);
+ connect(&d->useAlternateCommandBox, &QCheckBox::toggled,
+ this, &RemoteLinuxRunConfigurationWidget::handleUseAlternateCommandChanged);
+ connect(&d->alternateCommand, &QLineEdit::textEdited,
+ this, &RemoteLinuxRunConfigurationWidget::handleAlternateCommandChanged);
+ connect(&d->workingDirLineEdit, &QLineEdit::textEdited,
+ this, &RemoteLinuxRunConfigurationWidget::handleWorkingDirectoryChanged);
handleDeploySpecsChanged();
handleUseAlternateCommandChanged();
}
diff --git a/src/plugins/remotelinux/remotelinuxruncontrol.cpp b/src/plugins/remotelinux/remotelinuxruncontrol.cpp
index 3259f63ffb5..4d359f82673 100644
--- a/src/plugins/remotelinux/remotelinuxruncontrol.cpp
+++ b/src/plugins/remotelinux/remotelinuxruncontrol.cpp
@@ -48,7 +48,7 @@ class RemoteLinuxRunControl::RemoteLinuxRunControlPrivate
{
public:
bool running;
- ProjectExplorer::DeviceApplicationRunner runner;
+ DeviceApplicationRunner runner;
IDevice::ConstPtr device;
QString remoteExecutable;
QStringList arguments;
@@ -57,7 +57,7 @@ public:
};
RemoteLinuxRunControl::RemoteLinuxRunControl(RunConfiguration *rc)
- : RunControl(rc, ProjectExplorer::NormalRunMode), d(new RemoteLinuxRunControlPrivate)
+ : RunControl(rc, NormalRunMode), d(new RemoteLinuxRunControlPrivate)
{
setIcon(QLatin1String(ProjectExplorer::Constants::ICON_RUN_SMALL));
@@ -80,12 +80,16 @@ void RemoteLinuxRunControl::start()
d->running = true;
emit started();
d->runner.disconnect(this);
- connect(&d->runner, SIGNAL(reportError(QString)), SLOT(handleErrorMessage(QString)));
- connect(&d->runner, SIGNAL(remoteStderr(QByteArray)),
- SLOT(handleRemoteErrorOutput(QByteArray)));
- 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)));
+ connect(&d->runner, &DeviceApplicationRunner::reportError,
+ this, &RemoteLinuxRunControl::handleErrorMessage);
+ connect(&d->runner, &DeviceApplicationRunner::remoteStderr,
+ this, &RemoteLinuxRunControl::handleRemoteErrorOutput);
+ connect(&d->runner, &DeviceApplicationRunner::remoteStdout,
+ this, &RemoteLinuxRunControl::handleRemoteOutput);
+ connect(&d->runner, &DeviceApplicationRunner::finished,
+ this, &RemoteLinuxRunControl::handleRunnerFinished);
+ connect(&d->runner, &DeviceApplicationRunner::reportProgress,
+ this, &RemoteLinuxRunControl::handleProgressReport);
d->runner.setEnvironment(d->environment);
d->runner.setWorkingDirectory(d->workingDir);
d->runner.start(d->device, d->remoteExecutable, d->arguments);
diff --git a/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp b/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp
index 69f7569e276..4295c39a75e 100644
--- a/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp
+++ b/src/plugins/remotelinux/remotelinuxruncontrolfactory.cpp
@@ -104,14 +104,15 @@ RunControl *RemoteLinuxRunControlFactory::create(RunConfiguration *runConfig, Ru
}
DebuggerStartParameters params = LinuxDeviceDebugSupport::startParameters(rc);
- if (mode == ProjectExplorer::DebugRunModeWithBreakOnMain)
+ if (mode == DebugRunModeWithBreakOnMain)
params.breakOnMain = true;
+ params.runConfiguration = rc;
DebuggerRunControl * const runControl
- = DebuggerRunControlFactory::doCreate(params, rc, errorMessage);
+ = DebuggerRunControlFactory::doCreate(params, errorMessage);
if (!runControl)
return 0;
LinuxDeviceDebugSupport * const debugSupport =
- new LinuxDeviceDebugSupport(rc, runControl->engine());
+ new LinuxDeviceDebugSupport(rc, runControl);
connect(runControl, SIGNAL(finished()), debugSupport, SLOT(handleDebuggingFinished()));
return runControl;
}
@@ -126,6 +127,7 @@ RunControl *RemoteLinuxRunControlFactory::create(RunConfiguration *runConfig, Ru
case NoRunMode:
case CallgrindRunMode:
case MemcheckRunMode:
+ case MemcheckWithGdbRunMode:
case ClangStaticAnalyzerMode:
QTC_ASSERT(false, return 0);
}
diff --git a/src/plugins/remotelinux/remotelinuxsignaloperation.cpp b/src/plugins/remotelinux/remotelinuxsignaloperation.cpp
index 1c06912fb89..7bd39f57165 100644
--- a/src/plugins/remotelinux/remotelinuxsignaloperation.cpp
+++ b/src/plugins/remotelinux/remotelinuxsignaloperation.cpp
@@ -47,8 +47,10 @@ RemoteLinuxSignalOperation::RemoteLinuxSignalOperation(
RemoteLinuxSignalOperation::~RemoteLinuxSignalOperation()
{
if (m_runner) {
- connect(m_runner, SIGNAL(processClosed(int)), m_runner, SLOT(deleteLater()));
- connect(m_runner, SIGNAL(connectionError()), m_runner, SLOT(deleteLater()));
+ connect(m_runner, &QSsh::SshRemoteProcessRunner::processClosed,
+ m_runner, &QSsh::SshRemoteProcessRunner::deleteLater);
+ connect(m_runner, &QSsh::SshRemoteProcessRunner::connectionError,
+ m_runner, &QSsh::SshRemoteProcessRunner::deleteLater);
}
}
diff --git a/src/plugins/remotelinux/sshkeydeployer.cpp b/src/plugins/remotelinux/sshkeydeployer.cpp
index 4fbfe64f461..e452ffb5c60 100644
--- a/src/plugins/remotelinux/sshkeydeployer.cpp
+++ b/src/plugins/remotelinux/sshkeydeployer.cpp
@@ -67,8 +67,10 @@ void SshKeyDeployer::deployPublicKey(const SshConnectionParameters &sshParams,
return;
}
- connect(&d->deployProcess, SIGNAL(connectionError()), SLOT(handleConnectionFailure()));
- connect(&d->deployProcess, SIGNAL(processClosed(int)), SLOT(handleKeyUploadFinished(int)));
+ connect(&d->deployProcess, &SshRemoteProcessRunner::connectionError,
+ this, &SshKeyDeployer::handleConnectionFailure);
+ connect(&d->deployProcess, &SshRemoteProcessRunner::processClosed,
+ this, &SshKeyDeployer::handleKeyUploadFinished);
const QByteArray command = "test -d .ssh "
"|| mkdir .ssh && chmod 0700 .ssh && echo '"
+ reader.data() + "' >> .ssh/authorized_keys && chmod 0600 .ssh/authorized_keys";
diff --git a/src/plugins/remotelinux/typespecificdeviceconfigurationlistmodel.cpp b/src/plugins/remotelinux/typespecificdeviceconfigurationlistmodel.cpp
index b96d3661ac0..f2069538343 100644
--- a/src/plugins/remotelinux/typespecificdeviceconfigurationlistmodel.cpp
+++ b/src/plugins/remotelinux/typespecificdeviceconfigurationlistmodel.cpp
@@ -131,7 +131,7 @@ bool TypeSpecificDeviceConfigurationListModel::deviceMatches(IDevice::ConstPtr d
{
if (dev.isNull())
return false;
- Core::Id typeId = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target()->kit());
+ Core::Id typeId = DeviceTypeKitInformation::deviceTypeId(target()->kit());
return dev->type() == typeId;
}
diff --git a/src/plugins/resourceeditor/qrceditor/qrceditor.cpp b/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
index 0100487cfc6..2fa4aa6ec05 100644
--- a/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
+++ b/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
@@ -313,7 +313,7 @@ void QrcEditor::resolveLocationIssues(QStringList &files)
if (clickedButton == context.copyButton) {
const QFileInfo fi(file);
QFileInfo suggestion;
- QDir tmpTarget(dir.path() + QDir::separator() + QLatin1String("Resources"));
+ QDir tmpTarget(dir.path() + QLatin1Char('/') + QLatin1String("Resources"));
if (tmpTarget.exists())
suggestion.setFile(tmpTarget, fi.fileName());
else
diff --git a/src/plugins/resourceeditor/qrceditor/resourcefile.cpp b/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
index cd926dbb8f6..1f32ca276ee 100644
--- a/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
+++ b/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
@@ -204,7 +204,7 @@ QString ResourceFile::contents() const
const File &file = *f;
QDomElement felt = doc.createElement(QLatin1String("file"));
relt.appendChild(felt);
- const QString conv_file = relativePath(file.name).replace(QDir::separator(), QLatin1Char('/'));
+ const QString conv_file = QDir::fromNativeSeparators(relativePath(file.name));
const QDomText text = doc.createTextNode(conv_file);
felt.appendChild(text);
if (!file.alias.isEmpty())
@@ -329,6 +329,7 @@ bool ResourceFile::replacePrefixAndLang(int prefix_idx, const QString &prefix, c
Q_ASSERT(prefix_idx >= 0 && prefix_idx < m_prefix_list.count());
m_prefix_list[prefix_idx]->name = fixed_prefix;
+ m_prefix_list[prefix_idx]->lang = lang;
return true;
}
@@ -427,7 +428,7 @@ QString ResourceFile::absolutePath(const QString &rel_path) const
return rel_path;
QString rc = QFileInfo(m_file_name).path();
- rc += QDir::separator();
+ rc += QLatin1Char('/');
rc += rel_path;
return QDir::cleanPath(rc);
}
diff --git a/src/plugins/resourceeditor/resourceeditorconstants.h b/src/plugins/resourceeditor/resourceeditorconstants.h
index b6bb62ea367..30209855d6c 100644
--- a/src/plugins/resourceeditor/resourceeditorconstants.h
+++ b/src/plugins/resourceeditor/resourceeditorconstants.h
@@ -50,7 +50,6 @@ const char C_REMOVE_FILE[] = "ResourceEditor.RemoveFile";
const char C_RENAME_FILE[] = "ResourceEditor.RenameFile";
const char C_OPEN_EDITOR[] = "ResourceEditor.OpenEditor";
-const char C_OPEN_TEXT_EDITOR[] = "ResourceEditor.OpenTextEditor";
const char C_COPY_PATH[] = "ResourceEditor.CopyPath";
const char C_COPY_URL[] = "ResourceEditor.CopyUrl";
diff --git a/src/plugins/resourceeditor/resourceeditorfactory.cpp b/src/plugins/resourceeditor/resourceeditorfactory.cpp
index b21c7907100..d6c63107a1b 100644
--- a/src/plugins/resourceeditor/resourceeditorfactory.cpp
+++ b/src/plugins/resourceeditor/resourceeditorfactory.cpp
@@ -56,6 +56,6 @@ ResourceEditorFactory::ResourceEditorFactory(ResourceEditorPlugin *plugin) :
Core::IEditor *ResourceEditorFactory::createEditor()
{
- Core::Context context(ResourceEditor::Constants::C_RESOURCEEDITOR);
+ Core::Context context(C_RESOURCEEDITOR);
return new ResourceEditorW(context, m_plugin);
}
diff --git a/src/plugins/resourceeditor/resourceeditorplugin.cpp b/src/plugins/resourceeditor/resourceeditorplugin.cpp
index 93ecef0e5a6..2b92b1f3092 100644
--- a/src/plugins/resourceeditor/resourceeditorplugin.cpp
+++ b/src/plugins/resourceeditor/resourceeditorplugin.cpp
@@ -38,12 +38,14 @@
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/coreconstants.h>
+#include <coreplugin/documentmanager.h>
#include <coreplugin/id.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectnodes.h>
#include <extensionsystem/pluginmanager.h>
@@ -179,10 +181,12 @@ bool ResourceEditorPlugin::initialize(const QStringList &arguments, QString *err
folderContextMenu->addAction(command, ProjectExplorer::Constants::G_FOLDER_FILES);
connect(m_openInEditor, SIGNAL(triggered()), this, SLOT(openEditorContextMenu()));
- m_openInTextEditor = new QAction(tr("Open in Text Editor"), this);
- command = Core::ActionManager::registerAction(m_openInTextEditor, Constants::C_OPEN_TEXT_EDITOR, projectTreeContext);
- folderContextMenu->addAction(command, ProjectExplorer::Constants::G_FOLDER_FILES);
- connect(m_openInTextEditor, SIGNAL(triggered()), this, SLOT(openTextEditorContextMenu()));
+ m_openWithMenu = new QMenu(tr("Open With"), folderContextMenu->menu());
+ folderContextMenu->menu()->insertMenu(
+ folderContextMenu->insertLocation(ProjectExplorer::Constants::G_FOLDER_FILES),
+ m_openWithMenu);
+ connect(m_openWithMenu, &QMenu::triggered,
+ Core::DocumentManager::instance(), &Core::DocumentManager::executeOpenWithMenuAction);
m_copyPath = new Utils::ParameterAction(QString(), tr("Copy path \"%1\""), Utils::ParameterAction::AlwaysEnabled, this);
command = Core::ActionManager::registerAction(m_copyPath, Constants::C_COPY_PATH, projectTreeContext);
@@ -202,9 +206,8 @@ bool ResourceEditorPlugin::initialize(const QStringList &arguments, QString *err
m_renameResourceFile->setEnabled(false);
m_removeResourceFile->setEnabled(false);
- connect(ProjectExplorer::ProjectExplorerPlugin::instance(), SIGNAL(currentNodeChanged(ProjectExplorer::Node*,ProjectExplorer::Project*)),
- this, SLOT(updateContextActions(ProjectExplorer::Node*,ProjectExplorer::Project*)));
-
+ connect(ProjectTree::instance(), &ProjectTree::currentNodeChanged,
+ this, &ResourceEditorPlugin::updateContextActions);
return true;
}
@@ -236,13 +239,13 @@ void ResourceEditorPlugin::addPrefixContextMenu()
QString prefix = dialog.prefix();
if (prefix.isEmpty())
return;
- ResourceTopLevelNode *topLevel = static_cast<ResourceTopLevelNode *>(ProjectExplorer::ProjectExplorerPlugin::currentNode());
+ ResourceTopLevelNode *topLevel = static_cast<ResourceTopLevelNode *>(ProjectTree::currentNode());
topLevel->addPrefix(prefix, dialog.lang());
}
void ResourceEditorPlugin::removePrefixContextMenu()
{
- ResourceFolderNode *rfn = static_cast<ResourceFolderNode *>(ProjectExplorer::ProjectExplorerPlugin::instance()->currentNode());
+ ResourceFolderNode *rfn = static_cast<ResourceFolderNode *>(ProjectTree::currentNode());
if (QMessageBox::question(Core::ICore::mainWindow(),
tr("Remove Prefix"),
tr("Remove prefix %1 and all its files?").arg(rfn->displayName()))
@@ -259,9 +262,9 @@ void ResourceEditorPlugin::renameFileContextMenu()
void ResourceEditorPlugin::removeFileContextMenu()
{
- ResourceFolderNode *rfn = static_cast<ResourceFolderNode *>(ProjectExplorer::ProjectExplorerPlugin::instance()->currentNode());
+ ResourceFolderNode *rfn = static_cast<ResourceFolderNode *>(ProjectTree::currentNode());
QString path = rfn->path();
- ProjectExplorer::FolderNode *parent = rfn->parentFolderNode();
+ FolderNode *parent = rfn->parentFolderNode();
if (!parent->removeFiles(QStringList() << path))
QMessageBox::warning(Core::ICore::mainWindow(),
tr("File Removal Failed"),
@@ -270,33 +273,24 @@ void ResourceEditorPlugin::removeFileContextMenu()
void ResourceEditorPlugin::openEditorContextMenu()
{
- ResourceTopLevelNode *topLevel = static_cast<ResourceTopLevelNode *>(ProjectExplorer::ProjectExplorerPlugin::instance()->currentNode());
- QString path = topLevel->path();
- Core::EditorManager::openEditor(path);
-}
-
-void ResourceEditorPlugin::openTextEditorContextMenu()
-{
- ResourceTopLevelNode *topLevel = static_cast<ResourceTopLevelNode *>(ProjectExplorerPlugin::currentNode());
- QString path = topLevel->path();
- Core::EditorManager::openEditor(path, Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
+ Core::EditorManager::openEditor(ProjectTree::currentNode()->path());
}
void ResourceEditorPlugin::copyPathContextMenu()
{
- ResourceFileNode *node = static_cast<ResourceFileNode *>(ProjectExplorerPlugin::currentNode());
+ ResourceFileNode *node = static_cast<ResourceFileNode *>(ProjectTree::currentNode());
QApplication::clipboard()->setText(QLatin1String(resourcePrefix) + node->qrcPath());
}
void ResourceEditorPlugin::copyUrlContextMenu()
{
- ResourceFileNode *node = static_cast<ResourceFileNode *>(ProjectExplorerPlugin::currentNode());
+ ResourceFileNode *node = static_cast<ResourceFileNode *>(ProjectTree::currentNode());
QApplication::clipboard()->setText(QLatin1String(urlPrefix) + node->qrcPath());
}
void ResourceEditorPlugin::renamePrefixContextMenu()
{
- ResourceFolderNode *node = static_cast<ResourceFolderNode *>(ProjectExplorerPlugin::currentNode());
+ ResourceFolderNode *node = static_cast<ResourceFolderNode *>(ProjectTree::currentNode());
PrefixLangDialog dialog(tr("Rename Prefix"), node->prefix(), node->lang(), Core::ICore::mainWindow());
if (dialog.exec() != QDialog::Accepted)
@@ -308,9 +302,9 @@ void ResourceEditorPlugin::renamePrefixContextMenu()
node->renamePrefix(prefix, dialog.lang());
}
-void ResourceEditorPlugin::updateContextActions(ProjectExplorer::Node *node, ProjectExplorer::Project *)
+void ResourceEditorPlugin::updateContextActions(Node *node, Project *)
{
- bool isResourceNode = qobject_cast<ResourceTopLevelNode *>(node);
+ bool isResourceNode = dynamic_cast<ResourceTopLevelNode *>(node);
m_addPrefix->setEnabled(isResourceNode);
m_addPrefix->setVisible(isResourceNode);
@@ -318,9 +312,9 @@ void ResourceEditorPlugin::updateContextActions(ProjectExplorer::Node *node, Pro
bool enableRemove = false;
if (isResourceNode) {
- ProjectExplorer::FolderNode *parent = node ? node->parentFolderNode() : 0;
- enableRename = parent && parent->supportedActions(node).contains(ProjectExplorer::Rename);
- enableRemove = parent && parent->supportedActions(node).contains(ProjectExplorer::RemoveFile);
+ FolderNode *parent = node ? node->parentFolderNode() : 0;
+ enableRename = parent && parent->supportedActions(node).contains(Rename);
+ enableRemove = parent && parent->supportedActions(node).contains(RemoveFile);
}
m_renameResourceFile->setEnabled(isResourceNode && enableRename);
@@ -331,17 +325,20 @@ void ResourceEditorPlugin::updateContextActions(ProjectExplorer::Node *node, Pro
m_openInEditor->setEnabled(isResourceNode);
m_openInEditor->setVisible(isResourceNode);
- m_openInTextEditor->setEnabled(isResourceNode);
- m_openInTextEditor->setVisible(isResourceNode);
-
- bool isResourceFolder = qobject_cast<ResourceFolderNode *>(node);
+ bool isResourceFolder = dynamic_cast<ResourceFolderNode *>(node);
m_removePrefix->setEnabled(isResourceFolder);
m_removePrefix->setVisible(isResourceFolder);
m_renamePrefix->setEnabled(isResourceFolder);
m_renamePrefix->setVisible(isResourceFolder);
- bool isResourceFile = qobject_cast<ResourceFileNode *>(node);
+ if (isResourceNode)
+ Core::DocumentManager::populateOpenWithMenu(m_openWithMenu, node->path());
+ else
+ m_openWithMenu->clear();
+ m_openWithMenu->menuAction()->setVisible(!m_openWithMenu->actions().isEmpty());
+
+ bool isResourceFile = dynamic_cast<ResourceFileNode *>(node);
m_copyPath->setEnabled(isResourceFile);
m_copyPath->setVisible(isResourceFile);
m_copyUrl->setEnabled(isResourceFile);
diff --git a/src/plugins/resourceeditor/resourceeditorplugin.h b/src/plugins/resourceeditor/resourceeditorplugin.h
index 7611e3b8b7d..44c5a84717a 100644
--- a/src/plugins/resourceeditor/resourceeditorplugin.h
+++ b/src/plugins/resourceeditor/resourceeditorplugin.h
@@ -35,6 +35,7 @@
QT_BEGIN_NAMESPACE
class QAction;
+class QMenu;
QT_END_NAMESPACE
namespace ProjectExplorer {
@@ -75,7 +76,6 @@ private slots:
void removeFileContextMenu();
void openEditorContextMenu();
- void openTextEditorContextMenu();
void copyPathContextMenu();
void copyUrlContextMenu();
@@ -102,7 +102,7 @@ private:
QAction *m_removeResourceFile;
QAction *m_openInEditor;
- QAction *m_openInTextEditor;
+ QMenu *m_openWithMenu;
// file context menu
Utils::ParameterAction *m_copyPath;
diff --git a/src/plugins/resourceeditor/resourceeditorw.cpp b/src/plugins/resourceeditor/resourceeditorw.cpp
index a4e68e297db..247914a6eae 100644
--- a/src/plugins/resourceeditor/resourceeditorw.cpp
+++ b/src/plugins/resourceeditor/resourceeditorw.cpp
@@ -54,6 +54,8 @@
#include <QInputDialog>
#include <QClipboard>
+using namespace Utils;
+
namespace ResourceEditor {
namespace Internal {
@@ -68,7 +70,7 @@ ResourceEditorDocument::ResourceEditorDocument(ResourceEditorW *parent) :
{
setId(ResourceEditor::Constants::RESOURCEEDITOR_ID);
setMimeType(QLatin1String(ResourceEditor::Constants::C_RESOURCE_MIMETYPE));
- setFilePath(parent->m_resourceEditor->fileName());
+ setFilePath(FileName::fromString(parent->m_resourceEditor->fileName()));
if (debugResourceEditorW)
qDebug() << "ResourceEditorFile::ResourceEditorFile()";
}
@@ -145,7 +147,7 @@ bool ResourceEditorW::open(QString *errorString, const QString &fileName, const
return false;
}
- m_resourceDocument->setFilePath(fileName);
+ m_resourceDocument->setFilePath(FileName::fromString(fileName));
m_resourceDocument->setBlockDirtyChanged(false);
m_resourceEditor->setDirty(fileName != realFileName);
m_shouldAutoSave = false;
@@ -158,23 +160,23 @@ bool ResourceEditorDocument::save(QString *errorString, const QString &name, boo
if (debugResourceEditorW)
qDebug(">ResourceEditorW::save: %s", qPrintable(name));
- const QString oldFileName = filePath();
- const QString actualName = name.isEmpty() ? oldFileName : name;
+ const FileName oldFileName = filePath();
+ const FileName actualName = name.isEmpty() ? oldFileName : FileName::fromString(name);
if (actualName.isEmpty())
return false;
m_blockDirtyChanged = true;
- m_parent->m_resourceEditor->setFileName(actualName);
+ m_parent->m_resourceEditor->setFileName(actualName.toString());
if (!m_parent->m_resourceEditor->save()) {
*errorString = m_parent->m_resourceEditor->errorMessage();
- m_parent->m_resourceEditor->setFileName(oldFileName);
+ m_parent->m_resourceEditor->setFileName(oldFileName.toString());
m_blockDirtyChanged = false;
return false;
}
m_parent->m_shouldAutoSave = false;
if (autoSave) {
- m_parent->m_resourceEditor->setFileName(oldFileName);
+ m_parent->m_resourceEditor->setFileName(oldFileName.toString());
m_parent->m_resourceEditor->setDirty(true);
m_blockDirtyChanged = false;
return true;
@@ -194,7 +196,7 @@ QString ResourceEditorDocument::plainText() const
bool ResourceEditorDocument::setContents(const QByteArray &contents)
{
- Utils::TempFileSaver saver;
+ TempFileSaver saver;
saver.write(contents);
if (!saver.finalize(Core::ICore::mainWindow()))
return false;
@@ -206,10 +208,10 @@ bool ResourceEditorDocument::setContents(const QByteArray &contents)
return rc;
}
-void ResourceEditorDocument::setFilePath(const QString &newName)
+void ResourceEditorDocument::setFilePath(const FileName &newName)
{
- if (newName != m_parent->m_resourceEditor->fileName())
- m_parent->m_resourceEditor->setFileName(newName);
+ if (newName.toString() != m_parent->m_resourceEditor->fileName())
+ m_parent->m_resourceEditor->setFileName(newName.toString());
IDocument::setFilePath(newName);
}
@@ -246,7 +248,7 @@ bool ResourceEditorDocument::reload(QString *errorString, ReloadFlag flag, Chang
emit changed();
} else {
emit aboutToReload();
- QString fn = filePath();
+ QString fn = filePath().toString();
const bool success = m_parent->open(errorString, fn, fn);
emit reloadFinished(success);
return success;
diff --git a/src/plugins/resourceeditor/resourceeditorw.h b/src/plugins/resourceeditor/resourceeditorw.h
index 60c9cb68576..fea5e2a3de3 100644
--- a/src/plugins/resourceeditor/resourceeditorw.h
+++ b/src/plugins/resourceeditor/resourceeditorw.h
@@ -65,7 +65,7 @@ public:
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
QString defaultPath() const;
QString suggestedFileName() const;
- void setFilePath(const QString &newName);
+ void setFilePath(const Utils::FileName &newName);
void setBlockDirtyChanged(bool value);
public slots:
diff --git a/src/plugins/resourceeditor/resourcenode.cpp b/src/plugins/resourceeditor/resourcenode.cpp
index e8d3f8d2c51..ca15ac51bae 100644
--- a/src/plugins/resourceeditor/resourcenode.cpp
+++ b/src/plugins/resourceeditor/resourcenode.cpp
@@ -40,6 +40,7 @@
#include <qmljstools/qmljstoolsconstants.h>
+#include <QCoreApplication>
#include <QDir>
#include <QDebug>
@@ -126,6 +127,7 @@ ResourceTopLevelNode::ResourceTopLevelNode(const QString &filePath, FolderNode *
ResourceTopLevelNode::~ResourceTopLevelNode()
{
Core::DocumentManager::removeDocument(m_document);
+ delete m_document;
}
void ResourceTopLevelNode::update()
@@ -253,8 +255,8 @@ bool ResourceTopLevelNode::removePrefix(const QString &prefix, const QString &la
ProjectExplorer::FolderNode::AddNewInformation ResourceTopLevelNode::addNewInformation(const QStringList &files, Node *context) const
{
- QString name = tr("%1 Prefix: %2")
- .arg(QFileInfo(path()).fileName())
+ QString name = QCoreApplication::translate("ResourceTopLevelNode", "%1 Prefix: %2")
+ .arg(Utils::FileName::fromString(path()).fileName())
.arg(QLatin1Char('/'));
int p = -1;
@@ -267,7 +269,7 @@ ProjectExplorer::FolderNode::AddNewInformation ResourceTopLevelNode::addNewInfor
// The ResourceFolderNode '/' defers to us, as otherwise
// two nodes would be responsible for '/'
// Thus also return a high priority for it
- if (ResourceFolderNode *rfn = qobject_cast<ResourceFolderNode *>(context))
+ if (ResourceFolderNode *rfn = dynamic_cast<ResourceFolderNode *>(context))
if (rfn->prefix() == QLatin1String("/") && rfn->parentFolderNode() == this)
p = 120;
}
@@ -387,8 +389,8 @@ bool ResourceFolderNode::renamePrefix(const QString &prefix, const QString &lang
ProjectExplorer::FolderNode::AddNewInformation ResourceFolderNode::addNewInformation(const QStringList &files, Node *context) const
{
- QString name = tr("%1 Prefix: %2")
- .arg(QFileInfo(m_topLevelNode->path()).fileName())
+ QString name = QCoreApplication::translate("ResourceTopLevelNode", "%1 Prefix: %2")
+ .arg(Utils::FileName::fromString(m_topLevelNode->path()).fileName())
.arg(displayName());
int p = -1; // never the default
@@ -441,11 +443,11 @@ void ResourceFolderNode::updateFiles(QList<ProjectExplorer::FileNode *> newList)
}
ResourceFileWatcher::ResourceFileWatcher(ResourceTopLevelNode *node)
- : IDocument(node), m_node(node)
+ : IDocument(0), m_node(node)
{
setId("ResourceNodeWatcher");
setMimeType(QLatin1String(ResourceEditor::Constants::C_RESOURCE_MIMETYPE));
- setFilePath(node->path());
+ setFilePath(Utils::FileName::fromString(node->path()));
}
bool ResourceFileWatcher::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -495,7 +497,6 @@ bool ResourceFileWatcher::reload(QString *errorString, ReloadFlag flag, ChangeTy
ResourceFileNode::ResourceFileNode(const QString &filePath, const QString &qrcPath, ResourceTopLevelNode *topLevel)
: ProjectExplorer::FileNode(filePath, ProjectExplorer::UnknownFileType, false),
- m_topLevel(topLevel),
m_qrcPath(qrcPath)
{
diff --git a/src/plugins/resourceeditor/resourcenode.h b/src/plugins/resourceeditor/resourcenode.h
index 690848c2de8..7baf92f7aad 100644
--- a/src/plugins/resourceeditor/resourcenode.h
+++ b/src/plugins/resourceeditor/resourcenode.h
@@ -44,7 +44,6 @@ namespace Internal { class ResourceFileWatcher; }
class RESOURCE_EXPORT ResourceTopLevelNode : public ProjectExplorer::FolderNode
{
- Q_OBJECT
public:
ResourceTopLevelNode(const QString &filePath, FolderNode *parent);
~ResourceTopLevelNode();
@@ -54,9 +53,6 @@ public:
bool addFiles(const QStringList &filePaths, QStringList *notAdded);
bool removeFiles(const QStringList &filePaths, QStringList *notRemoved);
- bool addFiles(const QString &prefix, const QString &lang, const QStringList &filePaths, QStringList *notAdded);
- bool removeFiles(const QString &prefix, const QString &lang,const QStringList &filePaths, QStringList *notRemoved);
-
bool addPrefix(const QString &prefix, const QString &lang);
bool removePrefix(const QString &prefix, const QString &lang);
@@ -71,7 +67,6 @@ namespace Internal {
class ResourceFolderNode : public ProjectExplorer::FolderNode
{
friend class ResourceEditor::ResourceTopLevelNode; // for updateFiles
- Q_OBJECT
public:
ResourceFolderNode(const QString &prefix, const QString &lang, ResourceTopLevelNode *parent);
~ResourceFolderNode();
@@ -100,7 +95,6 @@ private:
class ResourceFileNode : public ProjectExplorer::FileNode
{
- Q_OBJECT
public:
ResourceFileNode(const QString &filePath, const QString &qrcPath, ResourceTopLevelNode *topLevel);
@@ -109,7 +103,6 @@ public:
QList<ProjectExplorer::ProjectAction> supportedActions(Node *node) const;
private:
- ResourceTopLevelNode *m_topLevel;
QString m_displayName;
QString m_qrcPath;
};
diff --git a/src/plugins/subversion/checkoutwizard.cpp b/src/plugins/subversion/checkoutwizard.cpp
index 19f5e1a2476..c7b655d65ad 100644
--- a/src/plugins/subversion/checkoutwizard.cpp
+++ b/src/plugins/subversion/checkoutwizard.cpp
@@ -37,7 +37,7 @@
#include <coreplugin/iversioncontrol.h>
#include <vcsbase/vcscommand.h>
#include <vcsbase/vcsbaseconstants.h>
-#include <vcsbase/vcsconfigurationpage.h>
+#include <vcsbase/wizard/vcsconfigurationpage.h>
#include <utils/qtcassert.h>
using namespace Utils;
@@ -54,9 +54,12 @@ CheckoutWizard::CheckoutWizard(const FileName &path, QWidget *parent) :
BaseCheckoutWizard(path, parent)
{
const Core::IVersionControl *vc = SubversionPlugin::instance()->versionControl();
- if (!vc->isConfigured())
- addPage(new VcsConfigurationPage(vc));
- CheckoutWizardPage *cwp = new CheckoutWizardPage;
+ if (!vc->isConfigured()) {
+ auto configPage = new VcsConfigurationPage;
+ configPage->setVersionControl(vc);
+ addPage(configPage);
+ }
+ auto cwp = new CheckoutWizardPage;
cwp->setPath(path.toString());
addPage(cwp);
}
@@ -84,8 +87,8 @@ VcsCommand *CheckoutWizard::createCommand(FileName *checkoutDir)
const QString workingDirectory = cwp->path();
*checkoutDir = FileName::fromString(workingDirectory + QLatin1Char('/') + directory);
- VcsCommand *command = new VcsCommand(binary, workingDirectory,
- QProcessEnvironment::systemEnvironment());
+ auto command = new VcsCommand(binary, workingDirectory,
+ QProcessEnvironment::systemEnvironment());
command->addJob(args, -1);
return command;
}
diff --git a/src/plugins/subversion/subversion.qbs b/src/plugins/subversion/subversion.qbs
index 045595618f0..dd38509ad51 100644
--- a/src/plugins/subversion/subversion.qbs
+++ b/src/plugins/subversion/subversion.qbs
@@ -7,6 +7,7 @@ QtcPlugin {
Depends { name: "Utils" }
Depends { name: "Core" }
+ Depends { name: "DiffEditor" }
Depends { name: "TextEditor" }
Depends { name: "VcsBase" }
diff --git a/src/plugins/subversion/subversion_dependencies.pri b/src/plugins/subversion/subversion_dependencies.pri
index 87e1a57ad59..57e4824984a 100644
--- a/src/plugins/subversion/subversion_dependencies.pri
+++ b/src/plugins/subversion/subversion_dependencies.pri
@@ -4,4 +4,5 @@ QTC_LIB_DEPENDS += \
QTC_PLUGIN_DEPENDS += \
texteditor \
coreplugin \
- vcsbase
+ vcsbase \
+ diffeditor
diff --git a/src/plugins/subversion/subversionclient.cpp b/src/plugins/subversion/subversionclient.cpp
index 5cf33eed039..a5985bb1617 100644
--- a/src/plugins/subversion/subversionclient.cpp
+++ b/src/plugins/subversion/subversionclient.cpp
@@ -29,14 +29,23 @@
****************************************************************************/
#include "subversionclient.h"
-#include "subversionsettings.h"
#include "subversionconstants.h"
+#include "subversionplugin.h"
+#include "subversionsettings.h"
#include <vcsbase/vcscommand.h>
-#include <vcsbase/vcsbaseplugin.h>
#include <vcsbase/vcsbaseconstants.h>
+#include <vcsbase/vcsbaseeditor.h>
#include <vcsbase/vcsbaseeditorparameterwidget.h>
+#include <vcsbase/vcsbaseplugin.h>
+#include <utils/qtcassert.h>
#include <utils/synchronousprocess.h>
+#include <diffeditor/diffeditorcontroller.h>
+#include <diffeditor/diffeditordocument.h>
+#include <diffeditor/diffeditormanager.h>
+#include <diffeditor/diffeditorreloader.h>
+#include <diffeditor/diffutils.h>
+#include <coreplugin/editormanager/editormanager.h>
#include <QDir>
#include <QFileInfo>
@@ -45,64 +54,28 @@
using namespace Utils;
using namespace VcsBase;
+using namespace Core;
namespace Subversion {
namespace Internal {
-// 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 SubversionDiffParameters
-{
- QString workingDir;
- QStringList extraOptions;
- QStringList files;
-};
-
-// Parameter widget controlling whitespace diff mode, associated with a parameter
-class SubversionDiffParameterWidget : public VcsBaseEditorParameterWidget
+class SubversionLogParameterWidget : public VcsBaseEditorParameterWidget
{
Q_OBJECT
public:
- explicit SubversionDiffParameterWidget(SubversionClient *client,
- const SubversionDiffParameters &p,
- QWidget *parent = 0);
- QStringList arguments() const;
- void executeCommand();
-
-private:
- SubversionClient *m_client;
- const SubversionDiffParameters m_params;
-};
-
-SubversionDiffParameterWidget::SubversionDiffParameterWidget(SubversionClient *client,
- const SubversionDiffParameters &p,
- QWidget *parent)
- : VcsBaseEditorParameterWidget(parent), m_client(client), m_params(p)
-{
- mapSetting(addToggleButton(QLatin1String("w"), tr("Ignore Whitespace")),
- client->settings()->boolPointer(SubversionSettings::diffIgnoreWhiteSpaceKey));
-}
-
-QStringList SubversionDiffParameterWidget::arguments() const
-{
- QStringList args;
- // Subversion wants" -x -<ext-args>", default being -u
- const QStringList formatArguments = VcsBaseEditorParameterWidget::arguments();
- if (!formatArguments.isEmpty()) {
- args << QLatin1String("-x")
- << (QLatin1String("-u") + formatArguments.join(QString()));
+ SubversionLogParameterWidget(SubversionSettings *settings, QWidget *parent = 0) :
+ VcsBaseEditorParameterWidget(parent)
+ {
+ mapSetting(addToggleButton(QLatin1String("--verbose"), tr("Verbose"),
+ tr("Show files changed in each revision")),
+ settings->boolPointer(SubversionSettings::logVerboseKey));
}
- return args;
-}
-
-void SubversionDiffParameterWidget::executeCommand()
-{
- m_client->diff(m_params.workingDir, m_params.files, m_params.extraOptions);
-}
+};
SubversionClient::SubversionClient(SubversionSettings *settings) :
VcsBaseClient(settings)
{
+ setLogParameterWidgetCreator([=] { return new SubversionLogParameterWidget(settings); });
}
SubversionSettings *SubversionClient::settings() const
@@ -141,41 +114,14 @@ void SubversionClient::commit(const QString &repositoryRoot,
cmd->execute();
}
-Core::Id SubversionClient::vcsEditorKind(VcsCommandTag cmd) const
+Id SubversionClient::vcsEditorKind(VcsCommandTag cmd) const
{
switch (cmd) {
- case DiffCommand:
- return "Subversion Diff Editor"; // TODO: create subversionconstants.h
+ case VcsBaseClient::LogCommand: return Constants::SUBVERSION_LOG_EDITOR_ID;
+ case VcsBaseClient::AnnotateCommand: return Constants::SUBVERSION_BLAME_EDITOR_ID;
default:
- return Core::Id();
- }
-}
-
-SubversionClient::Version SubversionClient::svnVersion()
-{
- if (m_svnVersionBinary != settings()->binaryPath()) {
- QStringList args;
- args << QLatin1String("--version") << QLatin1String("-q");
- const SynchronousProcessResponse response =
- VcsBasePlugin::runVcs(QDir().absolutePath(), settings()->binaryPath(),
- args, settings()->timeOutMs());
- if (response.result == SynchronousProcessResponse::Finished &&
- response.exitCode == 0) {
- m_svnVersionBinary = settings()->binaryPath();
- m_svnVersion = response.stdOut.trimmed();
- } else {
- m_svnVersionBinary.clear();
- m_svnVersion.clear();
- }
- }
-
- SubversionClient::Version v;
- if (::sscanf(m_svnVersion.toLatin1().constData(), "%d.%d.%d",
- &v.majorVersion, &v.minorVersion, &v.patchVersion) != 3) {
- v.majorVersion = v.minorVersion = v.patchVersion = -1;
+ return Id();
}
-
- return v;
}
// Add authorization options to the command line arguments.
@@ -219,14 +165,230 @@ QString SubversionClient::synchronousTopic(const QString &repository)
return QString();
}
-void SubversionClient::diff(const QString &workingDir, const QStringList &files,
- const QStringList &extraOptions)
+class SubversionDiffEditorReloader : public DiffEditor::DiffEditorReloader
+{
+ Q_OBJECT
+public:
+ SubversionDiffEditorReloader(const SubversionClient *client);
+
+ void setWorkingDirectory(const QString &workingDirectory);
+ void setFilesList(const QStringList &filesList);
+ void setChangeNumber(int changeNumber);
+
+protected:
+ void reload();
+
+private slots:
+ void slotTextualDiffOutputReceived(const QString &contents);
+
+private:
+ QString getDescription() const;
+ void postCollectTextualDiffOutput();
+ int timeout() const;
+ FileName subversionPath() const;
+ QProcessEnvironment processEnvironment() const;
+
+ const SubversionClient *m_client;
+ QString m_workingDirectory;
+ QStringList m_filesList;
+ int m_changeNumber;
+ const QString m_waitMessage;
+};
+
+SubversionDiffEditorReloader::SubversionDiffEditorReloader(const SubversionClient *client)
+ : DiffEditor::DiffEditorReloader(),
+ m_client(client),
+ m_changeNumber(0),
+ m_waitMessage(tr("Waiting for data..."))
+{
+}
+
+int SubversionDiffEditorReloader::timeout() const
{
+ return m_client->settings()->intValue(VcsBaseClientSettings::timeoutKey);
+}
+
+FileName SubversionDiffEditorReloader::subversionPath() const
+{
+ return m_client->settings()->binaryPath();
+}
+
+QProcessEnvironment SubversionDiffEditorReloader::processEnvironment() const
+{
+ return m_client->processEnvironment();
+}
+
+void SubversionDiffEditorReloader::setWorkingDirectory(const QString &workingDirectory)
+{
+ if (isReloading())
+ return;
+
+ m_workingDirectory = workingDirectory;
+}
+
+void SubversionDiffEditorReloader::setFilesList(const QStringList &filesList)
+{
+ if (isReloading())
+ return;
+
+ m_filesList = filesList;
+}
+
+void SubversionDiffEditorReloader::setChangeNumber(int changeNumber)
+{
+ if (isReloading())
+ return;
+
+ m_changeNumber = qMax(changeNumber, 0);
+}
+
+QString SubversionDiffEditorReloader::getDescription() const
+{
+ QStringList args(QLatin1String("log"));
+ args << SubversionClient::addAuthenticationOptions(*m_client->settings());
+ args << QLatin1String("-r");
+ args << QString::number(m_changeNumber);
+ const SubversionResponse logResponse =
+ SubversionPlugin::instance()->runSvn(m_workingDirectory, args,
+ m_client->settings()->timeOutMs(),
+ VcsBasePlugin::SshPasswordPrompt);
+
+ if (logResponse.error)
+ return QString();
+
+ return logResponse.stdOut;
+}
+
+void SubversionDiffEditorReloader::postCollectTextualDiffOutput()
+{
+ if (!controller())
+ return;
+
+ controller()->requestSaveState();
+ controller()->clear(m_waitMessage);
+ auto command = new VcsCommand(subversionPath(), m_workingDirectory, processEnvironment());
+ command->setCodec(EditorManager::defaultTextCodec());
+ connect(command, SIGNAL(output(QString)),
+ this, SLOT(slotTextualDiffOutputReceived(QString)));
+// command->addFlags(diffExecutionFlags());
+
QStringList args;
- args << addAuthenticationOptions(*settings());
- args.append(QLatin1String("--internal-diff"));
- args << extraOptions;
- VcsBaseClient::diff(workingDir, files, args);
+ args << QLatin1String("diff");
+ args << m_client->addAuthenticationOptions(*m_client->settings());
+ args << QLatin1String("--internal-diff");
+ if (controller()->isIgnoreWhitespace())
+ args << QLatin1String("-x") << QLatin1String("-uw");
+ if (m_changeNumber) {
+ args << QLatin1String("-r") << QString::number(m_changeNumber - 1)
+ + QLatin1String(":") + QString::number(m_changeNumber);
+ } else {
+ args << m_filesList;
+ }
+
+ command->addJob(args, timeout());
+ command->execute();
+}
+
+void SubversionDiffEditorReloader::slotTextualDiffOutputReceived(const QString &contents)
+{
+ if (!controller())
+ return;
+
+ bool ok;
+ QList<DiffEditor::FileData> fileDataList
+ = DiffEditor::DiffUtils::readPatch(contents, &ok);
+ controller()->setDiffFiles(fileDataList, m_workingDirectory);
+ controller()->requestRestoreState();
+
+ reloadFinished();
+}
+
+void SubversionDiffEditorReloader::reload()
+{
+ if (!controller())
+ return;
+
+ const QString description = m_changeNumber
+ ? getDescription() : QString();
+ postCollectTextualDiffOutput();
+ controller()->setDescription(description);
+}
+
+SubversionDiffEditorReloader *SubversionClient::findOrCreateDiffEditor(const QString &documentId,
+ const QString &source,
+ const QString &title,
+ const QString &workingDirectory) const
+{
+ DiffEditor::DiffEditorController *controller = 0;
+ SubversionDiffEditorReloader *reloader = 0;
+ DiffEditor::DiffEditorDocument *diffEditorDocument = DiffEditor::DiffEditorManager::find(documentId);
+ if (diffEditorDocument) {
+ controller = diffEditorDocument->controller();
+ reloader = static_cast<SubversionDiffEditorReloader *>(controller->reloader());
+ } else {
+ diffEditorDocument = DiffEditor::DiffEditorManager::findOrCreate(documentId, title);
+ QTC_ASSERT(diffEditorDocument, return 0);
+ controller = diffEditorDocument->controller();
+
+ reloader = new SubversionDiffEditorReloader(this);
+ controller->setReloader(reloader);
+ controller->setContextLinesNumberEnabled(false);
+ }
+ QTC_ASSERT(reloader, return 0);
+
+ reloader->setWorkingDirectory(workingDirectory);
+ VcsBasePlugin::setSource(diffEditorDocument, source);
+
+ return reloader;
+}
+
+void SubversionClient::diff(const QString &workingDirectory, const QStringList &files, const QStringList &extraOptions)
+{
+ Q_UNUSED(extraOptions);
+
+ const QString vcsCmdString = vcsCommandString(DiffCommand);
+ const QString documentId = VcsBaseEditor::getTitleId(workingDirectory, files);
+ const QString title = vcsEditorTitle(vcsCmdString, documentId);
+
+ SubversionDiffEditorReloader *reloader = findOrCreateDiffEditor(documentId, workingDirectory, title, workingDirectory);
+ QTC_ASSERT(reloader, return);
+ reloader->setFilesList(files);
+ reloader->requestReload();
+}
+
+void SubversionClient::log(const QString &workingDir,
+ const QStringList &files,
+ const QStringList &extraOptions,
+ bool enableAnnotationContextMenu)
+{
+ const auto logCount = settings()->intValue(SubversionSettings::logCountKey);
+ QStringList svnExtraOptions =
+ QStringList(extraOptions)
+ << SubversionClient::addAuthenticationOptions(*settings());
+ if (logCount > 0)
+ svnExtraOptions << QLatin1String("-l") << QString::number(logCount);
+
+ QStringList nativeFiles;
+ foreach (const QString& file, files)
+ nativeFiles.append(QDir::toNativeSeparators(file));
+
+ // subversion stores log in UTF-8 and returns it back in user system locale.
+ // So we do not need to encode it.
+ VcsBaseClient::log(workingDir, files, svnExtraOptions, enableAnnotationContextMenu);
+}
+
+void SubversionClient::describe(const QString &workingDirectory, int changeNumber, const QString &title)
+{
+ const QString documentId = VcsBaseEditor::editorTag(DiffOutput,
+ workingDirectory,
+ QStringList(),
+ QString::number(changeNumber));
+
+ SubversionDiffEditorReloader *reloader = findOrCreateDiffEditor(documentId, workingDirectory, title, workingDirectory);
+ QTC_ASSERT(reloader, return);
+ reloader->setChangeNumber(changeNumber);
+ reloader->controller()->setDescriptionEnabled(true);
+ reloader->requestReload();
}
QString SubversionClient::findTopLevelForFile(const QFileInfo &file) const
@@ -247,17 +409,6 @@ VcsBaseClient::StatusItem SubversionClient::parseStatusLine(const QString &line)
return VcsBaseClient::StatusItem();
}
-VcsBaseEditorParameterWidget *SubversionClient::createDiffEditor(
- const QString &workingDir, const QStringList &files, const QStringList &extraOptions)
-{
- Q_UNUSED(extraOptions)
- SubversionDiffParameters p;
- p.workingDir = workingDir;
- p.files = files;
- p.extraOptions = extraOptions;
- return new SubversionDiffParameterWidget(this, p);
-}
-
} // namespace Internal
} // namespace Subversion
diff --git a/src/plugins/subversion/subversionclient.h b/src/plugins/subversion/subversionclient.h
index e2ce0394a90..ee283cfca6b 100644
--- a/src/plugins/subversion/subversionclient.h
+++ b/src/plugins/subversion/subversionclient.h
@@ -41,6 +41,7 @@ namespace Subversion {
namespace Internal {
class SubversionSettings;
+class SubversionDiffEditorReloader;
class SubversionClient : public VcsBase::VcsBaseClient
{
@@ -60,21 +61,19 @@ public:
const QString &commitMessageFile,
const QStringList &extraOptions = QStringList());
- void diff(const QString &workingDir, const QStringList &files,
- const QStringList &extraOptions = QStringList());
+ void diff(const QString &workingDirectory, const QStringList &files,
+ const QStringList &extraOptions);
+
+ void log(const QString &workingDir,
+ const QStringList &files = QStringList(),
+ const QStringList &extraOptions = QStringList(),
+ bool enableAnnotationContextMenu = false) Q_DECL_OVERRIDE;
+
+ void describe(const QString &workingDirectory, int changeNumber, const QString &title);
QString findTopLevelForFile(const QFileInfo &file) const;
QStringList revisionSpec(const QString &revision) const;
StatusItem parseStatusLine(const QString &line) const;
- class Version {
- public:
- int majorVersion;
- int minorVersion;
- int patchVersion;
- };
-
- Version svnVersion();
-
// Add authorization options to the command line arguments.
static QStringList addAuthenticationOptions(const SubversionSettings &settings);
@@ -82,12 +81,15 @@ public:
protected:
Core::Id vcsEditorKind(VcsCommandTag cmd) const;
- VcsBase::VcsBaseEditorParameterWidget *createDiffEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions);
+
private:
- Utils::FileName m_svnVersionBinary;
- QString m_svnVersion;
+ SubversionDiffEditorReloader *findOrCreateDiffEditor(const QString &documentId,
+ const QString &source,
+ const QString &title,
+ const QString &workingDirectory) const;
+
+ mutable Utils::FileName m_svnVersionBinary;
+ mutable QString m_svnVersion;
};
} // namespace Internal
diff --git a/src/plugins/subversion/subversionconstants.h b/src/plugins/subversion/subversionconstants.h
index 0c8e5019a3c..adbaa44a56f 100644
--- a/src/plugins/subversion/subversionconstants.h
+++ b/src/plugins/subversion/subversionconstants.h
@@ -39,7 +39,24 @@ namespace Constants {
const char NON_INTERACTIVE_OPTION[] = "--non-interactive";
enum { debug = 0 };
+const char SUBVERSION_CONTEXT[] = "Subversion Context";
+
+const char SUBVERSION_COMMIT_EDITOR_ID[] = "Subversion Commit Editor";
+const char SUBVERSION_COMMIT_EDITOR_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("VCS", "Subversion Commit Editor");
+const char SUBVERSION_SUBMIT_MIMETYPE[] = "text/vnd.qtcreator.svn.submit";
+
+const char SUBVERSION_LOG_EDITOR_ID[] = "Subversion File Log Editor";
+const char SUBVERSION_LOG_EDITOR_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("VCS", "Subversion File Log Editor");
+const char SUBVERSION_LOG_MIMETYPE[] = "text/vnd.qtcreator.svn.log";
+
+const char SUBVERSION_BLAME_EDITOR_ID[] = "Subversion Annotation Editor";
+const char SUBVERSION_BLAME_EDITOR_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("VCS", "Subversion Annotation Editor");
+const char SUBVERSION_BLAME_MIMETYPE[] = "text/vnd.qtcreator.svn.annotation";
+
+const char SUBMIT_CURRENT[] = "Subversion.SubmitCurrentLog";
+const char DIFF_SELECTED[] = "Subversion.DiffSelectedFilesInLog";
+
} // namespace Constants
-} // namespace SubVersion
+} // namespace Subversion
#endif // SUBVERSION_CONSTANTS_H
diff --git a/src/plugins/subversion/subversioncontrol.cpp b/src/plugins/subversion/subversioncontrol.cpp
index 60a9cdfe956..928dcb9bcc1 100644
--- a/src/plugins/subversion/subversioncontrol.cpp
+++ b/src/plugins/subversion/subversioncontrol.cpp
@@ -93,8 +93,6 @@ bool SubversionControl::supportsOperation(Operation operation) const
case DeleteOperation:
case MoveOperation:
case AnnotateOperation:
- case CheckoutOperation:
- case GetRepositoryRootOperation:
break;
case CreateRepositoryOperation:
case SnapshotOperations:
@@ -129,16 +127,6 @@ bool SubversionControl::vcsMove(const QString &from, const QString &to)
return m_plugin->vcsMove(fromInfo.absolutePath(), fromInfo.absoluteFilePath(), toInfo.absoluteFilePath());
}
-bool SubversionControl::vcsCheckout(const QString &directory, const QByteArray &url)
-{
- return m_plugin->vcsCheckout(directory, url);
-}
-
-QString SubversionControl::vcsGetRepositoryURL(const QString &directory)
-{
- return m_plugin->vcsGetRepositoryURL(directory);
-}
-
bool SubversionControl::vcsCreateRepository(const QString &)
{
return false;
diff --git a/src/plugins/subversion/subversioncontrol.h b/src/plugins/subversion/subversioncontrol.h
index 6c8279b83d1..a6530ed6957 100644
--- a/src/plugins/subversion/subversioncontrol.h
+++ b/src/plugins/subversion/subversioncontrol.h
@@ -57,8 +57,6 @@ public:
bool vcsDelete(const QString &filename);
bool vcsMove(const QString &from, const QString &to);
bool vcsCreateRepository(const QString &directory);
- bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
bool vcsAnnotate(const QString &file, int line);
diff --git a/src/plugins/subversion/subversionplugin.cpp b/src/plugins/subversion/subversionplugin.cpp
index 756afc21755..0993c65efd1 100644
--- a/src/plugins/subversion/subversionplugin.cpp
+++ b/src/plugins/subversion/subversionplugin.cpp
@@ -92,7 +92,6 @@ using namespace VcsBase;
namespace Subversion {
namespace Internal {
-const char SUBVERSION_CONTEXT[] = "Subversion Context";
const char CMD_ID_SUBVERSION_MENU[] = "Subversion.Menu";
const char CMD_ID_ADD[] = "Subversion.Add";
const char CMD_ID_DELETE_FILE[] = "Subversion.Delete";
@@ -114,26 +113,16 @@ const char CMD_ID_UPDATE[] = "Subversion.Update";
const char CMD_ID_COMMIT_PROJECT[] = "Subversion.CommitProject";
const char CMD_ID_DESCRIBE[] = "Subversion.Describe";
-const char SUBVERSION_SUBMIT_MIMETYPE[] = "text/vnd.qtcreator.svn.submit";
-const char SUBVERSIONCOMMITEDITOR_ID[] = "Subversion Commit Editor";
-const char SUBVERSIONCOMMITEDITOR_DISPLAY_NAME[] = QT_TRANSLATE_NOOP("VCS", "Subversion Commit Editor");
-const char SUBMIT_CURRENT[] = "Subversion.SubmitCurrentLog";
-const char DIFF_SELECTED[] = "Subversion.DiffSelectedFilesInLog";
-
const VcsBaseEditorParameters editorParameters[] = {
{
LogOutput,
- "Subversion File Log Editor", // id
- QT_TRANSLATE_NOOP("VCS", "Subversion File Log Editor"), // display_name
- "text/vnd.qtcreator.svn.log"},
+ Constants::SUBVERSION_LOG_EDITOR_ID,
+ Constants::SUBVERSION_LOG_EDITOR_DISPLAY_NAME,
+ Constants::SUBVERSION_LOG_MIMETYPE},
{ AnnotateOutput,
- "Subversion Annotation Editor", // id
- QT_TRANSLATE_NOOP("VCS", "Subversion Annotation Editor"), // display_name
- "text/vnd.qtcreator.svn.annotation"},
-{ DiffOutput,
- "Subversion Diff Editor", // id
- QT_TRANSLATE_NOOP("VCS", "Subversion Diff Editor"), // display_name
- "text/x-patch"}
+ Constants::SUBVERSION_BLAME_EDITOR_ID,
+ Constants::SUBVERSION_BLAME_EDITOR_DISPLAY_NAME,
+ Constants::SUBVERSION_BLAME_MIMETYPE}
};
// Utility to find a parameter set by type
@@ -236,9 +225,9 @@ bool SubversionPlugin::isCommitEditorOpen() const
}
const VcsBaseSubmitEditorParameters submitParameters = {
- SUBVERSION_SUBMIT_MIMETYPE,
- SUBVERSIONCOMMITEDITOR_ID,
- SUBVERSIONCOMMITEDITOR_DISPLAY_NAME,
+ Constants::SUBVERSION_SUBMIT_MIMETYPE,
+ Constants::SUBVERSION_COMMIT_EDITOR_ID,
+ Constants::SUBVERSION_COMMIT_EDITOR_DISPLAY_NAME,
VcsBaseSubmitEditorParameters::DiffFiles
};
@@ -291,12 +280,12 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
subversionMenu->menu()->setTitle(tr("&Subversion"));
toolsContainer->addMenu(subversionMenu);
m_menuAction = subversionMenu->menu()->menuAction();
- Core::Command *command;
+ Command *command;
m_diffCurrentAction = new ParameterAction(tr("Diff Current File"), tr("Diff \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_diffCurrentAction,
CMD_ID_DIFF_CURRENT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+S,Meta+D") : tr("Alt+S,Alt+D")));
connect(m_diffCurrentAction, SIGNAL(triggered()), this, SLOT(diffCurrentFile()));
subversionMenu->addAction(command);
@@ -305,7 +294,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_filelogCurrentAction = new ParameterAction(tr("Filelog Current File"), tr("Filelog \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_filelogCurrentAction,
CMD_ID_FILELOG_CURRENT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_filelogCurrentAction, SIGNAL(triggered()), this,
SLOT(filelogCurrentFile()));
subversionMenu->addAction(command);
@@ -314,7 +303,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_annotateCurrentAction = new ParameterAction(tr("Annotate Current File"), tr("Annotate \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_annotateCurrentAction,
CMD_ID_ANNOTATE_CURRENT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_annotateCurrentAction, SIGNAL(triggered()), this,
SLOT(annotateCurrentFile()));
subversionMenu->addAction(command);
@@ -325,7 +314,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_addAction = new ParameterAction(tr("Add"), tr("Add \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_addAction, CMD_ID_ADD,
context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+S,Meta+A") : tr("Alt+S,Alt+A")));
connect(m_addAction, SIGNAL(triggered()), this, SLOT(addCurrentFile()));
subversionMenu->addAction(command);
@@ -334,7 +323,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_commitCurrentAction = new ParameterAction(tr("Commit Current File"), tr("Commit \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_commitCurrentAction,
CMD_ID_COMMIT_CURRENT, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
command->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Meta+S,Meta+C") : tr("Alt+S,Alt+C")));
connect(m_commitCurrentAction, SIGNAL(triggered()), this, SLOT(startCommitCurrentFile()));
subversionMenu->addAction(command);
@@ -343,7 +332,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_deleteAction = new ParameterAction(tr("Delete..."), tr("Delete \"%1\"..."), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_deleteAction, CMD_ID_DELETE_FILE,
context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_deleteAction, SIGNAL(triggered()), this, SLOT(promptToDeleteCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
@@ -351,7 +340,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_revertAction = new ParameterAction(tr("Revert..."), tr("Revert \"%1\"..."), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_revertAction, CMD_ID_REVERT,
context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_revertAction, SIGNAL(triggered()), this, SLOT(revertCurrentFile()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
@@ -361,7 +350,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_diffProjectAction = new ParameterAction(tr("Diff Project"), tr("Diff Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_diffProjectAction, CMD_ID_DIFF_PROJECT,
context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_diffProjectAction, SIGNAL(triggered()), this, SLOT(diffProject()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
@@ -369,14 +358,14 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_statusProjectAction = new ParameterAction(tr("Project Status"), tr("Status of Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_statusProjectAction, CMD_ID_STATUS,
context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_statusProjectAction, SIGNAL(triggered()), this, SLOT(projectStatus()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_logProjectAction = new ParameterAction(tr("Log Project"), tr("Log Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_logProjectAction, CMD_ID_PROJECTLOG, context);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_logProjectAction, SIGNAL(triggered()), this, SLOT(logProject()));
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
@@ -384,14 +373,14 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_updateProjectAction = new ParameterAction(tr("Update Project"), tr("Update Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_updateProjectAction, CMD_ID_UPDATE, context);
connect(m_updateProjectAction, SIGNAL(triggered()), this, SLOT(updateProject()));
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
m_commitProjectAction = new ParameterAction(tr("Commit Project"), tr("Commit Project \"%1\""), ParameterAction::EnabledWithParameter, this);
command = ActionManager::registerAction(m_commitProjectAction, CMD_ID_COMMIT_PROJECT, context);
connect(m_commitProjectAction, SIGNAL(triggered()), this, SLOT(startCommitProject()));
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
subversionMenu->addAction(command);
m_commandLocator->appendCommand(command);
@@ -441,11 +430,11 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
m_commandLocator->appendCommand(command);
// Actions of the submit editor
- Context svncommitcontext(SUBVERSIONCOMMITEDITOR_ID);
+ Context svncommitcontext(Constants::SUBVERSION_COMMIT_EDITOR_ID);
m_submitCurrentLogAction = new QAction(VcsBaseSubmitEditor::submitIcon(), tr("Commit"), this);
command = ActionManager::registerAction(m_submitCurrentLogAction, SUBMIT_CURRENT, svncommitcontext);
- command->setAttribute(Core::Command::CA_UpdateText);
+ command->setAttribute(Command::CA_UpdateText);
connect(m_submitCurrentLogAction, SIGNAL(triggered()), this, SLOT(submitCurrentLog()));
m_submitDiffAction = new QAction(VcsBaseSubmitEditor::diffIcon(), tr("Diff &Selected Files"), this);
@@ -472,7 +461,7 @@ bool SubversionPlugin::submitEditorAboutToClose()
// Submit editor closing. Make it write out the commit message
// and retrieve files
- const QFileInfo editorFile(editorDocument->filePath());
+ const QFileInfo editorFile = editorDocument->filePath().toFileInfo();
const QFileInfo changeFile(m_commitMessageFileName);
if (editorFile.absoluteFilePath() != changeFile.absoluteFilePath())
return true; // Oops?!
@@ -516,12 +505,12 @@ bool SubversionPlugin::submitEditorAboutToClose()
void SubversionPlugin::diffCommitFiles(const QStringList &files)
{
- m_client->diff(m_commitRepository, files);
+ m_client->diff(m_commitRepository, files, QStringList());
}
SubversionSubmitEditor *SubversionPlugin::openSubversionSubmitEditor(const QString &fileName)
{
- IEditor *editor = EditorManager::openEditor(fileName, SUBVERSIONCOMMITEDITOR_ID);
+ IEditor *editor = EditorManager::openEditor(fileName, Constants::SUBVERSION_COMMIT_EDITOR_ID);
SubversionSubmitEditor *submitEditor = qobject_cast<SubversionSubmitEditor*>(editor);
QTC_ASSERT(submitEditor, return 0);
setSubmitEditor(submitEditor);
@@ -642,14 +631,16 @@ void SubversionPlugin::diffProject()
QTC_ASSERT(state.hasProject(), return);
const QString relativeProject = state.relativeCurrentProject();
m_client->diff(state.currentProjectTopLevel(),
- relativeProject.isEmpty() ? QStringList() : QStringList(relativeProject));
+ relativeProject.isEmpty() ? QStringList() : QStringList(relativeProject),
+ QStringList());
}
void SubversionPlugin::diffCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- m_client->diff(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()));
+ m_client->diff(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()),
+ QStringList());
}
void SubversionPlugin::startCommitCurrentFile()
@@ -744,7 +735,7 @@ void SubversionPlugin::diffRepository()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- m_client->diff(state.topLevel(), QStringList());
+ m_client->diff(state.topLevel(), QStringList(), QStringList());
}
void SubversionPlugin::statusRepository()
@@ -779,41 +770,7 @@ void SubversionPlugin::filelog(const QString &workingDir,
const QString &file,
bool enableAnnotationContextMenu)
{
- // no need for temp file
- QStringList args(QLatin1String("log"));
- args << SubversionClient::addAuthenticationOptions(settings());
- if (m_settings.intValue(SubversionSettings::logCountKey) > 0) {
- args << QLatin1String("-l")
- << QString::number(m_settings.intValue(SubversionSettings::logCountKey));
- }
- if (!file.isEmpty())
- args.append(QDir::toNativeSeparators(file));
-
- // subversion stores log in UTF-8 and returns it back in user system locale.
- // So we do not need to encode it.
- const SubversionResponse response =
- runSvn(workingDir, args, m_settings.timeOutMs(),
- SshPasswordPrompt, 0/*codec*/);
- if (response.error)
- return;
-
- // Re-use an existing view if possible to support
- // the common usage pattern of continuously changing and diffing a file
-
- const QString id = VcsBaseEditor::getTitleId(workingDir, QStringList(file));
- const QString tag = VcsBaseEditor::editorTag(LogOutput, workingDir,
- QStringList(file));
- if (IEditor *editor = VcsBaseEditor::locateEditorByTag(tag)) {
- editor->document()->setContents(response.stdOut.toUtf8());
- EditorManager::activateEditor(editor);
- } else {
- const QString title = QString::fromLatin1("svn log %1").arg(id);
- const QString source = VcsBaseEditor::getSource(workingDir, file);
- IEditor *newEditor = showOutputInEditor(title, response.stdOut, LogOutput, source, /*codec*/0);
- VcsBaseEditor::tagEditor(newEditor, tag);
- if (enableAnnotationContextMenu)
- VcsBaseEditor::getVcsBaseEditor(newEditor)->setFileLogAnnotateEnabled(true);
- }
+ m_client->log(workingDir, QStringList(file), QStringList(), enableAnnotationContextMenu);
}
void SubversionPlugin::updateProject()
@@ -914,49 +871,14 @@ void SubversionPlugin::describe(const QString &source, const QString &changeNr)
qDebug() << Q_FUNC_INFO << source << topLevel << changeNr;
// Number must be >= 1
bool ok;
+
const int number = changeNr.toInt(&ok);
if (!ok || number < 1)
return;
- // Run log to obtain message (local utf8)
- QString description;
- QStringList args(QLatin1String("log"));
- args << SubversionClient::addAuthenticationOptions(settings());
- args.push_back(QLatin1String("-r"));
- args.push_back(changeNr);
- const SubversionResponse logResponse =
- runSvn(topLevel, args, m_settings.timeOutMs(), SshPasswordPrompt);
- if (logResponse.error)
- return;
- description = logResponse.stdOut;
- // Run diff (encoding via source codec)
- args.clear();
- args.push_back(QLatin1String("diff"));
- args << SubversionClient::addAuthenticationOptions(settings());
- args.push_back(QLatin1String("-r"));
- QString diffArg;
- QTextStream(&diffArg) << (number - 1) << ':' << number;
- args.push_back(diffArg);
-
- QTextCodec *codec = VcsBaseEditor::getCodec(source);
- const SubversionResponse response =
- runSvn(topLevel, args, m_settings.timeOutMs(),
- SshPasswordPrompt, codec);
- if (response.error)
- return;
- description += response.stdOut;
+ const QString title = QString::fromLatin1("svn describe %1#%2").arg(fi.fileName(), changeNr);
- // Re-use an existing view if possible to support
- // the common usage pattern of continuously changing and diffing a file
- const QString tag = VcsBaseEditor::editorTag(DiffOutput, source, QStringList(), changeNr);
- if (IEditor *editor = VcsBaseEditor::locateEditorByTag(tag)) {
- editor->document()->setContents(description.toUtf8());
- EditorManager::activateEditor(editor);
- } else {
- const QString title = QString::fromLatin1("svn describe %1#%2").arg(fi.fileName(), changeNr);
- IEditor *newEditor = showOutputInEditor(title, description, DiffOutput, source, codec);
- VcsBaseEditor::tagEditor(newEditor, tag);
- }
+ m_client->describe(topLevel, number, title);
}
void SubversionPlugin::slotDescribe()
@@ -1141,45 +1063,6 @@ bool SubversionPlugin::vcsCheckout(const QString &directory, const QByteArray &u
}
-QString SubversionPlugin::vcsGetRepositoryURL(const QString &directory)
-{
- QXmlStreamReader xml;
- QStringList args = QStringList(QLatin1String("info"));
- args << SubversionClient::addAuthenticationOptions(settings()) << QLatin1String("--xml");
-
- const SubversionResponse response = runSvn(directory, args, 10 * m_settings.timeOutMs(), SuppressCommandLogging);
- xml.addData(response.stdOut);
-
- bool repo = false;
- bool root = false;
-
- while (!xml.atEnd() && !xml.hasError()) {
- switch (xml.readNext()) {
- case QXmlStreamReader::StartDocument:
- break;
- case QXmlStreamReader::StartElement:
- if (xml.name() == QLatin1String("repository"))
- repo = true;
- else if (repo && xml.name() == QLatin1String("root"))
- root = true;
- break;
- case QXmlStreamReader::EndElement:
- if (xml.name() == QLatin1String("repository"))
- repo = false;
- else if (repo && xml.name() == QLatin1String("root"))
- root = false;
- break;
- case QXmlStreamReader::Characters:
- if (repo && root)
- return xml.text().toString();
- break;
- default:
- break;
- }
- }
- return QString();
-}
-
bool SubversionPlugin::managesDirectory(const QString &directory, QString *topLevel /* = 0 */) const
{
const QDir dir(directory);
@@ -1234,39 +1117,6 @@ SubversionControl *SubversionPlugin::subVersionControl() const
}
#ifdef WITH_TESTS
-void SubversionPlugin::testDiffFileResolving_data()
-{
- QTest::addColumn<QByteArray>("header");
- QTest::addColumn<QByteArray>("fileName");
-
- QTest::newRow("New") << QByteArray(
- "Index: src/plugins/subversion/subversioneditor.cpp\n"
- "===================================================================\n"
- "--- src/plugins/subversion/subversioneditor.cpp\t(revision 0)\n"
- "+++ src/plugins/subversion/subversioneditor.cpp\t(revision 0)\n"
- "@@ -0,0 +125 @@\n\n")
- << QByteArray("src/plugins/subversion/subversioneditor.cpp");
- QTest::newRow("Deleted") << QByteArray(
- "Index: src/plugins/subversion/subversioneditor.cpp\n"
- "===================================================================\n"
- "--- src/plugins/subversion/subversioneditor.cpp\t(revision 42)\n"
- "+++ src/plugins/subversion/subversioneditor.cpp\t(working copy)\n"
- "@@ -1,125 +0,0 @@\n\n")
- << QByteArray("src/plugins/subversion/subversioneditor.cpp");
- QTest::newRow("Normal") << QByteArray(
- "Index: src/plugins/subversion/subversioneditor.cpp\n"
- "===================================================================\n"
- "--- src/plugins/subversion/subversioneditor.cpp\t(revision 42)\n"
- "+++ src/plugins/subversion/subversioneditor.cpp\t(working copy)\n"
- "@@ -120,7 +120,7 @@\n\n")
- << QByteArray("src/plugins/subversion/subversioneditor.cpp");
-}
-
-void SubversionPlugin::testDiffFileResolving()
-{
- VcsBaseEditorWidget::testDiffFileResolving(editorParameters[2].id);
-}
-
void SubversionPlugin::testLogResolving()
{
QByteArray data(
diff --git a/src/plugins/subversion/subversionplugin.h b/src/plugins/subversion/subversionplugin.h
index 4060f84d6eb..0a6eb5d5715 100644
--- a/src/plugins/subversion/subversionplugin.h
+++ b/src/plugins/subversion/subversionplugin.h
@@ -87,12 +87,14 @@ public:
bool managesDirectory(const QString &directory, QString *topLevel = 0) const;
bool managesFile(const QString &workingDirectory, const QString &fileName) const;
bool vcsCheckout(const QString &directory, const QByteArray &url);
- QString vcsGetRepositoryURL(const QString &directory);
static SubversionPlugin *instance();
QString monitorFile(const QString &repository) const;
QString synchronousTopic(const QString &repository) const;
+ SubversionResponse runSvn(const QString &workingDir,
+ const QStringList &arguments, int timeOut,
+ unsigned flags, QTextCodec *outputCodec = 0) const;
public slots:
void vcsAnnotate(const QString &workingDir, const QString &file,
@@ -123,8 +125,6 @@ private slots:
void statusRepository();
void updateRepository();
#ifdef WITH_TESTS
- void testDiffFileResolving_data();
- void testDiffFileResolving();
void testLogResolving();
#endif
@@ -137,9 +137,6 @@ private:
Core::IEditor * showOutputInEditor(const QString& title, const QString &output,
int editorType, const QString &source,
QTextCodec *codec);
- SubversionResponse runSvn(const QString &workingDir,
- const QStringList &arguments, int timeOut,
- unsigned flags, QTextCodec *outputCodec = 0) const;
void filelog(const QString &workingDir,
const QString &file = QString(),
diff --git a/src/plugins/subversion/subversionsettings.cpp b/src/plugins/subversion/subversionsettings.cpp
index 8f26effb2a5..89247465e42 100644
--- a/src/plugins/subversion/subversionsettings.cpp
+++ b/src/plugins/subversion/subversionsettings.cpp
@@ -43,6 +43,7 @@ const QLatin1String SubversionSettings::userKey("User");
const QLatin1String SubversionSettings::passwordKey("Password");
const QLatin1String SubversionSettings::spaceIgnorantAnnotationKey("SpaceIgnorantAnnotation");
const QLatin1String SubversionSettings::diffIgnoreWhiteSpaceKey("DiffIgnoreWhiteSpace");
+const QLatin1String SubversionSettings::logVerboseKey("LogVerbose");
SubversionSettings::SubversionSettings()
{
@@ -54,6 +55,7 @@ SubversionSettings::SubversionSettings()
declareKey(passwordKey, QLatin1String(""));
declareKey(spaceIgnorantAnnotationKey, true);
declareKey(diffIgnoreWhiteSpaceKey, false);
+ declareKey(logVerboseKey, false);
}
bool SubversionSettings::hasAuthentication() const
diff --git a/src/plugins/subversion/subversionsettings.h b/src/plugins/subversion/subversionsettings.h
index f1a73fcdb0a..3c00a126646 100644
--- a/src/plugins/subversion/subversionsettings.h
+++ b/src/plugins/subversion/subversionsettings.h
@@ -44,6 +44,7 @@ public:
static const QLatin1String passwordKey;
static const QLatin1String spaceIgnorantAnnotationKey;
static const QLatin1String diffIgnoreWhiteSpaceKey;
+ static const QLatin1String logVerboseKey;
SubversionSettings();
bool hasAuthentication() const;
diff --git a/src/plugins/subversion/subversionsubmiteditor.cpp b/src/plugins/subversion/subversionsubmiteditor.cpp
index 1827662b9e9..89baf7c5b76 100644
--- a/src/plugins/subversion/subversionsubmiteditor.cpp
+++ b/src/plugins/subversion/subversionsubmiteditor.cpp
@@ -47,7 +47,7 @@ SubversionSubmitEditor::SubversionSubmitEditor(const VcsBase::VcsBaseSubmitEdito
void SubversionSubmitEditor::setStatusList(const QList<StatusFilePair> &statusOutput)
{
typedef QList<StatusFilePair>::const_iterator ConstIterator;
- VcsBase::SubmitFileModel *model = new VcsBase::SubmitFileModel(this);
+ auto model = new VcsBase::SubmitFileModel(this);
const ConstIterator cend = statusOutput.constEnd();
for (ConstIterator it = statusOutput.constBegin(); it != cend; ++it)
diff --git a/src/plugins/tasklist/stopmonitoringhandler.cpp b/src/plugins/tasklist/stopmonitoringhandler.cpp
index de58f307491..dda301cd017 100644
--- a/src/plugins/tasklist/stopmonitoringhandler.cpp
+++ b/src/plugins/tasklist/stopmonitoringhandler.cpp
@@ -66,7 +66,7 @@ QAction *StopMonitoringHandler::createAction(QObject *parent) const
const QString toolTip =
QCoreApplication::translate("TaskList::Internal::StopMonitoringHandler",
"Stop monitoring task files.");
- QAction *stopMonitoringAction = new QAction(text, parent);
+ auto stopMonitoringAction = new QAction(text, parent);
stopMonitoringAction->setToolTip(toolTip);
return stopMonitoringAction;
}
diff --git a/src/plugins/tasklist/taskfile.cpp b/src/plugins/tasklist/taskfile.cpp
index 46c9eaadc51..1c3c889dba5 100644
--- a/src/plugins/tasklist/taskfile.cpp
+++ b/src/plugins/tasklist/taskfile.cpp
@@ -92,12 +92,12 @@ bool TaskFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
deleteLater();
return true;
}
- return open(errorString, filePath());
+ return open(errorString, filePath().toString());
}
bool TaskFile::open(QString *errorString, const QString &fileName)
{
- setFilePath(fileName);
+ setFilePath(Utils::FileName::fromString(fileName));
return TaskListPlugin::loadFile(errorString, m_baseDir, fileName);
}
diff --git a/src/plugins/tasklist/tasklistplugin.cpp b/src/plugins/tasklist/tasklistplugin.cpp
index 4ee85843a3d..9d2e01d661d 100644
--- a/src/plugins/tasklist/tasklistplugin.cpp
+++ b/src/plugins/tasklist/tasklistplugin.cpp
@@ -38,7 +38,7 @@
#include <coreplugin/idocumentfactory.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/mimedatabase.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <projectexplorer/session.h>
#include <projectexplorer/task.h>
@@ -166,19 +166,19 @@ static bool parseTaskFile(QString *errorString, const QString &base, const QStri
// TaskListPlugin
// --------------------------------------------------------------------------
-Core::IDocument *TaskListPlugin::openTasks(const QString &base, const QString &fileName)
+IDocument *TaskListPlugin::openTasks(const QString &base, const QString &fileName)
{
foreach (TaskFile *doc, m_openFiles) {
- if (doc->filePath() == fileName)
+ if (doc->filePath().toString() == fileName)
return doc;
}
- TaskFile *file = new TaskFile(this);
+ auto file = new TaskFile(this);
file->setBaseDir(base);
QString errorString;
if (!file->open(&errorString, fileName)) {
- QMessageBox::critical(Core::ICore::mainWindow(), tr("File Error"), errorString);
+ QMessageBox::critical(ICore::mainWindow(), tr("File Error"), errorString);
delete file;
return 0;
}
@@ -186,7 +186,7 @@ Core::IDocument *TaskListPlugin::openTasks(const QString &base, const QString &f
m_openFiles.append(file);
// Register with filemanager:
- Core::DocumentManager::addDocument(file);
+ DocumentManager::addDocument(file);
return file;
}
@@ -203,13 +203,13 @@ bool TaskListPlugin::initialize(const QStringList &arguments, QString *errorMess
//: Category under which tasklist tasks are listed in Issues view
TaskHub::addCategory(Constants::TASKLISTTASK_ID, tr("My Tasks"));
- if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml"), errorMessage))
return false;
m_fileFactory = new IDocumentFactory;
m_fileFactory->addMimeType(QLatin1String("text/x-tasklist"));
m_fileFactory->setOpener([this](const QString &fileName) -> IDocument * {
- ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ Project *project = ProjectTree::currentProject();
return this->openTasks(project ? project->projectDirectory().toString() : QString(), fileName);
});
diff --git a/src/plugins/texteditor/autocompleter.cpp b/src/plugins/texteditor/autocompleter.cpp
index 56863f6b77a..83ee9cbeff9 100644
--- a/src/plugins/texteditor/autocompleter.cpp
+++ b/src/plugins/texteditor/autocompleter.cpp
@@ -90,10 +90,10 @@ void AutoCompleter::countBrackets(QTextCursor cursor,
cursor.setPosition(from);
QTextBlock block = cursor.block();
while (block.isValid() && block.position() < end) {
- TextEditor::Parentheses parenList = TextEditor::TextDocumentLayout::parentheses(block);
- if (!parenList.isEmpty() && !TextEditor::TextDocumentLayout::ifdefedOut(block)) {
+ Parentheses parenList = TextDocumentLayout::parentheses(block);
+ if (!parenList.isEmpty() && !TextDocumentLayout::ifdefedOut(block)) {
for (int i = 0; i < parenList.count(); ++i) {
- TextEditor::Parenthesis paren = parenList.at(i);
+ Parenthesis paren = parenList.at(i);
int position = block.position() + paren.pos;
if (position < from || position >= end)
continue;
@@ -151,10 +151,10 @@ QString AutoCompleter::autoComplete(QTextCursor &cursor, const QString &textToIn
const QString brackets = QLatin1String("[]");
if (parentheses.contains(character) || brackets.contains(character)) {
QTextCursor tmp= cursor;
- bool foundBlockStart = TextEditor::TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp);
+ bool foundBlockStart = TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp);
int blockStart = foundBlockStart ? tmp.position() : 0;
tmp = cursor;
- bool foundBlockEnd = TextEditor::TextBlockUserData::findNextBlockClosingParenthesis(&tmp);
+ bool foundBlockEnd = TextBlockUserData::findNextBlockClosingParenthesis(&tmp);
int blockEnd = foundBlockEnd ? tmp.position() : (cursor.document()->characterCount() - 1);
const QChar openChar = parentheses.contains(character) ? QLatin1Char('(') : QLatin1Char('[');
const QChar closeChar = parentheses.contains(character) ? QLatin1Char(')') : QLatin1Char(']');
@@ -218,10 +218,10 @@ bool AutoCompleter::autoBackspace(QTextCursor &cursor)
const QChar character = lookBehind;
if (character == QLatin1Char('(') || character == QLatin1Char('[')) {
QTextCursor tmp = cursor;
- TextEditor::TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp);
+ TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp);
int blockStart = tmp.isNull() ? 0 : tmp.position();
tmp = cursor;
- TextEditor::TextBlockUserData::findNextBlockClosingParenthesis(&tmp);
+ TextBlockUserData::findNextBlockClosingParenthesis(&tmp);
int blockEnd = tmp.isNull() ? (cursor.document()->characterCount()-1) : tmp.position();
QChar openChar = character;
QChar closeChar = (character == QLatin1Char('(')) ? QLatin1Char(')') : QLatin1Char(']');
diff --git a/src/plugins/texteditor/basefilefind.cpp b/src/plugins/texteditor/basefilefind.cpp
index 1709cffb3aa..7c13415e46e 100644
--- a/src/plugins/texteditor/basefilefind.cpp
+++ b/src/plugins/texteditor/basefilefind.cpp
@@ -55,6 +55,9 @@
#include <QLabel>
#include <QLabel>
+using namespace Utils;
+using namespace Core;
+
namespace TextEditor {
namespace Internal {
@@ -63,8 +66,8 @@ class BaseFileFindPrivate
public:
BaseFileFindPrivate() : m_resultLabel(0), m_filterCombo(0) {}
- QMap<QFutureWatcher<Utils::FileSearchResultList> *, QPointer<Core::SearchResult> > m_watchers;
- QPointer<Core::IFindSupport> m_currentFindSupport;
+ QMap<QFutureWatcher<FileSearchResultList> *, QPointer<SearchResult> > m_watchers;
+ QPointer<IFindSupport> m_currentFindSupport;
QLabel *m_resultLabel;
QStringListModel m_filterStrings;
@@ -75,8 +78,6 @@ public:
} // namespace Internal
using namespace Internal;
-using namespace Utils;
-using namespace Core;
BaseFileFind::BaseFileFind() : d(new BaseFileFindPrivate)
{
@@ -125,15 +126,15 @@ QStringList BaseFileFind::fileNameFilters() const
return filters;
}
-void BaseFileFind::runNewSearch(const QString &txt, Core::FindFlags findFlags,
+void BaseFileFind::runNewSearch(const QString &txt, FindFlags findFlags,
SearchResultWindow::SearchMode searchMode)
{
d->m_currentFindSupport = 0;
if (d->m_filterCombo)
updateComboEntries(d->m_filterCombo, true);
- SearchResult *search = Core::SearchResultWindow::instance()->startNewSearch(label(),
- toolTip().arg(Core::IFindFilter::descriptionForFindFlags(findFlags)),
- txt, searchMode, Core::SearchResultWindow::PreserveCaseEnabled,
+ SearchResult *search = SearchResultWindow::instance()->startNewSearch(label(),
+ toolTip().arg(IFindFilter::descriptionForFindFlags(findFlags)),
+ txt, searchMode, SearchResultWindow::PreserveCaseEnabled,
QString::fromLatin1("TextEditor"));
search->setTextToReplace(txt);
search->setSearchAgainSupported(true);
@@ -158,14 +159,14 @@ void BaseFileFind::runNewSearch(const QString &txt, Core::FindFlags findFlags,
runSearch(search);
}
-void BaseFileFind::runSearch(Core::SearchResult *search)
+void BaseFileFind::runSearch(SearchResult *search)
{
FileFindParameters parameters = search->userData().value<FileFindParameters>();
CountingLabel *label = new CountingLabel;
connect(search, SIGNAL(countChanged(int)), label, SLOT(updateCount(int)));
CountingLabel *statusLabel = new CountingLabel;
connect(search, SIGNAL(countChanged(int)), statusLabel, SLOT(updateCount(int)));
- Core::SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch|IOutputPane::WithFocus));
+ SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch|IOutputPane::WithFocus));
QFutureWatcher<FileSearchResultList> *watcher = new QFutureWatcher<FileSearchResultList>();
d->m_watchers.insert(watcher, search);
watcher->setPendingResultsLimit(1);
@@ -189,24 +190,24 @@ void BaseFileFind::runSearch(Core::SearchResult *search)
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
}
-void BaseFileFind::findAll(const QString &txt, Core::FindFlags findFlags)
+void BaseFileFind::findAll(const QString &txt, FindFlags findFlags)
{
runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}
-void BaseFileFind::replaceAll(const QString &txt, Core::FindFlags findFlags)
+void BaseFileFind::replaceAll(const QString &txt, FindFlags findFlags)
{
runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
}
void BaseFileFind::doReplace(const QString &text,
- const QList<Core::SearchResultItem> &items,
+ const QList<SearchResultItem> &items,
bool preserveCase)
{
QStringList files = replaceAll(text, items, preserveCase);
if (!files.isEmpty()) {
DocumentManager::notifyFilesChangedInternally(files);
- Core::SearchResultWindow::instance()->hide();
+ SearchResultWindow::instance()->hide();
}
}
@@ -219,10 +220,10 @@ void BaseFileFind::displayResult(int index) {
watcher->cancel();
return;
}
- Utils::FileSearchResultList results = watcher->resultAt(index);
- QList<Core::SearchResultItem> items;
- foreach (const Utils::FileSearchResult &result, results) {
- Core::SearchResultItem item;
+ FileSearchResultList results = watcher->resultAt(index);
+ QList<SearchResultItem> items;
+ foreach (const FileSearchResult &result, results) {
+ SearchResultItem item;
item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
item.lineNumber = result.lineNumber;
item.text = result.matchingLine;
@@ -232,7 +233,7 @@ void BaseFileFind::displayResult(int index) {
item.userData = result.regexpCapturedTexts;
items << item;
}
- search->addResults(items, Core::SearchResult::AddOrdered);
+ search->addResults(items, SearchResult::AddOrdered);
}
void BaseFileFind::searchFinished()
@@ -305,7 +306,7 @@ void BaseFileFind::updateComboEntries(QComboBox *combo, bool onTop)
}
}
-void BaseFileFind::openEditor(const Core::SearchResultItem &item)
+void BaseFileFind::openEditor(const SearchResultItem &item)
{
SearchResult *result = qobject_cast<SearchResult *>(sender());
IEditor *openedEditor = 0;
@@ -354,7 +355,7 @@ void BaseFileFind::recheckEnabled()
}
QStringList BaseFileFind::replaceAll(const QString &text,
- const QList<Core::SearchResultItem> &items,
+ const QList<SearchResultItem> &items,
bool preserveCase)
{
if (items.isEmpty())
@@ -362,12 +363,12 @@ QStringList BaseFileFind::replaceAll(const QString &text,
RefactoringChanges refactoring;
- QHash<QString, QList<Core::SearchResultItem> > changes;
- foreach (const Core::SearchResultItem &item, items)
+ QHash<QString, QList<SearchResultItem> > changes;
+ foreach (const SearchResultItem &item, items)
changes[QDir::fromNativeSeparators(item.path.first())].append(item);
// Checking for files without write permissions
- QHashIterator<QString, QList<Core::SearchResultItem> > it(changes);
+ QHashIterator<QString, QList<SearchResultItem> > it(changes);
QSet<QString> roFiles;
while (it.hasNext()) {
it.next();
@@ -388,12 +389,12 @@ QStringList BaseFileFind::replaceAll(const QString &text,
while (it.hasNext()) {
it.next();
const QString fileName = it.key();
- const QList<Core::SearchResultItem> changeItems = it.value();
+ const QList<SearchResultItem> changeItems = it.value();
ChangeSet changeSet;
RefactoringFilePtr file = refactoring.file(fileName);
QSet<QPair<int, int> > processed;
- foreach (const Core::SearchResultItem &item, changeItems) {
+ foreach (const SearchResultItem &item, changeItems) {
const QPair<int, int> &p = qMakePair(item.lineNumber, item.textMarkPos);
if (processed.contains(p))
continue;
diff --git a/src/plugins/texteditor/basehoverhandler.cpp b/src/plugins/texteditor/basehoverhandler.cpp
index 6c3ef8065d1..08e1bbcdb31 100644
--- a/src/plugins/texteditor/basehoverhandler.cpp
+++ b/src/plugins/texteditor/basehoverhandler.cpp
@@ -33,7 +33,6 @@
#include <coreplugin/icore.h>
#include <utils/tooltip/tooltip.h>
-#include <utils/tooltip/tipcontents.h>
#include <QPoint>
@@ -144,7 +143,7 @@ void BaseHoverHandler::operateTooltip(TextEditorWidget *editorWidget, const QPoi
if (m_toolTip.isEmpty())
Utils::ToolTip::hide();
else
- Utils::ToolTip::show(point, Utils::TextContent(m_toolTip), editorWidget);
+ Utils::ToolTip::show(point, m_toolTip, editorWidget);
}
} // namespace TextEditor
diff --git a/src/plugins/texteditor/behaviorsettingspage.cpp b/src/plugins/texteditor/behaviorsettingspage.cpp
index f7b900ece80..a55538c3326 100644
--- a/src/plugins/texteditor/behaviorsettingspage.cpp
+++ b/src/plugins/texteditor/behaviorsettingspage.cpp
@@ -267,11 +267,11 @@ const ExtraEncodingSettings &BehaviorSettingsPage::extraEncodingSettings() const
void BehaviorSettingsPage::openCodingStylePreferences(TabSettingsWidget::CodingStyleLink link)
{
switch (link) {
- case TextEditor::TabSettingsWidget::CppLink:
+ case TabSettingsWidget::CppLink:
Core::ICore::showOptionsDialog(CppTools::Constants::CPP_SETTINGS_CATEGORY,
CppTools::Constants::CPP_CODE_STYLE_SETTINGS_ID);
break;
- case TextEditor::TabSettingsWidget::QtQuickLink:
+ case TabSettingsWidget::QtQuickLink:
Core::ICore::showOptionsDialog(QmlJSEditor::Constants::SETTINGS_CATEGORY_QML,
QmlJSTools::Constants::QML_JS_CODE_STYLE_SETTINGS_ID);
break;
diff --git a/src/plugins/texteditor/codeassist/codeassistant.cpp b/src/plugins/texteditor/codeassist/codeassistant.cpp
index 25b54ec0343..51b0ab7f880 100644
--- a/src/plugins/texteditor/codeassist/codeassistant.cpp
+++ b/src/plugins/texteditor/codeassist/codeassistant.cpp
@@ -82,7 +82,7 @@ public:
void startAutomaticProposalTimer();
void automaticProposalTimeout();
void clearAbortedPosition();
- void updateCompletionSettings(const TextEditor::CompletionSettings &settings);
+ void updateFromCompletionSettings(const TextEditor::CompletionSettings &settings);
virtual bool eventFilter(QObject *o, QEvent *e);
@@ -115,8 +115,6 @@ private:
// --------------------
const QChar CodeAssistantPrivate::m_null;
-static const int AutomaticProposalTimerInterval = 400;
-
CodeAssistantPrivate::CodeAssistantPrivate(CodeAssistant *assistant)
: q(assistant)
, m_editorWidget(0)
@@ -125,17 +123,14 @@ CodeAssistantPrivate::CodeAssistantPrivate(CodeAssistant *assistant)
, m_assistKind(TextEditor::Completion)
, m_proposalWidget(0)
, m_receivedContentWhileWaiting(false)
- , m_settings(TextEditorSettings::completionSettings())
, m_abortedBasePosition(-1)
{
m_automaticProposalTimer.setSingleShot(true);
- m_automaticProposalTimer.setInterval(AutomaticProposalTimerInterval);
-
connect(&m_automaticProposalTimer, &QTimer::timeout,
this, &CodeAssistantPrivate::automaticProposalTimeout);
connect(TextEditorSettings::instance(), &TextEditorSettings::completionSettingsChanged,
- this, &CodeAssistantPrivate::updateCompletionSettings);
+ this, &CodeAssistantPrivate::updateFromCompletionSettings);
connect(Core::EditorManager::instance(), &Core::EditorManager::currentEditorChanged,
this, &CodeAssistantPrivate::clearAbortedPosition);
@@ -456,9 +451,11 @@ void CodeAssistantPrivate::stopAutomaticProposalTimer()
m_automaticProposalTimer.stop();
}
-void CodeAssistantPrivate::updateCompletionSettings(const TextEditor::CompletionSettings &settings)
+void CodeAssistantPrivate::updateFromCompletionSettings(
+ const TextEditor::CompletionSettings &settings)
{
m_settings = settings;
+ m_automaticProposalTimer.setInterval(m_settings.m_automaticProposalTimeoutInMs);
}
void CodeAssistantPrivate::explicitlyAborted()
@@ -520,6 +517,11 @@ void CodeAssistant::configure(TextEditorWidget *editorWidget)
d->configure(editorWidget);
}
+void CodeAssistant::updateFromCompletionSettings(const CompletionSettings &settings)
+{
+ d->updateFromCompletionSettings(settings);
+}
+
void CodeAssistant::process()
{
d->process();
diff --git a/src/plugins/texteditor/codeassist/codeassistant.h b/src/plugins/texteditor/codeassist/codeassistant.h
index ddfcba5d7d0..983631f04ea 100644
--- a/src/plugins/texteditor/codeassist/codeassistant.h
+++ b/src/plugins/texteditor/codeassist/codeassistant.h
@@ -40,6 +40,7 @@
namespace TextEditor {
class CodeAssistantPrivate;
+class CompletionSettings;
class IAssistProvider;
class TextEditorWidget;
@@ -52,6 +53,7 @@ public:
~CodeAssistant();
void configure(TextEditorWidget *editorWidget);
+ void updateFromCompletionSettings(const TextEditor::CompletionSettings &settings);
void process();
void notifyChange();
diff --git a/src/plugins/texteditor/codeassist/genericproposalmodel.cpp b/src/plugins/texteditor/codeassist/genericproposalmodel.cpp
index 92e4da8510e..3881775bc8a 100644
--- a/src/plugins/texteditor/codeassist/genericproposalmodel.cpp
+++ b/src/plugins/texteditor/codeassist/genericproposalmodel.cpp
@@ -214,7 +214,7 @@ void GenericProposalModel::filter(const QString &prefix)
*
* It also implements the fully and first-letter-only case sensitivity.
*/
- const TextEditor::CaseSensitivity caseSensitivity =
+ const CaseSensitivity caseSensitivity =
TextEditorSettings::completionSettings().m_caseSensitivity;
QString keyRegExp;
@@ -223,8 +223,8 @@ void GenericProposalModel::filter(const QString &prefix)
const QLatin1String uppercaseWordContinuation("[a-z0-9_]*");
const QLatin1String lowercaseWordContinuation("(?:[a-zA-Z0-9]*_)?");
foreach (const QChar &c, prefix) {
- if (caseSensitivity == TextEditor::CaseInsensitive ||
- (caseSensitivity == TextEditor::FirstLetterCaseSensitive && !first)) {
+ if (caseSensitivity == CaseInsensitive ||
+ (caseSensitivity == FirstLetterCaseSensitive && !first)) {
keyRegExp += QLatin1String("(?:");
if (!first)
diff --git a/src/plugins/texteditor/codeassist/genericproposalwidget.cpp b/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
index 585ea6d32f4..6996048bffa 100644
--- a/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
+++ b/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
@@ -145,11 +145,11 @@ QVariant ModelAdapter::data(const QModelIndex &index, int role) const
// ------------------------
// GenericProposalInfoFrame
// ------------------------
-class GenericProposalInfoFrame : public Utils::FakeToolTip
+class GenericProposalInfoFrame : public FakeToolTip
{
public:
GenericProposalInfoFrame(QWidget *parent = 0)
- : Utils::FakeToolTip(parent), m_label(new QLabel(this))
+ : FakeToolTip(parent), m_label(new QLabel(this))
{
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
diff --git a/src/plugins/texteditor/codecselector.cpp b/src/plugins/texteditor/codecselector.cpp
index f767526af1d..94de229f022 100644
--- a/src/plugins/texteditor/codecselector.cpp
+++ b/src/plugins/texteditor/codecselector.cpp
@@ -32,10 +32,10 @@
#include "textdocument.h"
#include <utils/algorithm.h>
+#include <utils/fileutils.h>
#include <utils/itemviews.h>
#include <QDebug>
-#include <QFileInfo>
#include <QTextCodec>
#include <QPushButton>
#include <QScrollBar>
@@ -78,7 +78,9 @@ CodecSelector::CodecSelector(QWidget *parent, TextDocument *doc)
QString decodingErrorHint;
if (m_hasDecodingError)
decodingErrorHint = QLatin1Char('\n') + tr("The following encodings are likely to fit:");
- m_label->setText(tr("Select encoding for \"%1\".%2").arg(QFileInfo(doc->filePath()).fileName()).arg(decodingErrorHint));
+ m_label->setText(tr("Select encoding for \"%1\".%2")
+ .arg(doc->filePath().fileName())
+ .arg(decodingErrorHint));
m_listWidget = new CodecListWidget(this);
m_listWidget->setActivationMode(Utils::DoubleClickActivation);
diff --git a/src/plugins/texteditor/codestylepool.cpp b/src/plugins/texteditor/codestylepool.cpp
index 820c62658bc..9528e913bc8 100644
--- a/src/plugins/texteditor/codestylepool.cpp
+++ b/src/plugins/texteditor/codestylepool.cpp
@@ -32,12 +32,16 @@
#include "icodestylepreferencesfactory.h"
#include "icodestylepreferences.h"
#include "tabsettings.h"
-#include <utils/persistentsettings.h>
+
#include <coreplugin/icore.h>
+#include <utils/fileutils.h>
+#include <utils/persistentsettings.h>
+
#include <QMap>
#include <QDir>
#include <QDebug>
+#include <QFileInfo>
using namespace TextEditor;
@@ -154,7 +158,7 @@ ICodeStylePreferences *CodeStylePool::createCodeStyle(const QByteArray &id, cons
if (!d->m_factory)
return 0;
- TextEditor::ICodeStylePreferences *codeStyle = d->m_factory->createCodeStyle();
+ ICodeStylePreferences *codeStyle = d->m_factory->createCodeStyle();
codeStyle->setId(id);
codeStyle->setTabSettings(tabSettings);
codeStyle->setValue(codeStyleData);
@@ -202,7 +206,7 @@ void CodeStylePool::removeCodeStyle(ICodeStylePreferences *codeStyle)
d->m_idToCodeStyle.remove(codeStyle->id());
QDir dir(settingsDir());
- dir.remove(settingsPath(codeStyle->id()).toFileInfo().fileName());
+ dir.remove(settingsPath(codeStyle->id()).fileName());
delete codeStyle;
}
@@ -226,7 +230,7 @@ void CodeStylePool::loadCustomCodeStyles()
ICodeStylePreferences *CodeStylePool::importCodeStyle(const Utils::FileName &fileName)
{
- TextEditor::ICodeStylePreferences *codeStyle = loadCodeStyle(fileName);
+ ICodeStylePreferences *codeStyle = loadCodeStyle(fileName);
if (codeStyle)
saveCodeStyle(codeStyle);
return codeStyle;
@@ -234,7 +238,7 @@ ICodeStylePreferences *CodeStylePool::importCodeStyle(const Utils::FileName &fil
ICodeStylePreferences *CodeStylePool::loadCodeStyle(const Utils::FileName &fileName)
{
- TextEditor::ICodeStylePreferences *codeStyle = 0;
+ ICodeStylePreferences *codeStyle = 0;
Utils::PersistentSettingsReader reader;
reader.load(fileName);
QVariantMap m = reader.restoreValues();
diff --git a/src/plugins/texteditor/codestyleselectorwidget.cpp b/src/plugins/texteditor/codestyleselectorwidget.cpp
index e64d1a4d799..673bb507b64 100644
--- a/src/plugins/texteditor/codestyleselectorwidget.cpp
+++ b/src/plugins/texteditor/codestyleselectorwidget.cpp
@@ -190,7 +190,7 @@ CodeStyleSelectorWidget::~CodeStyleSelectorWidget()
delete m_ui;
}
-void CodeStyleSelectorWidget::setCodeStyle(TextEditor::ICodeStylePreferences *codeStyle)
+void CodeStyleSelectorWidget::setCodeStyle(ICodeStylePreferences *codeStyle)
{
if (m_codeStyle == codeStyle)
return; // nothing changes
@@ -244,15 +244,15 @@ void CodeStyleSelectorWidget::slotComboBoxActivated(int index)
if (index < 0 || index >= m_ui->delegateComboBox->count())
return;
- TextEditor::ICodeStylePreferences *delegate =
- m_ui->delegateComboBox->itemData(index).value<TextEditor::ICodeStylePreferences *>();
+ ICodeStylePreferences *delegate =
+ m_ui->delegateComboBox->itemData(index).value<ICodeStylePreferences *>();
const bool wasBlocked = blockSignals(true);
m_codeStyle->setCurrentDelegate(delegate);
blockSignals(wasBlocked);
}
-void CodeStyleSelectorWidget::slotCurrentDelegateChanged(TextEditor::ICodeStylePreferences *delegate)
+void CodeStyleSelectorWidget::slotCurrentDelegateChanged(ICodeStylePreferences *delegate)
{
m_ignoreGuiSignals = true;
m_ui->delegateComboBox->setCurrentIndex(m_ui->delegateComboBox->findData(QVariant::fromValue(delegate)));
diff --git a/src/plugins/texteditor/completionsettings.cpp b/src/plugins/texteditor/completionsettings.cpp
index b5c6398a13d..4a26a937985 100644
--- a/src/plugins/texteditor/completionsettings.cpp
+++ b/src/plugins/texteditor/completionsettings.cpp
@@ -35,6 +35,7 @@
static const char groupPostfix[] = "Completion";
static const char caseSensitivityKey[] = "CaseSensitivity";
static const char completionTriggerKey[] = "CompletionTrigger";
+static const char automaticProposalTimeoutKey[] = "AutomaticProposalTimeout";
static const char autoInsertBracesKey[] = "AutoInsertBraces";
static const char surroundingAutoBracketsKey[] = "SurroundingAutoBrackets";
static const char partiallyCompleteKey[] = "PartiallyComplete";
@@ -46,6 +47,7 @@ using namespace TextEditor;
CompletionSettings::CompletionSettings()
: m_caseSensitivity(CaseInsensitive)
, m_completionTrigger(AutomaticCompletion)
+ , m_automaticProposalTimeoutInMs(400)
, m_autoInsertBrackets(true)
, m_surroundingAutoBrackets(true)
, m_partiallyComplete(true)
@@ -63,6 +65,7 @@ void CompletionSettings::toSettings(const QString &category, QSettings *s) const
s->beginGroup(group);
s->setValue(QLatin1String(caseSensitivityKey), (int) m_caseSensitivity);
s->setValue(QLatin1String(completionTriggerKey), (int) m_completionTrigger);
+ s->setValue(QLatin1String(automaticProposalTimeoutKey), m_automaticProposalTimeoutInMs);
s->setValue(QLatin1String(autoInsertBracesKey), m_autoInsertBrackets);
s->setValue(QLatin1String(surroundingAutoBracketsKey), m_surroundingAutoBrackets);
s->setValue(QLatin1String(partiallyCompleteKey), m_partiallyComplete);
@@ -82,6 +85,7 @@ void CompletionSettings::fromSettings(const QString &category, const QSettings *
m_caseSensitivity = (CaseSensitivity) s->value(group + QLatin1String(caseSensitivityKey), m_caseSensitivity).toInt();
m_completionTrigger = (CompletionTrigger) s->value(group + QLatin1String(completionTriggerKey), m_completionTrigger).toInt();
+ m_automaticProposalTimeoutInMs = s->value(group + QLatin1String(automaticProposalTimeoutKey), m_automaticProposalTimeoutInMs).toInt();
m_autoInsertBrackets = s->value(group + QLatin1String(autoInsertBracesKey), m_autoInsertBrackets).toBool();
m_surroundingAutoBrackets = s->value(group + QLatin1String(surroundingAutoBracketsKey), m_surroundingAutoBrackets).toBool();
m_partiallyComplete = s->value(group + QLatin1String(partiallyCompleteKey), m_partiallyComplete).toBool();
@@ -93,6 +97,7 @@ bool CompletionSettings::equals(const CompletionSettings &cs) const
{
return m_caseSensitivity == cs.m_caseSensitivity
&& m_completionTrigger == cs.m_completionTrigger
+ && m_automaticProposalTimeoutInMs == cs.m_automaticProposalTimeoutInMs
&& m_autoInsertBrackets == cs.m_autoInsertBrackets
&& m_surroundingAutoBrackets == cs.m_surroundingAutoBrackets
&& m_partiallyComplete == cs.m_partiallyComplete
diff --git a/src/plugins/texteditor/completionsettings.h b/src/plugins/texteditor/completionsettings.h
index c24f404da6c..06444b8d04f 100644
--- a/src/plugins/texteditor/completionsettings.h
+++ b/src/plugins/texteditor/completionsettings.h
@@ -66,6 +66,7 @@ public:
CaseSensitivity m_caseSensitivity;
CompletionTrigger m_completionTrigger;
+ int m_automaticProposalTimeoutInMs;
bool m_autoInsertBrackets;
bool m_surroundingAutoBrackets;
bool m_partiallyComplete;
diff --git a/src/plugins/texteditor/findincurrentfile.cpp b/src/plugins/texteditor/findincurrentfile.cpp
index c95e0d274bc..6416a8fb2e4 100644
--- a/src/plugins/texteditor/findincurrentfile.cpp
+++ b/src/plugins/texteditor/findincurrentfile.cpp
@@ -32,6 +32,7 @@
#include "texteditor.h"
#include <utils/filesearch.h>
+#include <utils/fileutils.h>
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/editormanager/editormanager.h>
@@ -73,18 +74,18 @@ Utils::FileIterator *FindInCurrentFile::files(const QStringList &nameFilters,
QVariant FindInCurrentFile::additionalParameters() const
{
- return qVariantFromValue(m_currentDocument->filePath());
+ return qVariantFromValue(m_currentDocument->filePath().toString());
}
QString FindInCurrentFile::label() const
{
- return tr("File \"%1\":").arg(QFileInfo(m_currentDocument->filePath()).fileName());
+ return tr("File \"%1\":").arg(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->filePath()));
+ return tr("File path: %1\n%2").arg(m_currentDocument->filePath().toUserOutput());
}
bool FindInCurrentFile::isEnabled() const
diff --git a/src/plugins/texteditor/findinfiles.cpp b/src/plugins/texteditor/findinfiles.cpp
index 7e2a9cd896d..5043682181f 100644
--- a/src/plugins/texteditor/findinfiles.cpp
+++ b/src/plugins/texteditor/findinfiles.cpp
@@ -34,6 +34,7 @@
#include <coreplugin/find/findplugin.h>
#include <utils/filesearch.h>
#include <utils/fileutils.h>
+#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -55,7 +56,7 @@ FindInFiles::FindInFiles()
m_directory(0)
{
m_instance = this;
- connect(Core::EditorManager::instance(), SIGNAL(findOnFileSystemRequest(QString)),
+ connect(EditorManager::instance(), SIGNAL(findOnFileSystemRequest(QString)),
this, SLOT(findOnFileSystem(QString)));
}
@@ -73,7 +74,7 @@ QString FindInFiles::displayName() const
return tr("Files on File System");
}
-void FindInFiles::findAll(const QString &txt, Core::FindFlags findFlags)
+void FindInFiles::findAll(const QString &txt, FindFlags findFlags)
{
updateComboEntries(m_directory, true);
BaseFileFind::findAll(txt, findFlags);
@@ -84,7 +85,7 @@ Utils::FileIterator *FindInFiles::files(const QStringList &nameFilters,
{
return new Utils::SubDirFileIterator(QStringList() << additionalParameters.toString(),
nameFilters,
- Core::EditorManager::defaultTextCodec());
+ EditorManager::defaultTextCodec());
}
QVariant FindInFiles::additionalParameters() const
@@ -129,7 +130,7 @@ QWidget *FindInFiles::createConfigWidget()
syncComboWithSettings(m_directory, m_directorySetting.toUserOutput());
dirLabel->setBuddy(m_directory);
gridLayout->addWidget(m_directory, 0, 1);
- QPushButton *browseButton = new QPushButton(tr("&Browse..."));
+ QPushButton *browseButton = new QPushButton(Utils::PathChooser::browseButtonLabel());
gridLayout->addWidget(browseButton, 0, 2);
connect(browseButton, SIGNAL(clicked()), this, SLOT(openFileBrowser()));
diff --git a/src/plugins/texteditor/fontsettings.cpp b/src/plugins/texteditor/fontsettings.cpp
index 0c18eca50cb..08d6a63f5f1 100644
--- a/src/plugins/texteditor/fontsettings.cpp
+++ b/src/plugins/texteditor/fontsettings.cpp
@@ -31,13 +31,13 @@
#include "fontsettings.h"
#include "fontsettingspage.h"
+#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
#include <coreplugin/icore.h>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
-#include <QFileInfo>
#include <QFont>
#include <QSettings>
#include <QTextCharFormat>
@@ -117,7 +117,7 @@ bool FontSettings::fromSettings(const QString &category,
// Load the selected color scheme
QString scheme = s->value(group + QLatin1String(schemeFileNameKey)).toString();
if (scheme.isEmpty() || !QFile::exists(scheme))
- scheme = defaultSchemeFileName(QFileInfo(scheme).fileName());
+ scheme = defaultSchemeFileName(Utils::FileName::fromString(scheme).fileName());
loadColorScheme(scheme, descriptions);
} else {
// Load color scheme from ini file
diff --git a/src/plugins/texteditor/fontsettingspage.cpp b/src/plugins/texteditor/fontsettingspage.cpp
index 1987379abc1..3be594711a2 100644
--- a/src/plugins/texteditor/fontsettingspage.cpp
+++ b/src/plugins/texteditor/fontsettingspage.cpp
@@ -34,6 +34,7 @@
#include "ui_fontsettingspage.h"
#include <coreplugin/icore.h>
+#include <utils/fileutils.h>
#include <utils/stringutils.h>
#include <utils/qtcassert.h>
@@ -110,7 +111,7 @@ private:
class FontSettingsPagePrivate
{
public:
- FontSettingsPagePrivate(const TextEditor::FormatDescriptions &fd,
+ FontSettingsPagePrivate(const FormatDescriptions &fd,
Core::Id id,
const QString &displayName,
const QString &category);
@@ -121,7 +122,7 @@ public:
const QString m_displayName;
const QString m_settingsGroup;
- TextEditor::FormatDescriptions m_descriptions;
+ FormatDescriptions m_descriptions;
FontSettings m_value;
FontSettings m_lastValue;
QPointer<QWidget> m_widget;
@@ -167,7 +168,7 @@ static QString createColorSchemeFileName(const QString &pattern)
}
// ------- FontSettingsPagePrivate
-FontSettingsPagePrivate::FontSettingsPagePrivate(const TextEditor::FormatDescriptions &fd,
+FontSettingsPagePrivate::FontSettingsPagePrivate(const FormatDescriptions &fd,
Core::Id id,
const QString &displayName,
const QString &category) :
@@ -562,7 +563,7 @@ void FontSettingsPage::refreshColorSchemeList()
int selected = 0;
QStringList schemeList = styleDir.entryList();
- QString defaultScheme = QFileInfo(FontSettings::defaultSchemeFileName()).fileName();
+ QString defaultScheme = Utils::FileName::fromString(FontSettings::defaultSchemeFileName()).fileName();
if (schemeList.removeAll(defaultScheme))
schemeList.prepend(defaultScheme);
foreach (const QString &file, schemeList) {
diff --git a/src/plugins/texteditor/generichighlighter/context.cpp b/src/plugins/texteditor/generichighlighter/context.cpp
index 8c0e134112d..af41010c9df 100644
--- a/src/plugins/texteditor/generichighlighter/context.cpp
+++ b/src/plugins/texteditor/generichighlighter/context.cpp
@@ -129,7 +129,7 @@ bool Context::isDynamic() const
void Context::updateDynamicRules(const QStringList &captures) const
{
- TextEditor::Internal::updateDynamicRules(m_rules, captures);
+ Internal::updateDynamicRules(m_rules, captures);
}
void Context::addRule(const QSharedPointer<Rule> &rule)
diff --git a/src/plugins/texteditor/generichighlighter/highlightdefinition.cpp b/src/plugins/texteditor/generichighlighter/highlightdefinition.cpp
index 7c133893da1..37bd044f724 100644
--- a/src/plugins/texteditor/generichighlighter/highlightdefinition.cpp
+++ b/src/plugins/texteditor/generichighlighter/highlightdefinition.cpp
@@ -35,6 +35,7 @@
#include "itemdata.h"
#include "reuse.h"
+#include <QCoreApplication>
#include <QString>
using namespace TextEditor;
@@ -45,11 +46,16 @@ namespace {
template <class Element, class Container>
QSharedPointer<Element> createHelper(const QString &name, Container &container)
{
- if (name.isEmpty())
- throw HighlighterException();
+ if (name.isEmpty()) {
+ throw HighlighterException(
+ QCoreApplication::translate("GenericHighlighter", "Element name is empty"));
+ }
- if (container.contains(name))
- throw HighlighterException();
+ if (container.contains(name)) {
+ throw HighlighterException(
+ QCoreApplication::translate("GenericHighlighter",
+ "Duplicate element name \"%1\"").arg(name));
+ }
return container.insert(name, QSharedPointer<Element>(new Element)).value();
}
@@ -59,8 +65,11 @@ QSharedPointer<Element>
findHelper(const QString &name, const Container &container)
{
typename Container::const_iterator it = container.find(name);
- if (it == container.end())
- throw HighlighterException();
+ if (it == container.end()) {
+ throw HighlighterException(
+ QCoreApplication::translate("GenericHighlighter",
+ "name \"%1\" not found").arg(name));
+ }
return it.value();
}
diff --git a/src/plugins/texteditor/generichighlighter/highlighter.cpp b/src/plugins/texteditor/generichighlighter/highlighter.cpp
index ca46a2d3d8c..8c482693a6b 100644
--- a/src/plugins/texteditor/generichighlighter/highlighter.cpp
+++ b/src/plugins/texteditor/generichighlighter/highlighter.cpp
@@ -38,8 +38,9 @@
#include "reuse.h"
#include "tabsettings.h"
-#include <QLatin1String>
-#include <QLatin1Char>
+#include <coreplugin/messagemanager.h>
+
+#include <QCoreApplication>
using namespace TextEditor;
using namespace Internal;
@@ -81,7 +82,7 @@ HighlighterCodeFormatterData *formatterData(const QTextBlock &block)
}
Highlighter::Highlighter(QTextDocument *parent) :
- TextEditor::SyntaxHighlighter(parent),
+ SyntaxHighlighter(parent),
m_regionDepth(0),
m_indentationBasedFolding(false),
m_tabSettings(0),
@@ -89,24 +90,24 @@ Highlighter::Highlighter(QTextDocument *parent) :
m_dynamicContextsCounter(0),
m_isBroken(false)
{
- static QVector<TextEditor::TextStyle> categories;
+ static QVector<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 // TODO : add style for alert (eg. yellow background)
- << TextEditor::C_TEXT // TODO : add style for error (eg. red underline)
- << TextEditor::C_FUNCTION
- << TextEditor::C_TEXT
- << TextEditor::C_TEXT
- << TextEditor::C_LOCAL;
+ categories << C_TEXT
+ << C_VISUAL_WHITESPACE
+ << C_KEYWORD
+ << C_TYPE
+ << C_COMMENT
+ << C_NUMBER
+ << C_NUMBER
+ << C_NUMBER
+ << C_STRING
+ << C_STRING
+ << C_TEXT // TODO : add style for alert (eg. yellow background)
+ << C_TEXT // TODO : add style for error (eg. red underline)
+ << C_FUNCTION
+ << C_TEXT
+ << C_TEXT
+ << C_LOCAL;
}
setTextFormatCategories(categories);
@@ -155,6 +156,16 @@ void Highlighter::setTabSettings(const TabSettings &ts)
m_tabSettings = &ts;
}
+static bool isOpeningParenthesis(QChar c)
+{
+ return c == QLatin1Char('{') || c == QLatin1Char('[') || c == QLatin1Char('(');
+}
+
+static bool isClosingParenthesis(QChar c)
+{
+ return c == QLatin1Char('}') || c == QLatin1Char(']') || c == QLatin1Char(')');
+}
+
void Highlighter::highlightBlock(const QString &text)
{
if (!m_defaultContext.isNull() && !m_isBroken) {
@@ -184,7 +195,22 @@ void Highlighter::highlightBlock(const QString &text)
// In the case region depth has changed since the last time the state was set.
setCurrentBlockState(computeState(extractObservableState(currentBlockState())));
}
- } catch (const HighlighterException &) {
+
+ Parentheses parentheses;
+ for (int pos = 0; pos < length; ++pos) {
+ const QChar c = text.at(pos);
+ if (isOpeningParenthesis(c))
+ parentheses.push_back(Parenthesis(Parenthesis::Opened, c, pos));
+ else if (isClosingParenthesis(c))
+ parentheses.push_back(Parenthesis(Parenthesis::Closed, c, pos));
+ }
+ TextDocumentLayout::setParentheses(currentBlock(), parentheses);
+
+ } catch (const HighlighterException &e) {
+ Core::MessageManager::write(
+ QCoreApplication::translate("GenericHighlighter",
+ "Generic highlighter error: ") + e.message(),
+ Core::MessageManager::WithFocus);
m_isBroken = true;
}
}
@@ -367,8 +393,10 @@ void Highlighter::changeContext(const QString &contextName,
if (contextName.startsWith(kPop)) {
QStringList list = contextName.split(kHash, QString::SkipEmptyParts);
for (int i = 0; i < list.size(); ++i) {
- if (m_contexts.isEmpty())
- throw HighlighterException();
+ if (m_contexts.isEmpty()) {
+ throw HighlighterException(
+ QCoreApplication::translate("GenericHighlighter", "Reached empty context"));
+ }
m_contexts.pop_back();
}
diff --git a/src/plugins/texteditor/generichighlighter/highlighterexception.h b/src/plugins/texteditor/generichighlighter/highlighterexception.h
index db57bba662a..a3ba6653ed1 100644
--- a/src/plugins/texteditor/generichighlighter/highlighterexception.h
+++ b/src/plugins/texteditor/generichighlighter/highlighterexception.h
@@ -31,8 +31,20 @@
#ifndef HIGHLIGHTEREXCEPTION_H
#define HIGHLIGHTEREXCEPTION_H
+#include <QString>
+
namespace TextEditor {
-namespace Internal { class HighlighterException {}; }
+namespace Internal {
+class HighlighterException
+{
+public:
+ HighlighterException(const QString &msg) : m_message(msg) {}
+ QString message() const { return m_message; }
+
+private:
+ QString m_message;
+};
+}
} // namespace TextEditor
#endif // HIGHLIGHTEREXCEPTION_H
diff --git a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
index 8673c95f0c0..43e169758e2 100644
--- a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
+++ b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
@@ -37,8 +37,6 @@
#include <QFileInfo>
#include <QMessageBox>
-#include <QDebug>
-
using namespace TextEditor;
using namespace Internal;
@@ -47,7 +45,6 @@ ManageDefinitionsDialog::ManageDefinitionsDialog(
const QString &path,
QWidget *parent) :
QDialog(parent),
- m_definitionsMetaData(metaDataList),
m_path(path)
{
ui.setupUi(this);
@@ -57,20 +54,21 @@ ManageDefinitionsDialog::ManageDefinitionsDialog(
setWindowTitle(tr("Download Definitions"));
- populateDefinitionsWidget();
+ populateDefinitionsWidget(metaDataList);
+ ui.definitionsTable->sortItems(0);
- connect(ui.downloadButton, SIGNAL(clicked()), this, SLOT(downloadDefinitions()));
- connect(ui.allButton, SIGNAL(clicked()), this, SLOT(selectAll()));
- connect(ui.clearButton, SIGNAL(clicked()), this, SLOT(clearSelection()));
- connect(ui.invertButton, SIGNAL(clicked()), this, SLOT(invertSelection()));
+ connect(ui.downloadButton, &QPushButton::clicked, this, &ManageDefinitionsDialog::downloadDefinitions);
+ connect(ui.allButton, &QPushButton::clicked, this, &ManageDefinitionsDialog::selectAll);
+ connect(ui.clearButton, &QPushButton::clicked, this, &ManageDefinitionsDialog::clearSelection);
+ connect(ui.invertButton, &QPushButton::clicked, this, &ManageDefinitionsDialog::invertSelection);
}
-void ManageDefinitionsDialog::populateDefinitionsWidget()
+void ManageDefinitionsDialog::populateDefinitionsWidget(const QList<DefinitionMetaDataPtr> &definitionsMetaData)
{
- const int size = m_definitionsMetaData.size();
+ const int size = definitionsMetaData.size();
ui.definitionsTable->setRowCount(size);
for (int i = 0; i < size; ++i) {
- const HighlightDefinitionMetaData &downloadData = *m_definitionsMetaData.at(i);
+ const HighlightDefinitionMetaData &downloadData = *definitionsMetaData.at(i);
// Look for this definition in the current path specified by the user, not the one
// stored in the settings. So the manager should not be queried for this information.
@@ -87,6 +85,7 @@ void ManageDefinitionsDialog::populateDefinitionsWidget()
QTableWidgetItem *item = new QTableWidgetItem;
if (j == 0) {
item->setText(downloadData.name);
+ item->setData(Qt::UserRole, downloadData.url);
} else if (j == 1) {
item->setText(dirVersion);
item->setTextAlignment(Qt::AlignCenter);
@@ -110,8 +109,10 @@ void ManageDefinitionsDialog::downloadDefinitions()
}
QList<QUrl> urls;
- foreach (const QModelIndex &index, ui.definitionsTable->selectionModel()->selectedRows())
- urls.append(m_definitionsMetaData.at(index.row())->url);
+ foreach (const QModelIndex &index, ui.definitionsTable->selectionModel()->selectedRows()) {
+ const QVariant url = ui.definitionsTable->item(index.row(), 0)->data(Qt::UserRole);
+ urls.append(url.toUrl());
+ }
Manager::instance()->downloadDefinitions(urls, m_path);
accept();
}
diff --git a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.h b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.h
index cc7dbc7e69b..4225f5a8bbb 100644
--- a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.h
+++ b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.h
@@ -34,8 +34,6 @@
#include "ui_managedefinitionsdialog.h"
#include "highlightdefinitionmetadata.h"
-#include <QList>
-
namespace TextEditor {
namespace Internal {
@@ -48,16 +46,13 @@ public:
const QString &path,
QWidget *parent = 0);
-private slots:
+private:
void downloadDefinitions();
void selectAll();
void clearSelection();
void invertSelection();
+ void populateDefinitionsWidget(const QList<DefinitionMetaDataPtr> &definitionsMetaData);
-private:
- void populateDefinitionsWidget();
-
- QList<DefinitionMetaDataPtr> m_definitionsMetaData;
QString m_path;
Ui::ManageDefinitionsDialog ui;
};
diff --git a/src/plugins/texteditor/generichighlighter/manager.cpp b/src/plugins/texteditor/generichighlighter/manager.cpp
index fbcf0419029..e7fdf65a34e 100644
--- a/src/plugins/texteditor/generichighlighter/manager.cpp
+++ b/src/plugins/texteditor/generichighlighter/manager.cpp
@@ -39,14 +39,14 @@
#include <texteditor/texteditorsettings.h>
#include <coreplugin/icore.h>
+#include <coreplugin/messagemanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <utils/algorithm.h>
#include <utils/QtConcurrentTools>
#include <utils/networkaccessmanager.h>
+#include <QCoreApplication>
#include <QString>
-#include <QLatin1Char>
-#include <QLatin1String>
#include <QStringList>
#include <QFile>
#include <QFileInfo>
@@ -175,7 +175,11 @@ QSharedPointer<HighlightDefinition> Manager::definition(const QString &id)
m_isBuildingDefinition.insert(id);
try {
reader.parse(source);
- } catch (HighlighterException &) {
+ } catch (const HighlighterException &e) {
+ MessageManager::write(
+ QCoreApplication::translate("GenericHighlighter",
+ "Generic highlighter error: ") + e.message(),
+ MessageManager::WithFocus);
definition.clear();
}
m_isBuildingDefinition.remove(id);
@@ -359,13 +363,8 @@ void Manager::registerMimeTypesFinished()
const QPair<RegisterData, QList<MimeType> > &result = m_registeringWatcher.result();
m_register = result.first;
- PlainTextEditorFactory *factory = PlainTextEditorFactory::instance();
- const QSet<QString> &inFactory = factory->mimeTypes().toSet();
- foreach (const MimeType &mimeType, result.second) {
+ foreach (const MimeType &mimeType, result.second)
MimeDatabase::addMimeType(mimeType);
- if (!inFactory.contains(mimeType.type()))
- factory->addMimeType(mimeType.type());
- }
emit mimeTypesRegistered();
}
diff --git a/src/plugins/texteditor/highlighterutils.cpp b/src/plugins/texteditor/highlighterutils.cpp
index 120463d5311..fec5ec798f2 100644
--- a/src/plugins/texteditor/highlighterutils.cpp
+++ b/src/plugins/texteditor/highlighterutils.cpp
@@ -70,7 +70,7 @@ void TextEditor::setMimeTypeForHighlighter(Highlighter *highlighter, const Core:
SyntaxHighlighter *TextEditor::createGenericSyntaxHighlighter(const Core::MimeType &mimeType)
{
- TextEditor::Highlighter *highlighter = new TextEditor::Highlighter();
+ Highlighter *highlighter = new Highlighter();
setMimeTypeForHighlighter(highlighter, mimeType);
return highlighter;
}
diff --git a/src/plugins/texteditor/indenter.cpp b/src/plugins/texteditor/indenter.cpp
index 927b1f39241..606c84c9bed 100644
--- a/src/plugins/texteditor/indenter.cpp
+++ b/src/plugins/texteditor/indenter.cpp
@@ -50,7 +50,7 @@ bool Indenter::isElectricCharacter(const QChar &) const
void Indenter::indentBlock(QTextDocument *doc,
const QTextBlock &block,
const QChar &typedChar,
- const TextEditor::TabSettings &tabSettings)
+ const TabSettings &tabSettings)
{
Q_UNUSED(doc);
Q_UNUSED(block);
@@ -61,7 +61,7 @@ void Indenter::indentBlock(QTextDocument *doc,
void Indenter::indent(QTextDocument *doc,
const QTextCursor &cursor,
const QChar &typedChar,
- const TextEditor::TabSettings &tabSettings)
+ const TabSettings &tabSettings)
{
if (cursor.hasSelection()) {
QTextBlock block = doc->findBlock(cursor.selectionStart());
@@ -75,7 +75,7 @@ void Indenter::indent(QTextDocument *doc,
}
}
-void Indenter::reindent(QTextDocument *doc, const QTextCursor &cursor, const TextEditor::TabSettings &tabSettings)
+void Indenter::reindent(QTextDocument *doc, const QTextCursor &cursor, const TabSettings &tabSettings)
{
if (cursor.hasSelection()) {
QTextBlock block = doc->findBlock(cursor.selectionStart());
diff --git a/src/plugins/texteditor/ioutlinewidget.h b/src/plugins/texteditor/ioutlinewidget.h
index ddf0782d720..0403c2cb7df 100644
--- a/src/plugins/texteditor/ioutlinewidget.h
+++ b/src/plugins/texteditor/ioutlinewidget.h
@@ -33,6 +33,7 @@
#include <texteditor/texteditor_global.h>
#include <QWidget>
+#include <QVariantMap>
namespace Core { class IEditor; }
@@ -47,8 +48,8 @@ public:
virtual QList<QAction*> filterMenuActions() const = 0;
virtual void setCursorSynchronization(bool syncWithCursor) = 0;
- virtual void restoreSettings(int position) { Q_UNUSED(position); }
- virtual void saveSettings(int position) { Q_UNUSED(position); }
+ virtual void restoreSettings(const QVariantMap & /*map*/) { }
+ virtual QVariantMap settings() const { return QVariantMap(); }
};
class TEXTEDITOR_EXPORT IOutlineWidgetFactory : public QObject {
diff --git a/src/plugins/texteditor/linenumberfilter.cpp b/src/plugins/texteditor/linenumberfilter.cpp
index b7ba9836a76..d16ffd55fda 100644
--- a/src/plugins/texteditor/linenumberfilter.cpp
+++ b/src/plugins/texteditor/linenumberfilter.cpp
@@ -63,7 +63,7 @@ void LineNumberFilter::prepareSearch(const QString &entry)
m_hasCurrentEditor = EditorManager::currentEditor() != 0;
}
-QList<LocatorFilterEntry> LineNumberFilter::matchesFor(QFutureInterface<Core::LocatorFilterEntry> &, const QString &entry)
+QList<LocatorFilterEntry> LineNumberFilter::matchesFor(QFutureInterface<LocatorFilterEntry> &, const QString &entry)
{
QList<LocatorFilterEntry> value;
QStringList lineAndColumn = entry.split(QLatin1Char(':'));
diff --git a/src/plugins/texteditor/normalindenter.cpp b/src/plugins/texteditor/normalindenter.cpp
index 621c4eefe8d..e7c5a04ace2 100644
--- a/src/plugins/texteditor/normalindenter.cpp
+++ b/src/plugins/texteditor/normalindenter.cpp
@@ -63,7 +63,7 @@ NormalIndenter::~NormalIndenter()
void NormalIndenter::indentBlock(QTextDocument *doc,
const QTextBlock &block,
const QChar &typedChar,
- const TextEditor::TabSettings &tabSettings)
+ const TabSettings &tabSettings)
{
Q_UNUSED(typedChar)
diff --git a/src/plugins/texteditor/outlinefactory.cpp b/src/plugins/texteditor/outlinefactory.cpp
index 1467ab6a899..b5db21d2142 100644
--- a/src/plugins/texteditor/outlinefactory.cpp
+++ b/src/plugins/texteditor/outlinefactory.cpp
@@ -45,8 +45,7 @@ namespace Internal {
OutlineWidgetStack::OutlineWidgetStack(OutlineFactory *factory) :
QStackedWidget(),
m_factory(factory),
- m_syncWithEditor(true),
- m_position(-1)
+ m_syncWithEditor(true)
{
QLabel *label = new QLabel(tr("No outline available"), this);
label->setAlignment(Qt::AlignCenter);
@@ -91,32 +90,37 @@ QToolButton *OutlineWidgetStack::filterButton()
return m_filterButton;
}
-static inline QString outLineKey(int position)
-{
- return QLatin1String("Outline.") + QString::number(position) + QLatin1String(".SyncWithEditor");
-}
-
void OutlineWidgetStack::restoreSettings(int position)
{
- m_position = position; // save it so that we can save/restore in updateCurrentEditor
-
QSettings *settings = Core::ICore::settings();
- const bool toggleSync = settings->value(outLineKey(position), true).toBool();
- toggleSyncButton()->setChecked(toggleSync);
+ settings->beginGroup(QLatin1String("Sidebar.Outline.") + QString::number(position));
+
+ bool syncWithEditor = true;
+ m_widgetSettings.clear();
+ foreach (const QString &key, settings->allKeys()) {
+ if (key == QLatin1String("SyncWithEditor")) {
+ syncWithEditor = settings->value(key).toBool();
+ continue;
+ }
+ m_widgetSettings.insert(key, settings->value(key));
+ }
+ settings->endGroup();
+ toggleSyncButton()->setChecked(syncWithEditor);
if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
- outlineWidget->restoreSettings(position);
+ outlineWidget->restoreSettings(m_widgetSettings);
}
void OutlineWidgetStack::saveSettings(int position)
{
- Q_ASSERT(position == m_position);
-
QSettings *settings = Core::ICore::settings();
- settings->setValue(outLineKey(position), toggleSyncButton()->isEnabled());
+ settings->beginGroup(QLatin1String("Sidebar.Outline.") + QString::number(position));
- if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
- outlineWidget->saveSettings(position);
+ settings->setValue(QLatin1String("SyncWithEditor"), toggleSyncButton()->isChecked());
+ for (auto iter = m_widgetSettings.constBegin(); iter != m_widgetSettings.constEnd(); ++iter)
+ settings->setValue(iter.key(), iter.value());
+
+ settings->endGroup();
}
bool OutlineWidgetStack::isCursorSynchronized() const
@@ -158,14 +162,14 @@ void OutlineWidgetStack::updateCurrentEditor(Core::IEditor *editor)
if (newWidget != currentWidget()) {
// delete old widget
if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget())) {
- if (m_position > -1)
- outlineWidget->saveSettings(m_position);
+ QVariantMap widgetSettings = outlineWidget->settings();
+ for (auto iter = widgetSettings.constBegin(); iter != widgetSettings.constEnd(); ++iter)
+ m_widgetSettings.insert(iter.key(), iter.value());
removeWidget(outlineWidget);
delete outlineWidget;
}
if (newWidget) {
- if (m_position > -1)
- newWidget->restoreSettings(m_position);
+ newWidget->restoreSettings(m_widgetSettings);
newWidget->setCursorSynchronization(m_syncWithEditor);
addWidget(newWidget);
setCurrentWidget(newWidget);
diff --git a/src/plugins/texteditor/outlinefactory.h b/src/plugins/texteditor/outlinefactory.h
index fbb872139a4..dd7b1db4962 100644
--- a/src/plugins/texteditor/outlinefactory.h
+++ b/src/plugins/texteditor/outlinefactory.h
@@ -71,8 +71,8 @@ private:
QToolButton *m_toggleSync;
QToolButton *m_filterButton;
QMenu *m_filterMenu;
+ QVariantMap m_widgetSettings;
bool m_syncWithEditor;
- int m_position;
};
class OutlineFactory : public Core::INavigationWidgetFactory
diff --git a/src/plugins/texteditor/refactoringchanges.cpp b/src/plugins/texteditor/refactoringchanges.cpp
index 8424d00171e..5685e75c881 100644
--- a/src/plugins/texteditor/refactoringchanges.cpp
+++ b/src/plugins/texteditor/refactoringchanges.cpp
@@ -161,7 +161,7 @@ RefactoringFile::RefactoringFile(QTextDocument *document, const QString &fileNam
{ }
RefactoringFile::RefactoringFile(TextEditorWidget *editor)
- : m_fileName(editor->textDocument()->filePath())
+ : m_fileName(editor->textDocument()->filePath().toString())
, m_document(0)
, m_editor(editor)
, m_openEditor(false)
diff --git a/src/plugins/texteditor/semantichighlighter.cpp b/src/plugins/texteditor/semantichighlighter.cpp
index 4146866fac2..e0a9e341279 100644
--- a/src/plugins/texteditor/semantichighlighter.cpp
+++ b/src/plugins/texteditor/semantichighlighter.cpp
@@ -40,7 +40,7 @@
using namespace TextEditor;
using namespace TextEditor::SemanticHighlighter;
-void TextEditor::SemanticHighlighter::incrementalApplyExtraAdditionalFormats(
+void SemanticHighlighter::incrementalApplyExtraAdditionalFormats(
SyntaxHighlighter *highlighter,
const QFuture<HighlightingResult> &future,
int from, int to,
@@ -110,7 +110,7 @@ void TextEditor::SemanticHighlighter::incrementalApplyExtraAdditionalFormats(
}
}
-void TextEditor::SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd(
+void SemanticHighlighter::clearExtraAdditionalFormatsUntilEnd(
SyntaxHighlighter *highlighter,
const QFuture<HighlightingResult> &future)
{
diff --git a/src/plugins/texteditor/snippets/plaintextsnippetprovider.cpp b/src/plugins/texteditor/snippets/plaintextsnippetprovider.cpp
index 66dfa79433c..cffe7f47729 100644
--- a/src/plugins/texteditor/snippets/plaintextsnippetprovider.cpp
+++ b/src/plugins/texteditor/snippets/plaintextsnippetprovider.cpp
@@ -54,5 +54,5 @@ QString PlainTextSnippetProvider::displayName() const
return QCoreApplication::translate("TextEditor::Internal::PlainTextSnippetProvider", "Text");
}
-void PlainTextSnippetProvider::decorateEditor(TextEditor::SnippetEditorWidget *) const
+void PlainTextSnippetProvider::decorateEditor(SnippetEditorWidget *) const
{}
diff --git a/src/plugins/texteditor/syntaxhighlighter.cpp b/src/plugins/texteditor/syntaxhighlighter.cpp
index d756358ba74..f5a3dd437d7 100644
--- a/src/plugins/texteditor/syntaxhighlighter.cpp
+++ b/src/plugins/texteditor/syntaxhighlighter.cpp
@@ -41,9 +41,9 @@
#include <math.h>
-using namespace TextEditor;
+namespace TextEditor {
-class TextEditor::SyntaxHighlighterPrivate
+class SyntaxHighlighterPrivate
{
SyntaxHighlighter *q_ptr;
Q_DECLARE_PUBLIC(SyntaxHighlighter)
@@ -74,7 +74,7 @@ public:
}
void applyFormatChanges(int from, int charsRemoved, int charsAdded);
- void updateFormatsForCategories(const TextEditor::FontSettings &fontSettings);
+ void updateFormatsForCategories(const FontSettings &fontSettings);
QVector<QTextCharFormat> formatChanges;
QTextBlock currentBlock;
@@ -82,7 +82,7 @@ public:
bool inReformatBlocks;
TextDocumentLayout::FoldValidator foldValidator;
QVector<QTextCharFormat> formats;
- QVector<TextEditor::TextStyle> formatCategories;
+ QVector<TextStyle> formatCategories;
};
static bool adjustRange(QTextLayout::FormatRange &range, int from, int charsRemoved, int charsAdded) {
@@ -735,13 +735,13 @@ QList<QColor> SyntaxHighlighter::generateColors(int n, const QColor &background)
return result;
}
-void SyntaxHighlighter::setFontSettings(const TextEditor::FontSettings &fontSettings)
+void SyntaxHighlighter::setFontSettings(const FontSettings &fontSettings)
{
Q_D(SyntaxHighlighter);
d->updateFormatsForCategories(fontSettings);
}
-void SyntaxHighlighter::setTextFormatCategories(const QVector<TextEditor::TextStyle> &categories)
+void SyntaxHighlighter::setTextFormatCategories(const QVector<TextStyle> &categories)
{
Q_D(SyntaxHighlighter);
d->formatCategories = categories;
@@ -756,10 +756,11 @@ QTextCharFormat SyntaxHighlighter::formatForCategory(int category) const
return d->formats.at(category);
}
-void SyntaxHighlighterPrivate::updateFormatsForCategories(const TextEditor::FontSettings &fontSettings)
+void SyntaxHighlighterPrivate::updateFormatsForCategories(const FontSettings &fontSettings)
{
formats = fontSettings.toTextCharFormats(formatCategories);
}
+} // namespace TextEditor
#include "moc_syntaxhighlighter.cpp"
diff --git a/src/plugins/texteditor/textdocument.cpp b/src/plugins/texteditor/textdocument.cpp
index 6559f5f218f..af37bf3d1dc 100644
--- a/src/plugins/texteditor/textdocument.cpp
+++ b/src/plugins/texteditor/textdocument.cpp
@@ -231,7 +231,7 @@ QMap<QString, QString> TextDocument::openedTextDocumentContents()
TextDocument *textEditorDocument = qobject_cast<TextDocument *>(document);
if (!textEditorDocument)
continue;
- QString fileName = textEditorDocument->filePath();
+ QString fileName = textEditorDocument->filePath().toString();
workingCopy[fileName] = textEditorDocument->plainText();
}
return workingCopy;
@@ -244,7 +244,7 @@ QMap<QString, QTextCodec *> TextDocument::openedTextDocumentEncodings()
TextDocument *textEditorDocument = qobject_cast<TextDocument *>(document);
if (!textEditorDocument)
continue;
- QString fileName = textEditorDocument->filePath();
+ QString fileName = textEditorDocument->filePath().toString();
workingCopy[fileName] = const_cast<QTextCodec *>(textEditorDocument->codec());
}
return workingCopy;
@@ -466,7 +466,7 @@ bool TextDocument::save(QString *errorString, const QString &saveFileName, bool
cursor.endEditBlock();
}
- QString fName = filePath();
+ QString fName = filePath().toString();
if (!saveFileName.isEmpty())
fName = saveFileName;
@@ -509,7 +509,7 @@ bool TextDocument::save(QString *errorString, const QString &saveFileName, bool
// inform about the new filename
const QFileInfo fi(fName);
d->m_document.setModified(false); // also triggers update of the block revisions
- setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
+ setFilePath(Utils::FileName::fromUserInput(fi.absoluteFilePath()));
emit changed();
return true;
}
@@ -524,12 +524,11 @@ bool TextDocument::shouldAutoSave() const
return d->m_autoSaveRevision != d->m_document.revision();
}
-void TextDocument::setFilePath(const QString &newName)
+void TextDocument::setFilePath(const Utils::FileName &newName)
{
if (newName == filePath())
return;
- const QFileInfo fi(newName);
- IDocument::setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
+ IDocument::setFilePath(Utils::FileName::fromUserInput(newName.toFileInfo().absoluteFilePath()));
}
bool TextDocument::isFileReadOnly() const
@@ -548,8 +547,7 @@ void TextDocument::checkPermissions()
{
bool previousReadOnly = d->m_fileIsReadOnly;
if (!filePath().isEmpty()) {
- const QFileInfo fi(filePath());
- d->m_fileIsReadOnly = !fi.isWritable();
+ d->m_fileIsReadOnly = !filePath().toFileInfo().isWritable();
} else {
d->m_fileIsReadOnly = false;
}
@@ -598,7 +596,7 @@ bool TextDocument::open(QString *errorString, const QString &fileName, const QSt
documentLayout->lastSaveRevision = d->m_autoSaveRevision = d->m_document.revision();
d->updateRevisions();
d->m_document.setModified(fileName != realFileName);
- setFilePath(QDir::cleanPath(fi.absoluteFilePath()));
+ setFilePath(Utils::FileName::fromUserInput(fi.absoluteFilePath()));
}
return readResult == Utils::TextFileFormat::ReadSuccess
|| readResult == Utils::TextFileFormat::ReadEncodingError;
@@ -620,7 +618,7 @@ bool TextDocument::reload(QString *errorString)
if (documentLayout)
marks = documentLayout->documentClosing(); // removes text marks non-permanently
- bool success = open(errorString, filePath(), filePath());
+ bool success = open(errorString, filePath().toString(), filePath().toString());
if (documentLayout)
documentLayout->documentReloaded(marks, this); // re-adds text marks
diff --git a/src/plugins/texteditor/textdocument.h b/src/plugins/texteditor/textdocument.h
index 5a3da885b44..7378807372e 100644
--- a/src/plugins/texteditor/textdocument.h
+++ b/src/plugins/texteditor/textdocument.h
@@ -111,7 +111,7 @@ public:
bool isSaveAsAllowed() const;
void checkPermissions();
bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
- void setFilePath(const QString &newName);
+ void setFilePath(const Utils::FileName &newName);
QString defaultPath() const;
QString suggestedFileName() const;
diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp
index 2c502f60df2..f1ab42e0b25 100644
--- a/src/plugins/texteditor/texteditor.cpp
+++ b/src/plugins/texteditor/texteditor.cpp
@@ -75,7 +75,6 @@
#include <utils/qtcassert.h>
#include <utils/stylehelper.h>
#include <utils/tooltip/tooltip.h>
-#include <utils/tooltip/tipcontents.h>
#include <utils/uncommentselection.h>
#include <QAbstractTextDocumentLayout>
@@ -287,8 +286,8 @@ public:
void processTooltipRequest(const QTextCursor &c);
- void transformSelection(Internal::TransformationMethod method);
- void transformBlockSelection(Internal::TransformationMethod method);
+ void transformSelection(TransformationMethod method);
+ void transformBlockSelection(TransformationMethod method);
bool inFindScope(const QTextCursor &cursor);
bool inFindScope(int selectionStart, int selectionEnd);
@@ -417,7 +416,7 @@ public:
QTextCursor m_selectBlockAnchor;
- Internal::TextBlockSelection m_blockSelection;
+ TextBlockSelection m_blockSelection;
void moveCursorVisible(bool ensureVisible = true);
@@ -436,7 +435,7 @@ public:
QPoint m_markDragStart;
bool m_markDragging;
- QScopedPointer<Internal::ClipboardAssistProvider> m_clipboardAssistProvider;
+ QScopedPointer<ClipboardAssistProvider> m_clipboardAssistProvider;
bool m_isMissingSyntaxDefinition;
@@ -491,7 +490,7 @@ TextEditorWidgetPrivate::TextEditorWidgetPrivate(TextEditorWidget *parent)
m_cursorBlockNumber(-1),
m_blockCount(0),
m_markDragging(false),
- m_clipboardAssistProvider(new Internal::ClipboardAssistProvider),
+ m_clipboardAssistProvider(new ClipboardAssistProvider),
m_isMissingSyntaxDefinition(false),
m_autoCompleter(new AutoCompleter)
{
@@ -1018,6 +1017,12 @@ TextDocumentPtr TextEditorWidget::textDocumentPtr() const
return d->m_document;
}
+TextEditorWidget *TextEditorWidget::currentTextEditorWidget()
+{
+ BaseTextEditor *editor = qobject_cast<BaseTextEditor *>(EditorManager::currentEditor());
+ return editor ? editor->editorWidget() : 0;
+}
+
void TextEditorWidgetPrivate::editorContentsChange(int position, int charsRemoved, int charsAdded)
{
if (m_animator)
@@ -2728,7 +2733,7 @@ void TextEditorWidgetPrivate::updateCodeFoldingVisible()
void TextEditorWidgetPrivate::reconfigure()
{
- q->configureMimeType(MimeDatabase::findByFile(m_document->filePath()));
+ q->configureMimeType(MimeDatabase::findByFile(m_document->filePath().toString()));
}
bool TextEditorWidget::codeFoldingVisible() const
@@ -3006,9 +3011,8 @@ bool TextEditorWidget::viewportEvent(QEvent *event)
RefactorMarker refactorMarker = d->m_refactorOverlay->markerAt(pos);
if (refactorMarker.isValid() && !refactorMarker.tooltip.isEmpty()) {
- ToolTip::show(he->globalPos(), TextContent(refactorMarker.tooltip),
- viewport(),
- refactorMarker.rect);
+ ToolTip::show(he->globalPos(), refactorMarker.tooltip,
+ viewport(), refactorMarker.rect);
return true;
}
@@ -5356,7 +5360,7 @@ bool TextEditorWidget::openLink(const Link &link, bool inNextSplit)
if (!link.hasValidTarget())
return false;
- if (!inNextSplit && textDocument()->filePath() == link.targetFileName) {
+ if (!inNextSplit && textDocument()->filePath().toString() == link.targetFileName) {
EditorManager::addCurrentPositionToNavigationHistory();
gotoLine(link.targetLine, link.targetColumn);
setFocus();
@@ -5867,14 +5871,14 @@ QList<QTextEdit::ExtraSelection> TextEditorWidget::extraSelections(ExtraSelectio
return d->m_extraSelections[kind];
}
-void TextEditorWidget::setExtraSelections(Core::Id kind, const QList<QTextEdit::ExtraSelection> &selections)
+void TextEditorWidget::setExtraSelections(Id kind, const QList<QTextEdit::ExtraSelection> &selections)
{
// Private Core:Id identifiers from the 0-1000 range cannot be used here, they conflict with ExtraSelectionKind
QTC_ASSERT(kind.uniqueIdentifier() >= NExtraSelectionKinds, return);
d->setExtraSelections(kind.uniqueIdentifier(), selections);
}
-QList<QTextEdit::ExtraSelection> TextEditorWidget::extraSelections(Core::Id kind) const
+QList<QTextEdit::ExtraSelection> TextEditorWidget::extraSelections(Id kind) const
{
// Private Core:Id identifiers from the 0-1000 range cannot be used here, they conflict with ExtraSelectionKind
QTC_ASSERT(kind.uniqueIdentifier() >= NExtraSelectionKinds, return QList<QTextEdit::ExtraSelection>());
@@ -6151,6 +6155,7 @@ void TextEditorWidget::setDisplaySettings(const DisplaySettings &ds)
setHighlightCurrentLine(ds.m_highlightCurrentLine);
setRevisionsVisible(ds.m_markTextChanges);
setCenterOnScroll(ds.m_centerCursorOnScroll);
+ setParenthesesMatchingEnabled(ds.m_highlightMatchingParentheses);
d->m_fileEncodingLabelAction->setVisible(ds.m_displayFileEncoding);
if (d->m_displaySettings.m_visualizeWhitespace != ds.m_visualizeWhitespace) {
@@ -6206,6 +6211,7 @@ void TextEditorWidget::setCompletionSettings(const CompletionSettings &completio
d->m_autoCompleter->setAutoParenthesesEnabled(completionSettings.m_autoInsertBrackets);
d->m_autoCompleter->setSurroundWithEnabled(completionSettings.m_autoInsertBrackets
&& completionSettings.m_surroundingAutoBrackets);
+ d->m_codeAssistant.updateFromCompletionSettings(completionSettings);
}
void TextEditorWidget::setExtraEncodingSettings(const ExtraEncodingSettings &extraEncodingSettings)
@@ -6702,11 +6708,6 @@ void BaseTextEditor::convertPosition(int pos, int *line, int *column) const
editorWidget()->convertPosition(pos, line, column);
}
-QRect BaseTextEditor::cursorRect(int pos) const
-{
- return editorWidget()->cursorRect(pos);
-}
-
QString BaseTextEditor::selectedText() const
{
return editorWidget()->selectedText();
@@ -7093,7 +7094,7 @@ AssistInterface *TextEditorWidget::createAssistInterface(AssistKind kind,
AssistReason reason) const
{
Q_UNUSED(kind);
- return new AssistInterface(document(), position(), d->m_document->filePath(), reason);
+ return new AssistInterface(document(), position(), d->m_document->filePath().toString(), reason);
}
QString TextEditorWidget::foldReplacementText(const QTextBlock &) const
@@ -7130,11 +7131,6 @@ TextEditorWidget *BaseTextEditor::editorWidget() const
return static_cast<TextEditorWidget *>(m_widget.data());
}
-QTextDocument *BaseTextEditor::qdocument() const
-{
- return textDocument()->document();
-}
-
void BaseTextEditor::setTextCursor(const QTextCursor &cursor)
{
editorWidget()->setTextCursor(cursor);
@@ -7202,7 +7198,7 @@ void TextEditorWidget::configureMimeType(const MimeType &mimeType)
setCodeFoldingSupported(true);
}
} else {
- const QString &fileName = textDocument()->filePath();
+ const QString &fileName = textDocument()->filePath().toString();
if (TextEditorSettings::highlighterSettings().isIgnoredFilePattern(fileName))
d->m_isMissingSyntaxDefinition = false;
}
@@ -7266,7 +7262,7 @@ void TextEditorLinkLabel::mouseMoveEvent(QMouseEvent *event)
if ((event->pos() - m_dragStartPosition).manhattanLength() < QApplication::startDragDistance())
return;
- auto data = new Utils::FileDropMimeData;
+ auto data = new FileDropMimeData;
data->addFile(m_link.targetFileName, m_link.targetLine, m_link.targetColumn);
auto drag = new QDrag(this);
drag->setMimeData(data);
@@ -7279,9 +7275,7 @@ void TextEditorLinkLabel::mouseReleaseEvent(QMouseEvent *event)
if (!m_link.hasValidTarget())
return;
- Core::EditorManager::openEditorAt(m_link.targetFileName,
- m_link.targetLine,
- m_link.targetColumn);
+ EditorManager::openEditorAt(m_link.targetFileName, m_link.targetLine, m_link.targetColumn);
}
//
@@ -7321,7 +7315,7 @@ public:
TextEditorFactory::AutoCompleterCreator m_autoCompleterCreator;
TextEditorFactory::IndenterCreator m_indenterCreator;
TextEditorFactory::SyntaxHighLighterCreator m_syntaxHighlighterCreator;
- Utils::CommentDefinition::Style m_commentStyle;
+ CommentDefinition::Style m_commentStyle;
QList<BaseHoverHandler *> m_hoverHandlers; // owned
CompletionAssistProvider * m_completionAssistProvider; // owned
bool m_duplicatedSupported;
@@ -7481,14 +7475,14 @@ BaseTextEditor *TextEditorFactoryPrivate::createEditorHelper(const TextDocumentP
widget->d->m_commentDefinition.setStyle(m_commentStyle);
QObject::connect(widget, &TextEditorWidget::activateEditor,
- [editor]() { Core::EditorManager::activateEditor(editor); });
+ [editor]() { EditorManager::activateEditor(editor); });
widget->finalizeInitialization();
editor->finalizeInitialization();
QObject::connect(widget->d->m_cursorPositionLabel, &LineColumnLabel::clicked, [editor] {
EditorManager::activateEditor(editor, EditorManager::IgnoreNavigationHistory);
- if (Core::Command *cmd = ActionManager::command(Core::Constants::GOTO)) {
+ if (Command *cmd = ActionManager::command(Core::Constants::GOTO)) {
if (QAction *act = cmd->action())
act->trigger();
}
diff --git a/src/plugins/texteditor/texteditor.h b/src/plugins/texteditor/texteditor.h
index 1dfe83807b2..bdc0e74c41f 100644
--- a/src/plugins/texteditor/texteditor.h
+++ b/src/plugins/texteditor/texteditor.h
@@ -147,7 +147,6 @@ public:
TextDocument *textDocument() const;
// Some convenience text access
- QTextDocument *qdocument() const;
void setTextCursor(const QTextCursor &cursor);
QTextCursor textCursor() const;
QChar characterAt(int pos) const;
@@ -184,9 +183,6 @@ public:
/*! Converts the \a pos in characters from beginning of document to \a line and \a column */
virtual void convertPosition(int pos, int *line, int *column) const;
- /*! Returns the cursor rectangle in pixels at \a pos, or current position if \a pos = -1 */
- virtual QRect cursorRect(int pos = -1) const;
-
virtual QString selectedText() const;
/*! Removes \a length characters to the right of the cursor. */
@@ -574,6 +570,8 @@ public:
QString contextHelpId();
void setContextHelpId(const QString &id);
+ static TextEditorWidget *currentTextEditorWidget();
+
protected:
/*!
Reimplement this function to enable code navigation.
diff --git a/src/plugins/texteditor/texteditorsettings.cpp b/src/plugins/texteditor/texteditorsettings.cpp
index 0121d1e3617..8e09907fb31 100644
--- a/src/plugins/texteditor/texteditorsettings.cpp
+++ b/src/plugins/texteditor/texteditorsettings.cpp
@@ -273,14 +273,14 @@ TextEditorSettings::TextEditorSettings(QObject *parent)
ExtensionSystem::PluginManager::addObject(d->m_fontSettingsPage);
// Add the GUI used to configure the tab, storage and interaction settings
- TextEditor::BehaviorSettingsPageParameters behaviorSettingsPageParameters;
+ BehaviorSettingsPageParameters behaviorSettingsPageParameters;
behaviorSettingsPageParameters.id = Constants::TEXT_EDITOR_BEHAVIOR_SETTINGS;
behaviorSettingsPageParameters.displayName = tr("Behavior");
behaviorSettingsPageParameters.settingsPrefix = QLatin1String("text");
d->m_behaviorSettingsPage = new BehaviorSettingsPage(behaviorSettingsPageParameters, this);
ExtensionSystem::PluginManager::addObject(d->m_behaviorSettingsPage);
- TextEditor::DisplaySettingsPageParameters displaySettingsPageParameters;
+ DisplaySettingsPageParameters displaySettingsPageParameters;
displaySettingsPageParameters.id = Constants::TEXT_EDITOR_DISPLAY_SETTINGS;
displaySettingsPageParameters.displayName = tr("Display");
displaySettingsPageParameters.settingsPrefix = QLatin1String("text");
@@ -377,7 +377,7 @@ const ExtraEncodingSettings &TextEditorSettings::extraEncodingSettings()
return d->m_behaviorSettingsPage->extraEncodingSettings();
}
-void TextEditorSettings::setCompletionSettings(const TextEditor::CompletionSettings &settings)
+void TextEditorSettings::setCompletionSettings(const CompletionSettings &settings)
{
if (d->m_completionSettings == settings)
return;
diff --git a/src/plugins/texteditor/textmark.cpp b/src/plugins/texteditor/textmark.cpp
index e97f6a9e347..222a0ba06f7 100644
--- a/src/plugins/texteditor/textmark.cpp
+++ b/src/plugins/texteditor/textmark.cpp
@@ -209,15 +209,15 @@ bool TextMarkRegistry::remove(TextMark *mark)
return m_marks[FileName::fromString(mark->fileName())].remove(mark);
}
-void TextMarkRegistry::editorOpened(Core::IEditor *editor)
+void TextMarkRegistry::editorOpened(IEditor *editor)
{
auto document = qobject_cast<TextDocument *>(editor ? editor->document() : 0);
if (!document)
return;
- if (!m_marks.contains(FileName::fromString(document->filePath())))
+ if (!m_marks.contains(document->filePath()))
return;
- foreach (TextMark *mark, m_marks.value(FileName::fromString(document->filePath())))
+ foreach (TextMark *mark, m_marks.value(document->filePath()))
document->addMark(mark);
}
diff --git a/src/plugins/todo/cpptodoitemsscanner.cpp b/src/plugins/todo/cpptodoitemsscanner.cpp
index 70a8901f53f..4a1dd384d0c 100644
--- a/src/plugins/todo/cpptodoitemsscanner.cpp
+++ b/src/plugins/todo/cpptodoitemsscanner.cpp
@@ -44,8 +44,8 @@ CppTodoItemsScanner::CppTodoItemsScanner(const KeywordList &keywordList, QObject
{
CppTools::CppModelManager *modelManager = CppTools::CppModelManager::instance();
- connect(modelManager, SIGNAL(documentUpdated(CPlusPlus::Document::Ptr)), this,
- SLOT(documentUpdated(CPlusPlus::Document::Ptr)), Qt::DirectConnection);
+ connect(modelManager, &CppTools::CppModelManager::documentUpdated,
+ this, &CppTodoItemsScanner::documentUpdated, Qt::DirectConnection);
}
void CppTodoItemsScanner::keywordListChanged()
diff --git a/src/plugins/todo/qmljstodoitemsscanner.cpp b/src/plugins/todo/qmljstodoitemsscanner.cpp
index 54fc73cb27b..7c508cdd082 100644
--- a/src/plugins/todo/qmljstodoitemsscanner.cpp
+++ b/src/plugins/todo/qmljstodoitemsscanner.cpp
@@ -40,8 +40,8 @@ QmlJsTodoItemsScanner::QmlJsTodoItemsScanner(const KeywordList &keywordList, QOb
TodoItemsScanner(keywordList, parent)
{
QmlJS::ModelManagerInterface *model = QmlJS::ModelManagerInterface::instance();
- connect(model, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
- this, SLOT(documentUpdated(QmlJS::Document::Ptr)), Qt::DirectConnection);
+ connect(model, &QmlJS::ModelManagerInterface::documentUpdated,
+ this, &QmlJsTodoItemsScanner::documentUpdated, Qt::DirectConnection);
}
bool QmlJsTodoItemsScanner::shouldProcessFile(const QString &fileName)
diff --git a/src/plugins/todo/todoitemsprovider.cpp b/src/plugins/todo/todoitemsprovider.cpp
index 9538f898564..a4d531c1850 100644
--- a/src/plugins/todo/todoitemsprovider.cpp
+++ b/src/plugins/todo/todoitemsprovider.cpp
@@ -81,7 +81,7 @@ 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()->filePath());
+ m_itemsList = m_itemsHash.value(m_currentEditor->document()->filePath().toString());
// Show only items of the startup project if any
} else {
if (m_startupProject)
@@ -109,7 +109,7 @@ void TodoItemsProvider::createScanners()
void TodoItemsProvider::setItemsListWithinStartupProject()
{
QHashIterator<QString, QList<TodoItem> > it(m_itemsHash);
- QSet<QString> fileNames = QSet<QString>::fromList(m_startupProject->files(ProjectExplorer::Project::ExcludeGeneratedFiles));
+ QSet<QString> fileNames = QSet<QString>::fromList(m_startupProject->files(Project::ExcludeGeneratedFiles));
while (it.hasNext()) {
it.next();
if (fileNames.contains(it.key()))
@@ -125,7 +125,7 @@ void TodoItemsProvider::itemsFetched(const QString &fileName, const QList<TodoIt
m_shouldUpdateList = true;
}
-void TodoItemsProvider::startupProjectChanged(ProjectExplorer::Project *project)
+void TodoItemsProvider::startupProjectChanged(Project *project)
{
m_startupProject = project;
updateList();
@@ -170,7 +170,7 @@ void TodoItemsProvider::setupUpdateListTimer()
{
m_shouldUpdateList = false;
QTimer *timer = new QTimer(this);
- connect(timer, SIGNAL(timeout()), SLOT(updateListTimeoutElapsed()));
+ connect(timer, &QTimer::timeout, this, &TodoItemsProvider::updateListTimeoutElapsed);
timer->start(Constants::OUTPUT_PANE_UPDATE_INTERVAL);
}
diff --git a/src/plugins/todo/todooutputpane.cpp b/src/plugins/todo/todooutputpane.cpp
index b2330a5f456..7dbb3247f02 100755..100644
--- a/src/plugins/todo/todooutputpane.cpp
+++ b/src/plugins/todo/todooutputpane.cpp
@@ -49,8 +49,10 @@ TodoOutputPane::TodoOutputPane(TodoItemsModel *todoItemsModel, QObject *parent)
createTreeView();
createScopeButtons();
setScanningScope(ScanningScopeCurrentFile); // default
- connect(m_todoItemsModel, SIGNAL(layoutChanged()), SIGNAL(navigateStateUpdate()));
- connect(m_todoItemsModel, SIGNAL(layoutChanged()), SLOT(updateTodoCount()));
+ connect(m_todoItemsModel, &TodoItemsModel::layoutChanged,
+ this, &TodoOutputPane::navigateStateUpdate);
+ connect(m_todoItemsModel, &TodoItemsModel::layoutChanged,
+ this, &TodoOutputPane::updateTodoCount);
}
TodoOutputPane::~TodoOutputPane()
@@ -183,7 +185,7 @@ void TodoOutputPane::createTreeView()
m_todoTreeView = new TodoOutputTreeView();
m_todoTreeView->setModel(m_todoItemsModel);
- connect(m_todoTreeView, SIGNAL(activated(QModelIndex)), SLOT(todoTreeViewClicked(QModelIndex)));
+ connect(m_todoTreeView, &TodoOutputTreeView::activated, this, &TodoOutputPane::todoTreeViewClicked);
}
void TodoOutputPane::freeTreeView()
@@ -206,7 +208,8 @@ void TodoOutputPane::createScopeButtons()
m_scopeButtons = new QButtonGroup();
m_scopeButtons->addButton(m_wholeProjectButton);
m_scopeButtons->addButton(m_currentFileButton);
- connect(m_scopeButtons, SIGNAL(buttonClicked(QAbstractButton*)), SLOT(scopeButtonClicked(QAbstractButton*)));
+ connect(m_scopeButtons, static_cast<void (QButtonGroup::*)(QAbstractButton *)>(&QButtonGroup::buttonClicked),
+ this, &TodoOutputPane::scopeButtonClicked);
m_spacer = new QWidget;
m_spacer->setMinimumWidth(Constants::OUTPUT_TOOLBAR_SPACER_WIDTH);
diff --git a/src/plugins/todo/todooutputpane.h b/src/plugins/todo/todooutputpane.h
index ab5f55932d4..ab5f55932d4 100755..100644
--- a/src/plugins/todo/todooutputpane.h
+++ b/src/plugins/todo/todooutputpane.h
diff --git a/src/plugins/todo/todoplugin.cpp b/src/plugins/todo/todoplugin.cpp
index 46a1b4bdaa4..9d33ba4ae00 100755..100644
--- a/src/plugins/todo/todoplugin.cpp
+++ b/src/plugins/todo/todoplugin.cpp
@@ -114,15 +114,18 @@ void TodoPlugin::createTodoOutputPane()
m_todoOutputPane = new TodoOutputPane(m_todoItemsProvider->todoItemsModel());
addAutoReleasedObject(m_todoOutputPane);
m_todoOutputPane->setScanningScope(m_settings.scanningScope);
- connect(m_todoOutputPane, SIGNAL(scanningScopeChanged(ScanningScope)), SLOT(scanningScopeChanged(ScanningScope)));
- connect(m_todoOutputPane, SIGNAL(todoItemClicked(TodoItem)), SLOT(todoItemClicked(TodoItem)));
+ connect(m_todoOutputPane, &TodoOutputPane::scanningScopeChanged,
+ this, &TodoPlugin::scanningScopeChanged);
+ connect(m_todoOutputPane, &TodoOutputPane::todoItemClicked,
+ this, &TodoPlugin::todoItemClicked);
}
void TodoPlugin::createOptionsPage()
{
m_optionsPage = new OptionsPage(m_settings);
addAutoReleasedObject(m_optionsPage);
- connect(m_optionsPage, SIGNAL(settingsChanged(Settings)), SLOT(settingsChanged(Settings)));
+ connect(m_optionsPage, &OptionsPage::settingsChanged,
+ this, &TodoPlugin::settingsChanged);
}
} // namespace Internal
diff --git a/src/plugins/todo/todoplugin.h b/src/plugins/todo/todoplugin.h
index 83776d7ddd2..83776d7ddd2 100755..100644
--- a/src/plugins/todo/todoplugin.h
+++ b/src/plugins/todo/todoplugin.h
diff --git a/src/plugins/valgrind/callgrind/callgrindcontroller.cpp b/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
index e8fd4c9e793..f0e138378dc 100644
--- a/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
@@ -103,10 +103,10 @@ void CallgrindController::run(Option option)
connection ? connection->connectionParameters() : QSsh::SshConnectionParameters(),
connection, this);
- connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
- SLOT(processFinished(int,QProcess::ExitStatus)));
- connect(m_process, SIGNAL(error(QProcess::ProcessError)),
- SLOT(processError(QProcess::ProcessError)));
+ connect(m_process, &ValgrindProcess::finished,
+ this, &CallgrindController::processFinished);
+ connect(m_process, &ValgrindProcess::error,
+ this, &CallgrindController::processError);
// save back current running operation
m_lastOption = option;
@@ -200,7 +200,7 @@ void CallgrindController::getLocalDataFile()
arg(m_valgrindProc->pid());
const QString workingDir = m_valgrindProc->workingDirectory();
// first, set the to-be-parsed file to callgrind.out.PID
- QString fileName = workingDir.isEmpty() ? baseFileName : (workingDir + QDir::separator() + baseFileName);
+ QString fileName = workingDir.isEmpty() ? baseFileName : (workingDir + QLatin1Char('/') + baseFileName);
if (!m_valgrindProc->isLocal()) {
///TODO: error handling
@@ -209,15 +209,15 @@ void CallgrindController::getLocalDataFile()
// 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());
- connect(m_findRemoteFile.data(), SIGNAL(readyReadStandardOutput()), this,
- SLOT(foundRemoteFile()));
+ connect(m_findRemoteFile.data(), &QSsh::SshRemoteProcess::readyReadStandardOutput,
+ this, &CallgrindController::foundRemoteFile);
m_findRemoteFile->start();
} else {
QDir dir(workingDir, QString::fromLatin1("%1.*").arg(baseFileName), QDir::Time);
QStringList outputFiles = dir.entryList();
// if there are files like callgrind.out.PID.NUM, set it to the most recent one of those
if (!outputFiles.isEmpty())
- fileName = workingDir + QDir::separator() + dir.entryList().first();
+ fileName = workingDir + QLatin1Char('/') + dir.entryList().first();
emit localParseDataAvailable(fileName);
}
@@ -228,16 +228,17 @@ void CallgrindController::foundRemoteFile()
m_remoteFile = m_findRemoteFile->readAllStandardOutput().trimmed();
m_sftp = m_ssh->createSftpChannel();
- connect(m_sftp.data(), SIGNAL(finished(QSsh::SftpJobId,QString)),
- this, SLOT(sftpJobFinished(QSsh::SftpJobId,QString)));
- connect(m_sftp.data(), SIGNAL(initialized()), this, SLOT(sftpInitialized()));
+ connect(m_sftp.data(), &QSsh::SftpChannel::finished,
+ this, &CallgrindController::sftpJobFinished);
+ connect(m_sftp.data(), &QSsh::SftpChannel::initialized,
+ this, &CallgrindController::sftpInitialized);
m_sftp->initialize();
}
void CallgrindController::sftpInitialized()
{
cleanupTempFile();
- QTemporaryFile dataFile(QDir::tempPath() + QDir::separator() + QLatin1String("callgrind.out."));
+ QTemporaryFile dataFile(QDir::tempPath() + QLatin1Char('/') + QLatin1String("callgrind.out."));
QTC_ASSERT(dataFile.open(), return);
m_tempDataFile = dataFile.fileName();
dataFile.setAutoRemove(false);
diff --git a/src/plugins/valgrind/callgrind/callgrindrunner.cpp b/src/plugins/valgrind/callgrind/callgrindrunner.cpp
index e28d3d72b36..8abafb9659e 100644
--- a/src/plugins/valgrind/callgrind/callgrindrunner.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindrunner.cpp
@@ -44,13 +44,12 @@ CallgrindRunner::CallgrindRunner(QObject *parent)
, m_parser(new Parser(this))
, m_paused(false)
{
- connect(m_controller,
- SIGNAL(finished(Valgrind::Callgrind::CallgrindController::Option)),
- SLOT(controllerFinished(Valgrind::Callgrind::CallgrindController::Option)));
- connect(m_controller, SIGNAL(localParseDataAvailable(QString)),
- this, SLOT(localParseDataAvailable(QString)));
- connect(m_controller, SIGNAL(statusMessage(QString)),
- this, SIGNAL(statusMessage(QString)));
+ connect(m_controller, &CallgrindController::finished,
+ this, &CallgrindRunner::controllerFinished);
+ connect(m_controller, &CallgrindController::localParseDataAvailable,
+ this, &CallgrindRunner::localParseDataAvailable);
+ connect(m_controller, &CallgrindController::statusMessage,
+ this, &CallgrindRunner::statusMessage);
}
QString CallgrindRunner::tool() const
diff --git a/src/plugins/valgrind/callgrindengine.cpp b/src/plugins/valgrind/callgrindengine.cpp
index 9465e229ae2..42273f69a35 100644
--- a/src/plugins/valgrind/callgrindengine.cpp
+++ b/src/plugins/valgrind/callgrindengine.cpp
@@ -48,9 +48,12 @@ CallgrindRunControl::CallgrindRunControl(const AnalyzerStartParameters &sp,
: ValgrindRunControl(sp, runConfiguration)
, m_markAsPaused(false)
{
- connect(&m_runner, SIGNAL(finished()), this, SLOT(slotFinished()));
- connect(m_runner.parser(), SIGNAL(parserDataReady()), this, SLOT(slotFinished()));
- connect(&m_runner, SIGNAL(statusMessage(QString)), SLOT(showStatusMessage(QString)));
+ connect(&m_runner, &Callgrind::CallgrindRunner::finished,
+ this, &CallgrindRunControl::slotFinished);
+ connect(m_runner.parser(), &Callgrind::Parser::parserDataReady,
+ this, &CallgrindRunControl::slotFinished);
+ connect(&m_runner, &Callgrind::CallgrindRunner::statusMessage,
+ this, &CallgrindRunControl::showStatusMessage);
}
void CallgrindRunControl::showStatusMessage(const QString &msg)
@@ -91,7 +94,7 @@ QString CallgrindRunControl::progressTitle() const
return tr("Profiling");
}
-Valgrind::ValgrindRunner * CallgrindRunControl::runner()
+ValgrindRunner * CallgrindRunControl::runner()
{
return &m_runner;
}
@@ -104,7 +107,7 @@ bool CallgrindRunControl::startEngine()
void CallgrindRunControl::dump()
{
- m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::Dump);
+ m_runner.controller()->run(Callgrind::CallgrindController::Dump);
}
void CallgrindRunControl::setPaused(bool paused)
@@ -133,20 +136,20 @@ void CallgrindRunControl::setToggleCollectFunction(const QString &toggleCollectF
void CallgrindRunControl::reset()
{
- m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::ResetEventCounters);
+ m_runner.controller()->run(Callgrind::CallgrindController::ResetEventCounters);
}
void CallgrindRunControl::pause()
{
- m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::Pause);
+ m_runner.controller()->run(Callgrind::CallgrindController::Pause);
}
void CallgrindRunControl::unpause()
{
- m_runner.controller()->run(Valgrind::Callgrind::CallgrindController::UnPause);
+ m_runner.controller()->run(Callgrind::CallgrindController::UnPause);
}
-Valgrind::Callgrind::ParseData *CallgrindRunControl::takeParserData()
+Callgrind::ParseData *CallgrindRunControl::takeParserData()
{
return m_runner.parser()->takeData();
}
diff --git a/src/plugins/valgrind/callgrindtool.cpp b/src/plugins/valgrind/callgrindtool.cpp
index bf054a1b1a0..a4beb29e540 100644
--- a/src/plugins/valgrind/callgrindtool.cpp
+++ b/src/plugins/valgrind/callgrindtool.cpp
@@ -65,7 +65,7 @@
#include <utils/styledbar.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <QFile>
#include <QFileInfo>
@@ -118,7 +118,7 @@ public:
void updateEventCombo();
AnalyzerRunControl *createRunControl(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration = 0);
+ RunConfiguration *runConfiguration = 0);
signals:
void cycleDetectionEnabled(bool enabled);
@@ -131,8 +131,8 @@ public slots:
void slotRequestDump();
void loadExternalLogFile();
- void selectFunction(const Valgrind::Callgrind::Function *);
- void setCostFormat(Valgrind::Internal::CostDelegate::CostFormat format);
+ void selectFunction(const Function *);
+ void setCostFormat(CostDelegate::CostFormat format);
void enableCycleDetection(bool enabled);
void shortenTemplates(bool enabled);
void setCostEvent(int index);
@@ -160,15 +160,15 @@ public slots:
void dataFunctionSelected(const QModelIndex &index);
void calleeFunctionSelected(const QModelIndex &index);
void callerFunctionSelected(const QModelIndex &index);
- void visualisationFunctionSelected(const Valgrind::Callgrind::Function *function);
- void showParserResults(const Valgrind::Callgrind::ParseData *data);
+ void visualisationFunctionSelected(const Function *function);
+ void showParserResults(const ParseData *data);
- void takeParserData(CallgrindRunControl *rc);
+ void takeParserDataFromRunControl(CallgrindRunControl *rc);
void takeParserData(ParseData *data);
- void engineStarting(const Analyzer::AnalyzerRunControl *);
+ void engineStarting(const AnalyzerRunControl *);
void engineFinished();
- void editorOpened(Core::IEditor *);
+ void editorOpened(IEditor *);
void requestContextMenu(TextEditorWidget *widget, int line, QMenu *menu);
public:
@@ -247,8 +247,10 @@ CallgrindToolPrivate::CallgrindToolPrivate(CallgrindTool *parent)
m_proxyModel->setFilterKeyColumn(DataModel::NameColumn);
m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
- connect(m_stackBrowser, SIGNAL(currentChanged()), SLOT(stackBrowserChanged()));
- connect(m_updateTimer, SIGNAL(timeout()), SLOT(updateFilterString()));
+ connect(m_stackBrowser, &StackBrowser::currentChanged,
+ this, &CallgrindToolPrivate::stackBrowserChanged);
+ connect(m_updateTimer, &QTimer::timeout,
+ this, &CallgrindToolPrivate::updateFilterString);
}
CallgrindToolPrivate::~CallgrindToolPrivate()
@@ -399,7 +401,7 @@ void CallgrindToolPrivate::updateCostFormat()
void CallgrindToolPrivate::handleFilterProjectCosts()
{
- ProjectExplorer::Project *pro = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ Project *pro = ProjectTree::currentProject();
QTC_ASSERT(pro, return);
if (m_filterProjectCosts->isChecked()) {
@@ -503,8 +505,8 @@ CallgrindTool::CallgrindTool(QObject *parent)
setRunMode(CallgrindRunMode);
setToolMode(ReleaseMode);
- connect(EditorManager::instance(), SIGNAL(editorOpened(Core::IEditor*)),
- d, SLOT(editorOpened(Core::IEditor*)));
+ connect(EditorManager::instance(), &EditorManager::editorOpened,
+ d, &CallgrindToolPrivate::editorOpened);
}
CallgrindTool::~CallgrindTool()
@@ -523,16 +525,16 @@ AnalyzerRunControl *CallgrindToolPrivate::createRunControl(const AnalyzerStartPa
{
CallgrindRunControl *rc = new CallgrindRunControl(sp, runConfiguration);
- 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(rc, &CallgrindRunControl::parserDataReady,
+ this, &CallgrindToolPrivate::takeParserDataFromRunControl);
+ connect(rc, &AnalyzerRunControl::starting,
+ this, &CallgrindToolPrivate::engineStarting);
+ connect(rc, &RunControl::finished,
+ this, &CallgrindToolPrivate::engineFinished);
- connect(this, SIGNAL(dumpRequested()), rc, SLOT(dump()));
- connect(this, SIGNAL(resetRequested()), rc, SLOT(reset()));
- connect(this, SIGNAL(pauseToggled(bool)), rc, SLOT(setPaused(bool)));
+ connect(this, &CallgrindToolPrivate::dumpRequested, rc, &CallgrindRunControl::dump);
+ connect(this, &CallgrindToolPrivate::resetRequested, rc, &CallgrindRunControl::reset);
+ connect(this, &CallgrindToolPrivate::pauseToggled, rc, &CallgrindRunControl::setPaused);
// initialize run control
rc->setPaused(m_pauseAction->isChecked());
@@ -587,8 +589,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
m_visualisation->setObjectName(QLatin1String("Valgrind.CallgrindTool.Visualisation"));
m_visualisation->setWindowTitle(tr("Visualization"));
m_visualisation->setModel(m_dataModel);
- connect(m_visualisation, SIGNAL(functionActivated(const Valgrind::Callgrind::Function*)),
- this, SLOT(visualisationFunctionSelected(const Valgrind::Callgrind::Function*)));
+ connect(m_visualisation, &Visualisation::functionActivated,
+ this, &CallgrindToolPrivate::visualisationFunctionSelected);
m_callersView = new CostView(mw);
m_callersView->setObjectName(QLatin1String("Valgrind.CallgrindTool.CallersView"));
@@ -601,8 +603,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
callerProxy->setSourceModel(m_callersModel);
m_callersView->setModel(callerProxy);
m_callersView->hideColumn(CallModel::CalleeColumn);
- connect(m_callersView, SIGNAL(activated(QModelIndex)),
- this, SLOT(callerFunctionSelected(QModelIndex)));
+ connect(m_callersView, &QAbstractItemView::activated,
+ this, &CallgrindToolPrivate::callerFunctionSelected);
m_calleesView = new CostView(mw);
m_calleesView->setObjectName(QLatin1String("Valgrind.CallgrindTool.CalleesView"));
@@ -615,8 +617,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
calleeProxy->setSourceModel(m_calleesModel);
m_calleesView->setModel(calleeProxy);
m_calleesView->hideColumn(CallModel::CallerColumn);
- connect(m_calleesView, SIGNAL(activated(QModelIndex)),
- this, SLOT(calleeFunctionSelected(QModelIndex)));
+ connect(m_calleesView, &QAbstractItemView::activated,
+ this, &CallgrindToolPrivate::calleeFunctionSelected);
m_flatView = new CostView(mw);
m_flatView->setObjectName(QLatin1String("Valgrind.CallgrindTool.FlatView"));
@@ -626,8 +628,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
m_flatView->setFrameStyle(QFrame::NoFrame);
m_flatView->setAttribute(Qt::WA_MacShowFocusRect, false);
m_flatView->setModel(m_proxyModel);
- connect(m_flatView, SIGNAL(activated(QModelIndex)),
- this, SLOT(dataFunctionSelected(QModelIndex)));
+ connect(m_flatView, &QAbstractItemView::activated,
+ this, &CallgrindToolPrivate::dataFunctionSelected);
updateCostFormat();
@@ -661,7 +663,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action = new QAction(this);
action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_OPENFILE)));
action->setToolTip(tr("Load External Log File"));
- connect(action, SIGNAL(triggered(bool)), this, SLOT(loadExternalLogFile()));
+ connect(action, &QAction::triggered, this, &CallgrindToolPrivate::loadExternalLogFile);
layout->addWidget(createToolButton(action));
m_loadExternalLogFile = action;
@@ -671,7 +673,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_REDO)));
//action->setText(tr("Dump"));
action->setToolTip(tr("Request the dumping of profile information. This will update the Callgrind visualization."));
- connect(action, SIGNAL(triggered()), this, SLOT(slotRequestDump()));
+ connect(action, &QAction::triggered, this, &CallgrindToolPrivate::slotRequestDump);
layout->addWidget(createToolButton(action));
m_dumpAction = action;
@@ -681,7 +683,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_CLEAR)));
//action->setText(tr("Reset"));
action->setToolTip(tr("Reset all event counters."));
- connect(action, SIGNAL(triggered()), this, SIGNAL(resetRequested()));
+ connect(action, &QAction::triggered, this, &CallgrindToolPrivate::resetRequested);
layout->addWidget(createToolButton(action));
m_resetAction = action;
@@ -691,7 +693,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_PAUSE)));
//action->setText(tr("Ignore"));
action->setToolTip(tr("Pause event logging. No events are counted which will speed up program execution during profiling."));
- connect(action, SIGNAL(toggled(bool)), this, SIGNAL(pauseToggled(bool)));
+ connect(action, &QAction::toggled, this, &CallgrindToolPrivate::pauseToggled);
layout->addWidget(createToolButton(action));
m_pauseAction = action;
@@ -701,7 +703,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action->setDisabled(true);
action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_PREV)));
action->setToolTip(tr("Go back one step in history. This will select the previously selected item."));
- connect(action, SIGNAL(triggered(bool)), m_stackBrowser, SLOT(goBack()));
+ connect(action, &QAction::triggered, m_stackBrowser, &StackBrowser::goBack);
layout->addWidget(createToolButton(action));
m_goBack = action;
@@ -710,7 +712,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action->setDisabled(true);
action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_NEXT)));
action->setToolTip(tr("Go forward one step in history."));
- connect(action, SIGNAL(triggered(bool)), m_stackBrowser, SLOT(goNext()));
+ connect(action, &QAction::triggered, m_stackBrowser, &StackBrowser::goNext);
layout->addWidget(createToolButton(action));
m_goNext = action;
@@ -719,8 +721,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
// event selection
m_eventCombo = new QComboBox;
m_eventCombo->setToolTip(tr("Selects which events from the profiling data are shown and visualized."));
- connect(m_eventCombo, SIGNAL(currentIndexChanged(int)),
- this, SLOT(setCostEvent(int)));
+ connect(m_eventCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &CallgrindToolPrivate::setCostEvent);
updateEventCombo();
layout->addWidget(m_eventCombo);
@@ -734,7 +736,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
m_costAbsolute->setToolTip(tr("Show costs as absolute numbers."));
m_costAbsolute->setCheckable(true);
m_costAbsolute->setChecked(true);
- connect(m_costAbsolute, SIGNAL(toggled(bool)), SLOT(updateCostFormat()));
+ connect(m_costAbsolute, &QAction::toggled, this, &CallgrindToolPrivate::updateCostFormat);
group->addAction(m_costAbsolute);
menu->addAction(m_costAbsolute);
@@ -742,7 +744,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
m_costRelative = new QAction(tr("Relative Costs"), this);
m_costRelative->setToolTip(tr("Show costs relative to total inclusive cost."));
m_costRelative->setCheckable(true);
- connect(m_costRelative, SIGNAL(toggled(bool)), SLOT(updateCostFormat()));
+ connect(m_costRelative, &QAction::toggled, this, &CallgrindToolPrivate::updateCostFormat);
group->addAction(m_costRelative);
menu->addAction(m_costRelative);
@@ -750,7 +752,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
m_costRelativeToParent = new QAction(tr("Relative Costs to Parent"), this);
m_costRelativeToParent->setToolTip(tr("Show costs relative to parent functions inclusive cost."));
m_costRelativeToParent->setCheckable(true);
- connect(m_costRelativeToParent, SIGNAL(toggled(bool)), SLOT(updateCostFormat()));
+ connect(m_costRelativeToParent, &QAction::toggled, this, &CallgrindToolPrivate::updateCostFormat);
group->addAction(m_costRelativeToParent);
menu->addAction(m_costRelativeToParent);
@@ -770,8 +772,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
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)), settings, SLOT(setDetectCycles(bool)));
+ connect(action, &QAction::toggled, m_dataModel, &DataModel::enableCycleDetection);
+ connect(action, &QAction::toggled, settings, &ValgrindGlobalSettings::setDetectCycles);
layout->addWidget(createToolButton(action));
m_cycleDetection = action;
@@ -779,8 +781,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
action = new QAction(QLatin1String("<>"), this);
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)), settings, SLOT(setShortenTemplates(bool)));
+ connect(action, &QAction::toggled, m_dataModel, &DataModel::setShortenTemplates);
+ connect(action, &QAction::toggled, settings, &ValgrindGlobalSettings::setShortenTemplates);
layout->addWidget(createToolButton(action));
m_shortenTemplates = action;
@@ -789,7 +791,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
action->setToolTip(tr("Show only profiling info that originated from this project source."));
action->setCheckable(true);
- connect(action, SIGNAL(toggled(bool)), this, SLOT(handleFilterProjectCosts()));
+ connect(action, &QAction::toggled, this, &CallgrindToolPrivate::handleFilterProjectCosts);
layout->addWidget(createToolButton(action));
m_filterProjectCosts = action;
@@ -797,7 +799,8 @@ QWidget *CallgrindToolPrivate::createWidgets()
///FIXME: find workaround for https://bugreports.qt.io/browse/QTCREATORBUG-3247
QLineEdit *filter = new QLineEdit;
filter->setPlaceholderText(tr("Filter..."));
- connect(filter, SIGNAL(textChanged(QString)), m_updateTimer, SLOT(start()));
+ connect(filter, &QLineEdit::textChanged,
+ m_updateTimer, static_cast<void(QTimer::*)()>(&QTimer::start));
layout->addWidget(filter);
m_searchFilter = filter;
@@ -816,7 +819,7 @@ void CallgrindToolPrivate::clearTextMarks()
m_textMarks.clear();
}
-void CallgrindToolPrivate::engineStarting(const Analyzer::AnalyzerRunControl *)
+void CallgrindToolPrivate::engineStarting(const AnalyzerRunControl *)
{
// enable/disable actions
m_resetAction->setEnabled(true);
@@ -872,7 +875,7 @@ void CallgrindToolPrivate::requestContextMenu(TextEditorWidget *widget, int line
// 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() == widget->textDocument()->filePath() && textMark->lineNumber() == line) {
+ if (textMark->fileName() == widget->textDocument()->filePath().toString() && textMark->lineNumber() == line) {
func = textMark->function();
break;
}
@@ -882,7 +885,7 @@ void CallgrindToolPrivate::requestContextMenu(TextEditorWidget *widget, int line
// add our action to the context menu
QAction *action = new QAction(tr("Select this Function in the Analyzer Output"), menu);
- connect(action, SIGNAL(triggered()), SLOT(handleShowCostsAction()));
+ connect(action, &QAction::triggered, this, &CallgrindToolPrivate::handleShowCostsAction);
action->setData(QVariant::fromValue<const Function *>(func));
menu->addAction(action);
}
@@ -926,7 +929,7 @@ void CallgrindToolPrivate::slotRequestDump()
void CallgrindToolPrivate::loadExternalLogFile()
{
const QString filePath = QFileDialog::getOpenFileName(
- Core::ICore::mainWindow(),
+ ICore::mainWindow(),
tr("Open Callgrind Log File"),
QString(),
tr("Callgrind Output (callgrind.out*);;All Files (*)"));
@@ -948,7 +951,7 @@ void CallgrindToolPrivate::loadExternalLogFile()
takeParserData(parser.takeData());
}
-void CallgrindToolPrivate::takeParserData(CallgrindRunControl *rc)
+void CallgrindToolPrivate::takeParserDataFromRunControl(CallgrindRunControl *rc)
{
takeParserData(rc->takeParserData());
}
diff --git a/src/plugins/valgrind/callgrindvisualisation.cpp b/src/plugins/valgrind/callgrindvisualisation.cpp
index d4168ab443c..4dcc35ca52d 100644
--- a/src/plugins/valgrind/callgrindvisualisation.cpp
+++ b/src/plugins/valgrind/callgrindvisualisation.cpp
@@ -234,9 +234,8 @@ Visualisation::Private::Private(Visualisation *qq)
// setup model
m_model->setMinimumInclusiveCostRatio(0.1);
- connect(m_model,
- SIGNAL(filterFunctionChanged(const Function*,const Function*)),
- qq, SLOT(populateScene()));
+ connect(m_model, &DataProxyModel::filterFunctionChanged,
+ qq, &Visualisation::populateScene);
}
void Visualisation::Private::handleMousePressEvent(QMouseEvent *event,
@@ -326,32 +325,24 @@ void Visualisation::setModel(QAbstractItemModel *model)
QTC_ASSERT(!d->m_model->sourceModel() && model, return); // only set once!
d->m_model->setSourceModel(model);
- connect(model,
- SIGNAL(columnsInserted(QModelIndex,int,int)),
- SLOT(populateScene()));
- connect(model,
- SIGNAL(columnsMoved(QModelIndex,int,int,QModelIndex,int)),
- SLOT(populateScene()));
- connect(model,
- SIGNAL(columnsRemoved(QModelIndex,int,int)),
- SLOT(populateScene()));
- connect(model,
- SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- SLOT(populateScene()));
- connect(model,
- SIGNAL(headerDataChanged(Qt::Orientation,int,int)),
- SLOT(populateScene()));
- connect(model, SIGNAL(layoutChanged()), SLOT(populateScene()));
- connect(model, SIGNAL(modelReset()), SLOT(populateScene()));
- connect(model,
- SIGNAL(rowsInserted(QModelIndex,int,int)),
- SLOT(populateScene()));
- connect(model,
- SIGNAL(rowsMoved(QModelIndex,int,int,QModelIndex,int)),
- SLOT(populateScene()));
- connect(model,
- SIGNAL(rowsRemoved(QModelIndex,int,int)),
- SLOT(populateScene()));
+ connect(model, &QAbstractItemModel::columnsInserted,
+ this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::columnsMoved,
+ this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::columnsRemoved,
+ this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::dataChanged,
+ this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::headerDataChanged,
+ this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::layoutChanged, this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::modelReset, this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::rowsInserted,
+ this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::rowsMoved,
+ this, &Visualisation::populateScene);
+ connect(model, &QAbstractItemModel::rowsRemoved,
+ this, &Visualisation::populateScene);
populateScene();
}
diff --git a/src/plugins/valgrind/memcheck/memcheckrunner.cpp b/src/plugins/valgrind/memcheck/memcheckrunner.cpp
index 4bd608b50ea..89820225095 100644
--- a/src/plugins/valgrind/memcheck/memcheckrunner.cpp
+++ b/src/plugins/valgrind/memcheck/memcheckrunner.cpp
@@ -57,7 +57,8 @@ class MemcheckRunner::Private
public:
explicit Private()
: parser(0),
- logSocket(0)
+ logSocket(0),
+ disableXml(false)
{
}
@@ -65,6 +66,7 @@ public:
XmlProtocol::ThreadedParser *parser;
QTcpServer logServer;
QTcpSocket *logSocket;
+ bool disableXml;
};
MemcheckRunner::MemcheckRunner(QObject *parent)
@@ -106,6 +108,13 @@ bool MemcheckRunner::start()
return ValgrindRunner::start();
}
+// Workaround for valgrind bug when running vgdb with xml output
+// https://bugs.kde.org/show_bug.cgi?id=343902
+void MemcheckRunner::disableXml()
+{
+ d->disableXml = true;
+}
+
void MemcheckRunner::xmlSocketConnected()
{
QTcpSocket *socket = d->xmlServer.nextPendingConnection();
@@ -118,8 +127,8 @@ void MemcheckRunner::logSocketConnected()
{
d->logSocket = d->logServer.nextPendingConnection();
QTC_ASSERT(d->logSocket, return);
- connect(d->logSocket, SIGNAL(readyRead()),
- this, SLOT(readLogSocket()));
+ connect(d->logSocket, &QIODevice::readyRead,
+ this, &MemcheckRunner::readLogSocket);
d->logServer.close();
}
@@ -141,7 +150,8 @@ bool MemcheckRunner::startServers(const QHostAddress &localHostAddress)
return false;
}
d->xmlServer.setMaxPendingConnections(1);
- connect(&d->xmlServer, SIGNAL(newConnection()), SLOT(xmlSocketConnected()));
+ connect(&d->xmlServer, &QTcpServer::newConnection,
+ this, &MemcheckRunner::xmlSocketConnected);
check = d->logServer.listen(localHostAddress);
if (!check) {
emit processErrorReceived( tr("LogServer on %1:").arg(ip) + QLatin1Char(' ')
@@ -149,19 +159,22 @@ bool MemcheckRunner::startServers(const QHostAddress &localHostAddress)
return false;
}
d->logServer.setMaxPendingConnections(1);
- connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected()));
+ connect(&d->logServer, &QTcpServer::newConnection,
+ this, &MemcheckRunner::logSocketConnected);
return true;
}
QStringList MemcheckRunner::memcheckLogArguments() const
{
- return QStringList()
- << QLatin1String("--xml=yes")
- << QString::fromLatin1("--xml-socket=%1:%2")
- .arg(d->xmlServer.serverAddress().toString()).arg(d->xmlServer.serverPort())
- << QLatin1String("--child-silent-after-fork=yes")
- << QString::fromLatin1("--log-socket=%1:%2")
- .arg(d->logServer.serverAddress().toString()).arg(d->logServer.serverPort());
+ QStringList arguments;
+ if (!d->disableXml)
+ arguments << QLatin1String("--xml=yes");
+ arguments << QString::fromLatin1("--xml-socket=%1:%2")
+ .arg(d->xmlServer.serverAddress().toString()).arg(d->xmlServer.serverPort())
+ << QLatin1String("--child-silent-after-fork=yes")
+ << QString::fromLatin1("--log-socket=%1:%2")
+ .arg(d->logServer.serverAddress().toString()).arg(d->logServer.serverPort());
+ return arguments;
}
void MemcheckRunner::localHostAddressRetrieved(const QHostAddress &localHostAddress)
diff --git a/src/plugins/valgrind/memcheck/memcheckrunner.h b/src/plugins/valgrind/memcheck/memcheckrunner.h
index 20f391db298..c9ed30b36bb 100644
--- a/src/plugins/valgrind/memcheck/memcheckrunner.h
+++ b/src/plugins/valgrind/memcheck/memcheckrunner.h
@@ -52,6 +52,7 @@ public:
void setParser(XmlProtocol::ThreadedParser *parser);
bool start();
+ void disableXml();
signals:
void logMessageReceived(const QByteArray &);
diff --git a/src/plugins/valgrind/memcheckengine.cpp b/src/plugins/valgrind/memcheckengine.cpp
index b7fdb3cb46d..f2925e0d8d9 100644
--- a/src/plugins/valgrind/memcheckengine.cpp
+++ b/src/plugins/valgrind/memcheckengine.cpp
@@ -30,14 +30,22 @@
****************************************************************************/
#include "memcheckengine.h"
-
+#include "valgrindprocess.h"
#include "valgrindsettings.h"
+#include "xmlprotocol/error.h"
+#include "xmlprotocol/status.h"
+
+#include <debugger/debuggerkitinformation.h>
+#include <debugger/debuggerstartparameters.h>
+#include <debugger/debuggerruncontrol.h>
+#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/target.h>
#include <projectexplorer/taskhub.h>
-
-#include <valgrind/xmlprotocol/error.h>
-#include <valgrind/xmlprotocol/status.h>
+#include <projectexplorer/toolchain.h>
#include <utils/qtcassert.h>
@@ -49,15 +57,15 @@ namespace Valgrind {
namespace Internal {
MemcheckRunControl::MemcheckRunControl(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
+ RunConfiguration *runConfiguration)
: ValgrindRunControl(sp, runConfiguration)
{
- connect(&m_parser, SIGNAL(error(Valgrind::XmlProtocol::Error)),
- SIGNAL(parserError(Valgrind::XmlProtocol::Error)));
- connect(&m_parser, SIGNAL(suppressionCount(QString,qint64)),
- SIGNAL(suppressionCount(QString,qint64)));
- connect(&m_parser, SIGNAL(internalError(QString)),
- SIGNAL(internalParserError(QString)));
+ connect(&m_parser, &XmlProtocol::ThreadedParser::error,
+ this, &MemcheckRunControl::parserError);
+ connect(&m_parser, &XmlProtocol::ThreadedParser::suppressionCount,
+ this, &MemcheckRunControl::suppressionCount);
+ connect(&m_parser, &XmlProtocol::ThreadedParser::internalError,
+ this, &MemcheckRunControl::internalParserError);
}
QString MemcheckRunControl::progressTitle() const
@@ -65,7 +73,7 @@ QString MemcheckRunControl::progressTitle() const
return tr("Analyzing Memory");
}
-Valgrind::ValgrindRunner *MemcheckRunControl::runner()
+ValgrindRunner *MemcheckRunControl::runner()
{
return &m_runner;
}
@@ -84,8 +92,8 @@ bool MemcheckRunControl::startEngine()
void MemcheckRunControl::stopEngine()
{
- disconnect(&m_parser, SIGNAL(internalError(QString)),
- this, SIGNAL(internalParserError(QString)));
+ disconnect(&m_parser, &ThreadedParser::internalError,
+ this, &MemcheckRunControl::internalParserError);
ValgrindRunControl::stopEngine();
}
@@ -129,5 +137,72 @@ QStringList MemcheckRunControl::suppressionFiles() const
return m_settings->suppressionFiles();
}
+MemcheckWithGdbRunControl::MemcheckWithGdbRunControl(const AnalyzerStartParameters &sp,
+ RunConfiguration *runConfiguration)
+ : MemcheckRunControl(sp, runConfiguration)
+{
+ connect(&m_runner, &Memcheck::MemcheckRunner::started,
+ this, &MemcheckWithGdbRunControl::startDebugger);
+ connect(&m_runner, &Memcheck::MemcheckRunner::logMessageReceived,
+ this, &MemcheckWithGdbRunControl::appendLog);
+ disconnect(&m_parser, &ThreadedParser::internalError,
+ this, &MemcheckRunControl::internalParserError);
+ m_runner.disableXml();
+}
+
+QStringList MemcheckWithGdbRunControl::toolArguments() const
+{
+ return MemcheckRunControl::toolArguments()
+ << QLatin1String("--vgdb=yes") << QLatin1String("--vgdb-error=0");
+}
+
+void MemcheckWithGdbRunControl::startDebugger()
+{
+ const qint64 valgrindPid = runner()->valgrindProcess()->pid();
+ const AnalyzerStartParameters &mySp = startParameters();
+ Debugger::DebuggerStartParameters sp;
+
+ RunConfiguration *rc = runConfiguration();
+ const Target *target = rc->target();
+ QTC_ASSERT(target, return);
+
+ const Kit *kit = target->kit();
+ QTC_ASSERT(kit, return);
+
+ if (const ToolChain *tc = ToolChainKitInformation::toolChain(kit))
+ sp.toolChainAbi = tc->targetAbi();
+
+ if (const Project *project = target->project()) {
+ sp.projectSourceDirectory = project->projectDirectory().toString();
+ sp.projectSourceFiles = project->files(Project::ExcludeGeneratedFiles);
+
+ if (const BuildConfiguration *bc = target->activeBuildConfiguration())
+ sp.projectBuildDirectory = bc->buildDirectory().toString();
+ }
+
+ sp.executable = mySp.debuggee;
+ sp.sysRoot = SysRootKitInformation::sysRoot(kit).toString();
+ sp.debuggerCommand = Debugger::DebuggerKitInformation::debuggerCommand(kit).toString();
+ sp.languages |= Debugger::CppLanguage;
+ sp.startMode = Debugger::AttachToRemoteServer;
+ sp.displayName = QString::fromLatin1("VGdb %1").arg(valgrindPid);
+ sp.remoteChannel = QString::fromLatin1("| vgdb --pid=%1").arg(valgrindPid);
+ sp.useContinueInsteadOfRun = true;
+ sp.expectedSignals << "SIGTRAP";
+ sp.runConfiguration = rc;
+
+ QString errorMessage;
+ RunControl *gdbRunControl = Debugger::DebuggerRunControlFactory::doCreate(sp, &errorMessage);
+ QTC_ASSERT(gdbRunControl, return);
+ connect(gdbRunControl, &RunControl::finished,
+ gdbRunControl, &RunControl::deleteLater);
+ gdbRunControl->start();
+}
+
+void MemcheckWithGdbRunControl::appendLog(const QByteArray &data)
+{
+ appendMessage(QString::fromUtf8(data), Utils::StdOutFormat);
+}
+
} // namespace Internal
} // namespace Valgrind
diff --git a/src/plugins/valgrind/memcheckengine.h b/src/plugins/valgrind/memcheckengine.h
index a11f8a13380..cd89f87d88b 100644
--- a/src/plugins/valgrind/memcheckengine.h
+++ b/src/plugins/valgrind/memcheckengine.h
@@ -59,15 +59,29 @@ signals:
void suppressionCount(const QString &name, qint64 count);
protected:
- virtual QString progressTitle() const;
- virtual QStringList toolArguments() const;
- virtual ValgrindRunner *runner();
+ QString progressTitle() const Q_DECL_OVERRIDE;
+ QStringList toolArguments() const Q_DECL_OVERRIDE;
+ ValgrindRunner *runner() Q_DECL_OVERRIDE;
-private:
+protected:
XmlProtocol::ThreadedParser m_parser;
Memcheck::MemcheckRunner m_runner;
};
+class MemcheckWithGdbRunControl : public MemcheckRunControl
+{
+ Q_OBJECT
+
+public:
+ MemcheckWithGdbRunControl(const Analyzer::AnalyzerStartParameters &sp,
+ ProjectExplorer::RunConfiguration *runConfiguration);
+
+protected:
+ QStringList toolArguments() const Q_DECL_OVERRIDE;
+ void startDebugger();
+ void appendLog(const QByteArray &data);
+};
+
} // namespace Internal
} // namespace Valgrind
diff --git a/src/plugins/valgrind/memcheckerrorview.cpp b/src/plugins/valgrind/memcheckerrorview.cpp
index 40efefd123b..52945537078 100644
--- a/src/plugins/valgrind/memcheckerrorview.cpp
+++ b/src/plugins/valgrind/memcheckerrorview.cpp
@@ -41,7 +41,6 @@
#include "xmlprotocol/modelhelpers.h"
#include "xmlprotocol/suppression.h"
-#include <coreplugin/coreconstants.h>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
@@ -52,12 +51,7 @@
#include <QDebug>
#include <QAction>
-#include <QApplication>
-#include <QClipboard>
-#include <QContextMenuEvent>
#include <QLabel>
-#include <QListView>
-#include <QMenu>
#include <QPainter>
#include <QScrollBar>
#include <QSortFilterProxyModel>
@@ -77,13 +71,12 @@ class MemcheckErrorDelegate : public Analyzer::DetailedErrorDelegate
public:
explicit MemcheckErrorDelegate(QListView *parent);
- void copy();
-
SummaryLineInfo summaryInfo(const QModelIndex &index) const;
private:
QWidget *createDetailsWidget(const QFont &font, const QModelIndex &errorIndex,
QWidget *parent) const;
+ QString textualRepresentation() const Q_DECL_OVERRIDE;
};
static QString makeFrameName(const Frame &frame, const QString &relativeTo,
@@ -92,7 +85,7 @@ static QString makeFrameName(const Frame &frame, const QString &relativeTo,
const QString d = frame.directory();
const QString f = frame.file();
const QString fn = frame.functionName();
- const QString fullPath = d + QDir::separator() + f;
+ const QString fullPath = d + QLatin1Char('/') + f;
QString path;
if (!d.isEmpty() && !f.isEmpty())
@@ -109,12 +102,14 @@ static QString makeFrameName(const Frame &frame, const QString &relativeTo,
if (frame.line() != -1)
path += QLatin1Char(':') + QString::number(frame.line());
+ // Since valgrind only runs on POSIX systems, converting path separators
+ // will ruin the paths on Windows. Leave it untouched.
path = path.toHtmlEscaped();
if (link && !f.isEmpty() && QFile::exists(fullPath)) {
// make a hyperlink label
path = QString::fromLatin1("<a href=\"file://%1:%2\" %4>%3</a>")
- .arg(fullPath, QString::number(frame.line()), path, linkAttr);
+ .arg(fullPath).arg(frame.line()).arg(path).arg(linkAttr);
}
if (!fn.isEmpty())
@@ -130,8 +125,9 @@ static QString relativeToPath()
const ProjectExplorer::Project *project = ProjectExplorer::SessionManager::startupProject();
QString relativeTo(project ? project->projectDirectory().toString() : QDir::homePath());
- if (!relativeTo.endsWith(QDir::separator()))
- relativeTo.append(QDir::separator());
+ const QChar slash = QLatin1Char('/');
+ if (!relativeTo.endsWith(slash))
+ relativeTo.append(slash);
return relativeTo;
}
@@ -187,8 +183,7 @@ QWidget *MemcheckErrorDelegate::createDetailsWidget(const QFont & font,
errorLocation(errorIndex, error, /*link=*/ true,
/*absolutePath=*/ false, linkStyle),
linkStyle));
- connect(errorLabel, &QLabel::linkActivated,
- this, &MemcheckErrorDelegate::openLinkInEditor);
+ connect(errorLabel, &QLabel::linkActivated, this, &MemcheckErrorDelegate::openLinkInEditor);
layout->addWidget(errorLabel);
const QVector<Stack> stacks = error.stacks();
@@ -223,8 +218,7 @@ QWidget *MemcheckErrorDelegate::createDetailsWidget(const QFont & font,
QFont fixedPitchFont = font;
fixedPitchFont.setFixedPitch(true);
frameLabel->setFont(fixedPitchFont);
- connect(frameLabel, &QLabel::linkActivated,
- this, &MemcheckErrorDelegate::openLinkInEditor);
+ connect(frameLabel, &QLabel::linkActivated, this, &MemcheckErrorDelegate::openLinkInEditor);
// pad frameNr to 2 chars since only 50 frames max are supported by valgrind
const QString displayText = displayTextTemplate
.arg(frameNr++, 2).arg(frameName);
@@ -260,9 +254,9 @@ Analyzer::DetailedErrorDelegate::SummaryLineInfo MemcheckErrorDelegate::summaryI
return info;
}
-void MemcheckErrorDelegate::copy()
+QString MemcheckErrorDelegate::textualRepresentation() const
{
- QTC_ASSERT(m_detailsIndex.isValid(), return);
+ QTC_ASSERT(m_detailsIndex.isValid(), return QString());
QString content;
QTextStream stream(&content);
@@ -282,7 +276,7 @@ void MemcheckErrorDelegate::copy()
}
stream.flush();
- QApplication::clipboard()->setText(content);
+ return content;
}
MemcheckErrorView::MemcheckErrorView(QWidget *parent)
@@ -292,14 +286,6 @@ MemcheckErrorView::MemcheckErrorView(QWidget *parent)
MemcheckErrorDelegate *delegate = new MemcheckErrorDelegate(this);
setItemDelegate(delegate);
- m_copyAction = new QAction(this);
- m_copyAction->setText(tr("Copy Selection"));
- m_copyAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
- m_copyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C));
- m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
- connect(m_copyAction, &QAction::triggered, delegate, &MemcheckErrorDelegate::copy);
- addAction(m_copyAction);
-
m_suppressAction = new QAction(this);
m_suppressAction->setText(tr("Suppress Error"));
m_suppressAction->setIcon(QIcon(QLatin1String(":/qmldesigner/images/eye_crossed.png")));
@@ -331,30 +317,28 @@ void MemcheckErrorView::settingsChanged(ValgrindBaseSettings *settings)
m_settings = settings;
}
-void MemcheckErrorView::contextMenuEvent(QContextMenuEvent *e)
+void MemcheckErrorView::suppressError()
+{
+ SuppressionDialog::maybeShow(this);
+}
+
+QList<QAction *> MemcheckErrorView::customActions() const
{
+ QList<QAction *> actions;
const QModelIndexList indizes = selectionModel()->selectedRows();
- if (indizes.isEmpty())
- return;
+ QTC_ASSERT(!indizes.isEmpty(), return actions);
- QList<Error> errors;
+ bool hasErrors = false;
foreach (const QModelIndex &index, indizes) {
Error error = model()->data(index, ErrorListModel::ErrorRole).value<Error>();
- if (!error.suppression().isNull())
- errors << error;
+ if (!error.suppression().isNull()) {
+ hasErrors = true;
+ break;
+ }
}
-
- QMenu menu;
- menu.addAction(m_copyAction);
- menu.addSeparator();
- menu.addAction(m_suppressAction);
- m_suppressAction->setEnabled(!errors.isEmpty());
- menu.exec(e->globalPos());
-}
-
-void MemcheckErrorView::suppressError()
-{
- SuppressionDialog::maybeShow(this);
+ m_suppressAction->setEnabled(hasErrors);
+ actions << m_suppressAction;
+ return actions;
}
} // namespace Internal
diff --git a/src/plugins/valgrind/memcheckerrorview.h b/src/plugins/valgrind/memcheckerrorview.h
index 9173325001f..468e2478f94 100644
--- a/src/plugins/valgrind/memcheckerrorview.h
+++ b/src/plugins/valgrind/memcheckerrorview.h
@@ -57,11 +57,11 @@ public slots:
void settingsChanged(ValgrindBaseSettings *settings);
private slots:
- void contextMenuEvent(QContextMenuEvent *e);
void suppressError();
private:
- QAction *m_copyAction;
+ QList<QAction *> customActions() const Q_DECL_OVERRIDE;
+
QAction *m_suppressAction;
QString m_defaultSuppFile;
ValgrindBaseSettings *m_settings;
diff --git a/src/plugins/valgrind/memchecktool.cpp b/src/plugins/valgrind/memchecktool.cpp
index 7f307b14ae9..026fb684f52 100644
--- a/src/plugins/valgrind/memchecktool.cpp
+++ b/src/plugins/valgrind/memchecktool.cpp
@@ -146,7 +146,7 @@ bool MemcheckErrorFilterProxyModel::filterAcceptsRow(int sourceRow, const QModel
foreach (Project *project, SessionManager::projects()) {
validFolders << project->projectDirectory().toString();
foreach (Target *target, project->targets()) {
- foreach (const ProjectExplorer::DeployableFile &file,
+ foreach (const DeployableFile &file,
target->deploymentData().allFiles()) {
if (file.isExecutable())
validFolders << file.remoteDirectory();
@@ -250,12 +250,12 @@ void MemcheckTool::updateFromSettings()
m_filterProjectAction->setChecked(!m_settings->filterExternalIssues());
m_errorView->settingsChanged(m_settings);
- connect(m_settings, SIGNAL(visibleErrorKindsChanged(QList<int>)),
- m_errorProxyModel, SLOT(setAcceptedKinds(QList<int>)));
+ connect(m_settings, &ValgrindBaseSettings::visibleErrorKindsChanged,
+ m_errorProxyModel, &MemcheckErrorFilterProxyModel::setAcceptedKinds);
m_errorProxyModel->setAcceptedKinds(m_settings->visibleErrorKinds());
- connect(m_settings, SIGNAL(filterExternalIssuesChanged(bool)),
- m_errorProxyModel, SLOT(setFilterExternalIssues(bool)));
+ connect(m_settings, &ValgrindBaseSettings::filterExternalIssuesChanged,
+ m_errorProxyModel, &MemcheckErrorFilterProxyModel::setFilterExternalIssues);
m_errorProxyModel->setFilterExternalIssues(m_settings->filterExternalIssues());
}
@@ -283,7 +283,7 @@ void MemcheckTool::maybeActiveRunConfigurationChanged()
// 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*)));
+ connect(m_settings, &ValgrindBaseSettings::destroyed, this, &MemcheckTool::settingsDestroyed);
updateFromSettings();
}
@@ -364,8 +364,8 @@ QWidget *MemcheckTool::createWidgets()
errorDock->show();
mw->splitDockWidget(mw->toolBarDockWidget(), errorDock, Qt::Vertical);
- connect(ProjectExplorerPlugin::instance(),
- SIGNAL(updateRunActions()), SLOT(maybeActiveRunConfigurationChanged()));
+ connect(ProjectExplorerPlugin::instance(), &ProjectExplorerPlugin::updateRunActions,
+ this, &MemcheckTool::maybeActiveRunConfigurationChanged);
//
// The Control Widget.
@@ -381,7 +381,7 @@ QWidget *MemcheckTool::createWidgets()
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()));
+ connect(action, &QAction::triggered, this, &MemcheckTool::loadExternalXmlLogFile);
button = new QToolButton;
button->setDefaultAction(action);
layout->addWidget(button);
@@ -421,7 +421,7 @@ QWidget *MemcheckTool::createWidgets()
m_filterMenu->addSeparator();
m_filterMenu->addAction(m_filterProjectAction);
m_filterMenu->addAction(m_suppressionSeparator);
- connect(m_filterMenu, SIGNAL(triggered(QAction*)), SLOT(updateErrorFilter()));
+ connect(m_filterMenu, &QMenu::triggered, this, &MemcheckTool::updateErrorFilter);
filterButton->setMenu(m_filterMenu);
layout->addWidget(filterButton);
@@ -438,15 +438,12 @@ AnalyzerRunControl *MemcheckTool::createRunControl(const AnalyzerStartParameters
m_frameFinder->setFiles(runConfiguration ? runConfiguration->target()
->project()->files(Project::AllFiles) : QStringList());
- MemcheckRunControl *engine = new MemcheckRunControl(sp, runConfiguration);
+ MemcheckRunControl *engine = createMemcheckRunControl(sp, runConfiguration);
- 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(engineFinished()));
+ connect(engine, &MemcheckRunControl::starting, this, &MemcheckTool::engineStarting);
+ connect(engine, &MemcheckRunControl::parserError, this, &MemcheckTool::parserError);
+ connect(engine, &MemcheckRunControl::internalParserError, this, &MemcheckTool::internalParserError);
+ connect(engine, &MemcheckRunControl::finished, this, &MemcheckTool::engineFinished);
return engine;
}
@@ -458,20 +455,19 @@ void MemcheckTool::engineStarting(const AnalyzerRunControl *engine)
QString dir;
if (RunConfiguration *rc = engine->runConfiguration())
- dir = rc->target()->project()->projectDirectory().toString() + QDir::separator();
+ dir = rc->target()->project()->projectDirectory().toString() + QLatin1Char('/');
const MemcheckRunControl *mEngine = dynamic_cast<const MemcheckRunControl *>(engine);
QTC_ASSERT(mEngine, return);
- const QString name = QFileInfo(mEngine->executable()).fileName();
+ const QString name = Utils::FileName::fromString(mEngine->executable()).fileName();
m_errorView->setDefaultSuppressionFile(dir + name + QLatin1String(".supp"));
foreach (const QString &file, mEngine->suppressionFiles()) {
- QAction *action = m_filterMenu->addAction(QFileInfo(file).fileName());
+ QAction *action = m_filterMenu->addAction(Utils::FileName::fromString(file).fileName());
action->setToolTip(file);
action->setData(file);
- connect(action, SIGNAL(triggered(bool)),
- this, SLOT(suppressionActionTriggered()));
+ connect(action, &QAction::triggered, this, &MemcheckTool::suppressionActionTriggered);
m_suppressionActions.append(action);
}
}
@@ -515,17 +511,15 @@ void MemcheckTool::loadExternalXmlLogFile()
}
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()));
+ connect(parser, &ThreadedParser::error, this, &MemcheckTool::parserError);
+ connect(parser, &ThreadedParser::internalError, this, &MemcheckTool::internalParserError);
+ connect(parser, &ThreadedParser::finished, this, &MemcheckTool::loadingExternalXmlLogFileFinished);
+ connect(parser, &ThreadedParser::finished, parser, &ThreadedParser::deleteLater);
parser->parse(logFile); // ThreadedParser owns the file
}
-void MemcheckTool::parserError(const Valgrind::XmlProtocol::Error &error)
+void MemcheckTool::parserError(const Error &error)
{
m_errorModel->addError(error);
}
@@ -577,6 +571,12 @@ int MemcheckTool::updateUiAfterFinishedHelper()
return issuesFound;
}
+MemcheckRunControl *MemcheckTool::createMemcheckRunControl(const AnalyzerStartParameters &sp,
+ RunConfiguration *runConfiguration)
+{
+ return new MemcheckRunControl(sp, runConfiguration);
+}
+
void MemcheckTool::engineFinished()
{
const int issuesFound = updateUiAfterFinishedHelper();
@@ -599,5 +599,18 @@ void MemcheckTool::setBusyCursor(bool busy)
m_errorView->setCursor(cursor);
}
+MemcheckWithGdbTool::MemcheckWithGdbTool(QObject *parent) :
+ MemcheckTool(parent)
+{
+ setRunMode(MemcheckWithGdbRunMode);
+ setObjectName(QLatin1String("MemcheckWithGdbTool"));
+}
+
+MemcheckRunControl *MemcheckWithGdbTool::createMemcheckRunControl(const AnalyzerStartParameters &sp,
+ RunConfiguration *runConfiguration)
+{
+ return new MemcheckWithGdbRunControl(sp, runConfiguration);
+}
+
} // namespace Internal
} // namespace Valgrind
diff --git a/src/plugins/valgrind/memchecktool.h b/src/plugins/valgrind/memchecktool.h
index 153e51c805b..11ebe718cd0 100644
--- a/src/plugins/valgrind/memchecktool.h
+++ b/src/plugins/valgrind/memchecktool.h
@@ -54,6 +54,7 @@ namespace Internal {
class FrameFinder;
class MemcheckErrorView;
+class MemcheckRunControl;
class ValgrindBaseSettings;
class MemcheckErrorFilterProxyModel : public QSortFilterProxyModel
@@ -108,6 +109,11 @@ private:
void updateFromSettings();
int updateUiAfterFinishedHelper();
+protected:
+ virtual MemcheckRunControl *createMemcheckRunControl(
+ const Analyzer::AnalyzerStartParameters &sp,
+ ProjectExplorer::RunConfiguration *runConfiguration);
+
private:
ValgrindBaseSettings *m_settings;
QMenu *m_filterMenu;
@@ -126,6 +132,17 @@ private:
QAction *m_goNext;
};
+class MemcheckWithGdbTool : public MemcheckTool
+{
+public:
+ MemcheckWithGdbTool(QObject *parent);
+
+protected:
+ MemcheckRunControl *createMemcheckRunControl(
+ const Analyzer::AnalyzerStartParameters &sp,
+ ProjectExplorer::RunConfiguration *runConfiguration) Q_DECL_OVERRIDE;
+};
+
} // namespace Internal
} // namespace Valgrind
diff --git a/src/plugins/valgrind/suppressiondialog.cpp b/src/plugins/valgrind/suppressiondialog.cpp
index e93ac0eba53..2e6ae768d8a 100644
--- a/src/plugins/valgrind/suppressiondialog.cpp
+++ b/src/plugins/valgrind/suppressiondialog.cpp
@@ -166,10 +166,14 @@ SuppressionDialog::SuppressionDialog(MemcheckErrorView *view, const QList<Error>
m_suppressionEdit->setPlainText(suppressions);
- connect(m_fileChooser, SIGNAL(validChanged()), SLOT(validate()));
- connect(m_suppressionEdit->document(), SIGNAL(contentsChanged()), SLOT(validate()));
- connect(m_buttonBox, SIGNAL(accepted()), SLOT(accept()));
- connect(m_buttonBox, SIGNAL(rejected()), SLOT(reject()));
+ connect(m_fileChooser, static_cast<void (Utils::PathChooser:: *)()>(&Utils::PathChooser::validChanged),
+ this, &SuppressionDialog::validate);
+ connect(m_suppressionEdit->document(), &QTextDocument::contentsChanged,
+ this, &SuppressionDialog::validate);
+ connect(m_buttonBox, &QDialogButtonBox::accepted,
+ this, &SuppressionDialog::accept);
+ connect(m_buttonBox, &QDialogButtonBox::rejected,
+ this, &SuppressionDialog::reject);
}
void SuppressionDialog::maybeShow(MemcheckErrorView *view)
diff --git a/src/plugins/valgrind/valgrind.qbs b/src/plugins/valgrind/valgrind.qbs
index 527cf201cbd..ff4fd8bcce1 100644
--- a/src/plugins/valgrind/valgrind.qbs
+++ b/src/plugins/valgrind/valgrind.qbs
@@ -10,6 +10,7 @@ QtcPlugin {
Depends { name: "Core" }
Depends { name: "AnalyzerBase" }
+ Depends { name: "Debugger" }
Depends { name: "ProjectExplorer" }
Depends { name: "TextEditor" }
Depends { name: "RemoteLinux" }
diff --git a/src/plugins/valgrind/valgrind_dependencies.pri b/src/plugins/valgrind/valgrind_dependencies.pri
index 4faca50ffd7..0e3f39ac8a7 100644
--- a/src/plugins/valgrind/valgrind_dependencies.pri
+++ b/src/plugins/valgrind/valgrind_dependencies.pri
@@ -7,6 +7,7 @@ QTC_LIB_DEPENDS += \
QTC_PLUGIN_DEPENDS += \
analyzerbase \
coreplugin \
+ debugger \
projectexplorer \
texteditor \
remotelinux
diff --git a/src/plugins/valgrind/valgrindconfigwidget.cpp b/src/plugins/valgrind/valgrindconfigwidget.cpp
index 5c127ef4053..8d35d7e5160 100644
--- a/src/plugins/valgrind/valgrindconfigwidget.cpp
+++ b/src/plugins/valgrind/valgrindconfigwidget.cpp
@@ -63,14 +63,14 @@ ValgrindConfigWidget::ValgrindConfigWidget(ValgrindBaseSettings *settings,
m_ui->valgrindExeChooser->setPromptDialogTitle(tr("Valgrind Command"));
updateUi();
- connect(m_settings, SIGNAL(changed()), this, SLOT(updateUi()));
+ connect(m_settings, &ValgrindBaseSettings::changed, this, &ValgrindConfigWidget::updateUi);
- connect(m_ui->valgrindExeChooser, SIGNAL(changed(QString)),
- 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)));
+ connect(m_ui->valgrindExeChooser, &Utils::PathChooser::changed,
+ m_settings, &ValgrindBaseSettings::setValgrindExecutable);
+ connect(m_settings, &ValgrindBaseSettings::valgrindExecutableChanged,
+ m_ui->valgrindExeChooser, &Utils::PathChooser::setPath);
+ connect(m_ui->smcDetectionComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ m_settings, &ValgrindBaseSettings::setSelfModifyingCodeDetection);
if (Utils::HostOsInfo::isWindowsHost()) {
// FIXME: On Window we know that we don't have a local valgrind
@@ -82,40 +82,40 @@ ValgrindConfigWidget::ValgrindConfigWidget(ValgrindBaseSettings *settings,
//
// Callgrind
//
- connect(m_ui->enableCacheSim, SIGNAL(toggled(bool)),
- m_settings, SLOT(setEnableCacheSim(bool)));
- connect(m_settings, SIGNAL(enableCacheSimChanged(bool)),
- m_ui->enableCacheSim, SLOT(setChecked(bool)));
-
- connect(m_ui->enableBranchSim, SIGNAL(toggled(bool)),
- m_settings, SLOT(setEnableBranchSim(bool)));
- connect(m_settings, SIGNAL(enableBranchSimChanged(bool)),
- m_ui->enableBranchSim, SLOT(setChecked(bool)));
-
- connect(m_ui->collectSystime, SIGNAL(toggled(bool)),
- m_settings, SLOT(setCollectSystime(bool)));
- connect(m_settings, SIGNAL(collectSystimeChanged(bool)),
- m_ui->collectSystime, SLOT(setChecked(bool)));
-
- connect(m_ui->collectBusEvents, SIGNAL(toggled(bool)),
- m_settings, SLOT(setCollectBusEvents(bool)));
- connect(m_settings, SIGNAL(collectBusEventsChanged(bool)),
- m_ui->collectBusEvents, SLOT(setChecked(bool)));
-
- connect(m_ui->enableEventToolTips, SIGNAL(toggled(bool)),
- m_settings, SLOT(setEnableEventToolTips(bool)));
- connect(m_settings, SIGNAL(enableEventToolTipsChanged(bool)),
- m_ui->enableEventToolTips, SLOT(setChecked(bool)));
-
- connect(m_ui->minimumInclusiveCostRatio, SIGNAL(valueChanged(double)),
- m_settings, SLOT(setMinimumInclusiveCostRatio(double)));
- connect(m_settings, SIGNAL(minimumInclusiveCostRatioChanged(double)),
- m_ui->minimumInclusiveCostRatio, SLOT(setValue(double)));
-
- connect(m_ui->visualisationMinimumInclusiveCostRatio, SIGNAL(valueChanged(double)),
- m_settings, SLOT(setVisualisationMinimumInclusiveCostRatio(double)));
- connect(m_settings, SIGNAL(visualisationMinimumInclusiveCostRatioChanged(double)),
- m_ui->visualisationMinimumInclusiveCostRatio, SLOT(setValue(double)));
+ connect(m_ui->enableCacheSim, &QCheckBox::toggled,
+ m_settings, &ValgrindBaseSettings::setEnableCacheSim);
+ connect(m_settings, &ValgrindBaseSettings::enableCacheSimChanged,
+ m_ui->enableCacheSim, &QAbstractButton::setChecked);
+
+ connect(m_ui->enableBranchSim, &QCheckBox::toggled,
+ m_settings, &ValgrindBaseSettings::setEnableBranchSim);
+ connect(m_settings, &ValgrindBaseSettings::enableBranchSimChanged,
+ m_ui->enableBranchSim, &QAbstractButton::setChecked);
+
+ connect(m_ui->collectSystime, &QCheckBox::toggled,
+ m_settings, &ValgrindBaseSettings::setCollectSystime);
+ connect(m_settings, &ValgrindBaseSettings::collectSystimeChanged,
+ m_ui->collectSystime, &QAbstractButton::setChecked);
+
+ connect(m_ui->collectBusEvents, &QCheckBox::toggled,
+ m_settings, &ValgrindBaseSettings::setCollectBusEvents);
+ connect(m_settings, &ValgrindBaseSettings::collectBusEventsChanged,
+ m_ui->collectBusEvents, &QAbstractButton::setChecked);
+
+ connect(m_ui->enableEventToolTips, &QGroupBox::toggled,
+ m_settings, &ValgrindBaseSettings::setEnableEventToolTips);
+ connect(m_settings, &ValgrindBaseSettings::enableEventToolTipsChanged,
+ m_ui->enableEventToolTips, &QGroupBox::setChecked);
+
+ connect(m_ui->minimumInclusiveCostRatio, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
+ m_settings, &ValgrindBaseSettings::setMinimumInclusiveCostRatio);
+ connect(m_settings, &ValgrindBaseSettings::minimumInclusiveCostRatioChanged,
+ m_ui->minimumInclusiveCostRatio, &QDoubleSpinBox::setValue);
+
+ connect(m_ui->visualisationMinimumInclusiveCostRatio, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
+ m_settings, &ValgrindBaseSettings::setVisualisationMinimumInclusiveCostRatio);
+ connect(m_settings, &ValgrindBaseSettings::visualisationMinimumInclusiveCostRatioChanged,
+ m_ui->visualisationMinimumInclusiveCostRatio, &QDoubleSpinBox::setValue);
//
// Memcheck
@@ -123,37 +123,35 @@ ValgrindConfigWidget::ValgrindConfigWidget(ValgrindBaseSettings *settings,
m_ui->suppressionList->setModel(m_model);
m_ui->suppressionList->setSelectionMode(QAbstractItemView::MultiSelection);
- connect(m_ui->addSuppression, SIGNAL(clicked()),
- this, SLOT(slotAddSuppression()));
- connect(m_ui->removeSuppression, SIGNAL(clicked()),
- this, SLOT(slotRemoveSuppression()));
-
- 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)),
- m_ui->trackOrigins, SLOT(setChecked(bool)));
-
- connect(m_settings, SIGNAL(suppressionFilesRemoved(QStringList)),
- this, SLOT(slotSuppressionsRemoved(QStringList)));
- connect(m_settings, SIGNAL(suppressionFilesAdded(QStringList)),
- this, SLOT(slotSuppressionsAdded(QStringList)));
-
- connect(m_ui->suppressionList->selectionModel(),
- SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
- this, SLOT(slotSuppressionSelectionChanged()));
+ connect(m_ui->addSuppression, &QPushButton::clicked, this, &ValgrindConfigWidget::slotAddSuppression);
+ connect(m_ui->removeSuppression, &QPushButton::clicked, this, &ValgrindConfigWidget::slotRemoveSuppression);
+
+ connect(m_ui->numCallers, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged),
+ m_settings, &ValgrindBaseSettings::setNumCallers);
+ connect(m_settings, &ValgrindBaseSettings::numCallersChanged,
+ m_ui->numCallers, &QSpinBox::setValue);
+
+ connect(m_ui->leakCheckOnFinish, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ m_settings, &ValgrindBaseSettings::setLeakCheckOnFinish);
+ connect(m_settings, &ValgrindBaseSettings::leakCheckOnFinishChanged,
+ m_ui->leakCheckOnFinish, &QComboBox::setCurrentIndex);
+
+ connect(m_ui->showReachable, &QCheckBox::toggled,
+ m_settings, &ValgrindBaseSettings::setShowReachable);
+ connect(m_settings, &ValgrindBaseSettings::showReachableChanged,
+ m_ui->showReachable, &QAbstractButton::setChecked);
+
+ connect(m_ui->trackOrigins, &QCheckBox::toggled, m_settings, &ValgrindBaseSettings::setTrackOrigins);
+ connect(m_settings, &ValgrindBaseSettings::trackOriginsChanged,
+ m_ui->trackOrigins, &QAbstractButton::setChecked);
+
+ connect(m_settings, &ValgrindBaseSettings::suppressionFilesRemoved,
+ this, &ValgrindConfigWidget::slotSuppressionsRemoved);
+ connect(m_settings, &ValgrindBaseSettings::suppressionFilesAdded,
+ this, &ValgrindConfigWidget::slotSuppressionsAdded);
+
+ connect(m_ui->suppressionList->selectionModel(), &QItemSelectionModel::selectionChanged,
+ this, &ValgrindConfigWidget::slotSuppressionSelectionChanged);
slotSuppressionSelectionChanged();
if (!global) {
diff --git a/src/plugins/valgrind/valgrindengine.cpp b/src/plugins/valgrind/valgrindengine.cpp
index e6f7984c58e..19dc3c43fce 100644
--- a/src/plugins/valgrind/valgrindengine.cpp
+++ b/src/plugins/valgrind/valgrindengine.cpp
@@ -55,7 +55,7 @@ namespace Valgrind {
namespace Internal {
ValgrindRunControl::ValgrindRunControl(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
+ RunConfiguration *runConfiguration)
: AnalyzerRunControl(sp, runConfiguration),
m_settings(0),
m_isStopping(false)
@@ -79,8 +79,10 @@ bool ValgrindRunControl::startEngine()
FutureProgress *fp = ProgressManager::addTimedTask(m_progress, progressTitle(), "valgrind", 100);
fp->setKeepOnFinish(FutureProgress::HideOnFinish);
- connect(fp, SIGNAL(canceled()), this, SLOT(handleProgressCanceled()));
- connect(fp, SIGNAL(finished()), this, SLOT(handleProgressFinished()));
+ connect(fp, &FutureProgress::canceled,
+ this, &ValgrindRunControl::handleProgressCanceled);
+ connect(fp, &FutureProgress::finished,
+ this, &ValgrindRunControl::handleProgressFinished);
m_progress.reportStarted();
const AnalyzerStartParameters &sp = startParameters();
@@ -101,11 +103,12 @@ bool ValgrindRunControl::startEngine()
run->setStartMode(sp.startMode);
run->setLocalRunMode(sp.localRunMode);
- connect(run, SIGNAL(processOutputReceived(QString,Utils::OutputFormat)),
- SLOT(receiveProcessOutput(QString,Utils::OutputFormat)));
- connect(run, SIGNAL(processErrorReceived(QString,QProcess::ProcessError)),
- SLOT(receiveProcessError(QString,QProcess::ProcessError)));
- connect(run, SIGNAL(finished()), SLOT(runnerFinished()));
+ connect(run, &ValgrindRunner::processOutputReceived,
+ this, &ValgrindRunControl::receiveProcessOutput);
+ connect(run, &ValgrindRunner::processErrorReceived,
+ this, &ValgrindRunControl::receiveProcessError);
+ connect(run, &ValgrindRunner::finished,
+ this, &ValgrindRunControl::runnerFinished);
if (!run->start()) {
m_progress.cancel();
@@ -166,10 +169,10 @@ void ValgrindRunControl::runnerFinished()
m_progress.reportFinished();
- disconnect(runner(), SIGNAL(processOutputReceived(QString,Utils::OutputFormat)),
- this, SLOT(receiveProcessOutput(QString,Utils::OutputFormat)));
- disconnect(runner(), SIGNAL(finished()),
- this, SLOT(runnerFinished()));
+ disconnect(runner(), &ValgrindRunner::processOutputReceived,
+ this, &ValgrindRunControl::receiveProcessOutput);
+ disconnect(runner(), &ValgrindRunner::finished,
+ this, &ValgrindRunControl::runnerFinished);
}
void ValgrindRunControl::receiveProcessOutput(const QString &output, OutputFormat format)
diff --git a/src/plugins/valgrind/valgrindplugin.cpp b/src/plugins/valgrind/valgrindplugin.cpp
index b5bf594965a..8a186137f27 100644
--- a/src/plugins/valgrind/valgrindplugin.cpp
+++ b/src/plugins/valgrind/valgrindplugin.cpp
@@ -116,6 +116,7 @@ bool ValgrindPlugin::initialize(const QStringList &, QString *)
addAutoReleasedObject(new ValgrindOptionsPage());
m_memcheckTool = new MemcheckTool(this);
+ m_memcheckWithGdbTool = new MemcheckWithGdbTool(this);
m_callgrindTool = new CallgrindTool(this);
ValgrindAction *action = 0;
@@ -126,6 +127,10 @@ bool ValgrindPlugin::initialize(const QStringList &, QString *)
QString memcheckToolTip = tr("Valgrind Analyze Memory uses the "
"\"memcheck\" tool to find memory leaks.");
+ QString memcheckWithGdbToolTip = tr(
+ "Valgrind Analyze Memory with GDB uses the \"memcheck\" tool to find memory leaks.\n"
+ "When a problem is detected, the application is interrupted and can be debugged");
+
if (!Utils::HostOsInfo::isWindowsHost()) {
action = new ValgrindAction(this);
action->setId("Memcheck.Local");
@@ -138,6 +143,16 @@ bool ValgrindPlugin::initialize(const QStringList &, QString *)
AnalyzerManager::addAction(action);
action = new ValgrindAction(this);
+ action->setId("MemcheckWithGdb.Local");
+ action->setTool(m_memcheckWithGdbTool);
+ action->setText(tr("Valgrind Memory Analyzer with GDB"));
+ action->setToolTip(memcheckWithGdbToolTip);
+ action->setMenuGroup(Constants::G_ANALYZER_TOOLS);
+ action->setStartMode(StartLocal);
+ action->setEnabled(false);
+ AnalyzerManager::addAction(action);
+
+ action = new ValgrindAction(this);
action->setId("Callgrind.Local");
action->setTool(m_callgrindTool);
action->setText(tr("Valgrind Function Profiler"));
@@ -188,7 +203,8 @@ void ValgrindPlugin::extensionsInitialized()
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()));
+ connect(action, &QAction::triggered, m_callgrindTool,
+ &CallgrindTool::handleShowCostsOfFunction);
Command *cmd = ActionManager::registerAction(action, "Analyzer.Callgrind.ShowCostsOfFunction",
analyzerContext);
editorContextMenu->addAction(cmd);
diff --git a/src/plugins/valgrind/valgrindplugin.h b/src/plugins/valgrind/valgrindplugin.h
index 28ccbd82773..4d26842d813 100644
--- a/src/plugins/valgrind/valgrindplugin.h
+++ b/src/plugins/valgrind/valgrindplugin.h
@@ -40,6 +40,7 @@ namespace Internal {
class ValgrindGlobalSettings;
class MemcheckTool;
+class MemcheckWithGdbTool;
class CallgrindTool;
class ValgrindPlugin : public ExtensionSystem::IPlugin
@@ -58,6 +59,7 @@ public:
private:
MemcheckTool *m_memcheckTool;
+ MemcheckWithGdbTool *m_memcheckWithGdbTool;
CallgrindTool *m_callgrindTool;
};
diff --git a/src/plugins/valgrind/valgrindprocess.cpp b/src/plugins/valgrind/valgrindprocess.cpp
index baac3273650..a07a361cb79 100644
--- a/src/plugins/valgrind/valgrindprocess.cpp
+++ b/src/plugins/valgrind/valgrindprocess.cpp
@@ -31,12 +31,14 @@
#include "valgrindprocess.h"
+#include <utils/fileutils.h>
+#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
+
#include <QDebug>
#include <QEventLoop>
-#include <QFileInfo>
-#include <utils/qtcassert.h>
-#include <utils/qtcprocess.h>
+using namespace ProjectExplorer;
namespace Valgrind {
@@ -44,7 +46,7 @@ ValgrindProcess::ValgrindProcess(bool isLocal, const QSsh::SshConnectionParamete
QSsh::SshConnection *connection, QObject *parent)
: QObject(parent),
m_isLocal(isLocal),
- m_localRunMode(ProjectExplorer::ApplicationLauncher::Gui)
+ m_localRunMode(ApplicationLauncher::Gui)
{
m_remote.m_params = sshParams;
m_remote.m_connection = connection;
@@ -110,7 +112,7 @@ void ValgrindProcess::setEnvironment(const Utils::Environment &environment)
///TODO: remote anything that should/could be done here?
}
-void ValgrindProcess::setLocalRunMode(ProjectExplorer::ApplicationLauncher::Mode localRunMode)
+void ValgrindProcess::setLocalRunMode(ApplicationLauncher::Mode localRunMode)
{
m_localRunMode = localRunMode;
}
@@ -140,14 +142,14 @@ void ValgrindProcess::close()
void ValgrindProcess::run()
{
if (isLocal()) {
- connect(&m_localProcess, SIGNAL(processExited(int,QProcess::ExitStatus)),
- this, SIGNAL(finished(int,QProcess::ExitStatus)));
- connect(&m_localProcess, SIGNAL(processStarted()),
- this, SLOT(localProcessStarted()));
- connect(&m_localProcess, SIGNAL(error(QProcess::ProcessError)),
- this, SIGNAL(error(QProcess::ProcessError)));
- connect(&m_localProcess, SIGNAL(appendMessage(QString,Utils::OutputFormat)),
- this, SIGNAL(processOutput(QString,Utils::OutputFormat)));
+ connect(&m_localProcess, &ApplicationLauncher::processExited,
+ this, &ValgrindProcess::finished);
+ connect(&m_localProcess, &ApplicationLauncher::processStarted,
+ this, &ValgrindProcess::localProcessStarted);
+ connect(&m_localProcess, &ApplicationLauncher::error,
+ this, &ValgrindProcess::error);
+ connect(&m_localProcess, &ApplicationLauncher::appendMessage,
+ this, &ValgrindProcess::processOutput);
m_localProcess.start(m_localRunMode, m_valgrindExecutable,
argumentString(Utils::HostOsInfo::hostOs()));
@@ -161,9 +163,10 @@ void ValgrindProcess::run()
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(handleError(QSsh::SshError)));
+ connect(m_remote.m_connection, &QSsh::SshConnection::connected,
+ this, &ValgrindProcess::connected);
+ connect(m_remote.m_connection, &QSsh::SshConnection::error,
+ this, &ValgrindProcess::handleError);
if (m_remote.m_connection->state() == QSsh::SshConnection::Unconnected)
m_remote.m_connection->connectToHost();
} else {
@@ -180,10 +183,10 @@ QString ValgrindProcess::errorString() const
return m_remote.m_errorString;
}
-QProcess::ProcessError ValgrindProcess::error() const
+QProcess::ProcessError ValgrindProcess::processError() const
{
if (isLocal())
- return m_localProcess.error();
+ return m_localProcess.processError();
else
return m_remote.m_error;
}
@@ -239,14 +242,14 @@ void ValgrindProcess::connected()
cmd += m_remote.m_valgrindExe + QLatin1Char(' ') + argumentString(Utils::OsTypeLinux);
m_remote.m_process = m_remote.m_connection->createRemoteProcess(cmd.toUtf8());
- connect(m_remote.m_process.data(), SIGNAL(readyReadStandardError()),
- this, SLOT(handleRemoteStderr()));
- connect(m_remote.m_process.data(), SIGNAL(readyReadStandardOutput()),
- this, SLOT(handleRemoteStdout()));
- connect(m_remote.m_process.data(), SIGNAL(closed(int)),
- this, SLOT(closed(int)));
- connect(m_remote.m_process.data(), SIGNAL(started()),
- this, SLOT(remoteProcessStarted()));
+ connect(m_remote.m_process.data(), &QSsh::SshRemoteProcess::readyReadStandardError,
+ this, &ValgrindProcess::handleRemoteStderr);
+ connect(m_remote.m_process.data(), &QSsh::SshRemoteProcess::readyReadStandardOutput,
+ this, &ValgrindProcess::handleRemoteStdout);
+ connect(m_remote.m_process.data(), &QSsh::SshRemoteProcess::closed,
+ this, &ValgrindProcess::closed);
+ connect(m_remote.m_process.data(), &QSsh::SshRemoteProcess::started,
+ this, &ValgrindProcess::remoteProcessStarted);
m_remote.m_process->start();
}
@@ -282,13 +285,13 @@ void ValgrindProcess::remoteProcessStarted()
" | 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_remote.m_debuggee).fileName());
+ ).arg(proc, Utils::FileName::fromString(m_remote.m_debuggee).fileName());
m_remote.m_findPID = m_remote.m_connection->createRemoteProcess(cmd.toUtf8());
- connect(m_remote.m_findPID.data(), SIGNAL(readyReadStandardError()),
- this, SLOT(handleRemoteStderr()));
- connect(m_remote.m_findPID.data(), SIGNAL(readyReadStandardOutput()),
- this, SLOT(findPIDOutputReceived()));
+ connect(m_remote.m_findPID.data(), &QSsh::SshRemoteProcess::readyReadStandardError,
+ this, &ValgrindProcess::handleRemoteStderr);
+ connect(m_remote.m_findPID.data(), &QSsh::SshRemoteProcess::readyReadStandardOutput,
+ this, &ValgrindProcess::findPIDOutputReceived);
m_remote.m_findPID->start();
}
diff --git a/src/plugins/valgrind/valgrindprocess.h b/src/plugins/valgrind/valgrindprocess.h
index ee05a166d1c..47a79166dae 100644
--- a/src/plugins/valgrind/valgrindprocess.h
+++ b/src/plugins/valgrind/valgrindprocess.h
@@ -75,7 +75,7 @@ public:
void close();
QString errorString() const;
- QProcess::ProcessError error() const;
+ QProcess::ProcessError processError() const;
void setProcessChannelMode(QProcess::ProcessChannelMode mode);
void setWorkingDirectory(const QString &path);
diff --git a/src/plugins/valgrind/valgrindruncontrolfactory.cpp b/src/plugins/valgrind/valgrindruncontrolfactory.cpp
index 15c2c963714..a7aa0c1b4a9 100644
--- a/src/plugins/valgrind/valgrindruncontrolfactory.cpp
+++ b/src/plugins/valgrind/valgrindruncontrolfactory.cpp
@@ -65,7 +65,7 @@ ValgrindRunControlFactory::ValgrindRunControlFactory(QObject *parent) :
bool ValgrindRunControlFactory::canRun(RunConfiguration *runConfiguration, RunMode mode) const
{
Q_UNUSED(runConfiguration);
- return mode == CallgrindRunMode || mode == MemcheckRunMode;
+ return mode == CallgrindRunMode || mode == MemcheckRunMode || mode == MemcheckWithGdbRunMode;
}
RunControl *ValgrindRunControlFactory::create(RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage)
@@ -95,7 +95,7 @@ RunControl *ValgrindRunControlFactory::create(RunConfiguration *runConfiguration
sp.connParams.host = server.serverAddress().toString();
sp.connParams.port = server.serverPort();
sp.startMode = StartLocal;
- sp.localRunMode = static_cast<ProjectExplorer::ApplicationLauncher::Mode>(rc1->runMode());
+ sp.localRunMode = static_cast<ApplicationLauncher::Mode>(rc1->runMode());
} else if (RemoteLinux::AbstractRemoteLinuxRunConfiguration *rc2 =
qobject_cast<RemoteLinux::AbstractRemoteLinuxRunConfiguration *>(runConfiguration)) {
sp.startMode = StartRemote;
@@ -131,7 +131,7 @@ public:
RunConfigWidget *createConfigurationWidget()
{
- return new Analyzer::AnalyzerRunConfigWidget(this);
+ return new AnalyzerRunConfigWidget(this);
}
};
diff --git a/src/plugins/valgrind/valgrindrunner.cpp b/src/plugins/valgrind/valgrindrunner.cpp
index 3924cafa51b..2267ffca8d1 100644
--- a/src/plugins/valgrind/valgrindrunner.cpp
+++ b/src/plugins/valgrind/valgrindrunner.cpp
@@ -94,16 +94,16 @@ void ValgrindRunner::Private::run(ValgrindProcess *_process)
// consider appending our options last so they override any interfering user-supplied options
// -q as suggested by valgrind manual
- QObject::connect(process, SIGNAL(processOutput(QString,Utils::OutputFormat)),
- q, SIGNAL(processOutputReceived(QString,Utils::OutputFormat)));
- QObject::connect(process, SIGNAL(started()),
- q, SLOT(processStarted()));
- QObject::connect(process, SIGNAL(finished(int,QProcess::ExitStatus)),
- q, SLOT(processFinished(int,QProcess::ExitStatus)));
- QObject::connect(process, SIGNAL(error(QProcess::ProcessError)),
- q, SLOT(processError(QProcess::ProcessError)));
- QObject::connect(process, SIGNAL(localHostAddressRetrieved(QHostAddress)), q,
- SLOT(localHostAddressRetrieved(QHostAddress)));
+ QObject::connect(process, &ValgrindProcess::processOutput,
+ q, &ValgrindRunner::processOutputReceived);
+ QObject::connect(process, &ValgrindProcess::started,
+ q, &ValgrindRunner::started);
+ QObject::connect(process, &ValgrindProcess::finished,
+ q, &ValgrindRunner::processFinished);
+ QObject::connect(process, &ValgrindProcess::error,
+ q, &ValgrindRunner::processError);
+ QObject::connect(process, &ValgrindProcess::localHostAddressRetrieved, q,
+ &ValgrindRunner::localHostAddressRetrieved);
process->setValgrindExecutable(valgrindExecutable);
process->setValgrindArguments(q->fullValgrindArguments());
@@ -234,7 +234,7 @@ void ValgrindRunner::waitForFinished() const
return;
QEventLoop loop;
- connect(this, SIGNAL(finished()), &loop, SLOT(quit()));
+ connect(this, &ValgrindRunner::finished, &loop, &QEventLoop::quit);
loop.exec();
}
@@ -267,7 +267,7 @@ void ValgrindRunner::processFinished(int ret, QProcess::ExitStatus status)
emit finished();
if (ret != 0 || status == QProcess::CrashExit)
- emit processErrorReceived(errorString(), d->process->error());
+ emit processErrorReceived(errorString(), d->process->processError());
}
void ValgrindRunner::localHostAddressRetrieved(const QHostAddress &localHostAddress)
@@ -275,11 +275,6 @@ void ValgrindRunner::localHostAddressRetrieved(const QHostAddress &localHostAddr
Q_UNUSED(localHostAddress);
}
-void ValgrindRunner::processStarted()
-{
- emit started();
-}
-
QString ValgrindRunner::errorString() const
{
if (d->process)
diff --git a/src/plugins/valgrind/valgrindrunner.h b/src/plugins/valgrind/valgrindrunner.h
index 21ad9a99f1a..80ad3455e17 100644
--- a/src/plugins/valgrind/valgrindrunner.h
+++ b/src/plugins/valgrind/valgrindrunner.h
@@ -101,7 +101,6 @@ signals:
protected slots:
virtual void processError(QProcess::ProcessError);
- virtual void processStarted();
virtual void processFinished(int, QProcess::ExitStatus);
virtual void localHostAddressRetrieved(const QHostAddress &localHostAddress);
diff --git a/src/plugins/valgrind/valgrindtool.cpp b/src/plugins/valgrind/valgrindtool.cpp
index 9e4fa349461..9f69c4f57ab 100644
--- a/src/plugins/valgrind/valgrindtool.cpp
+++ b/src/plugins/valgrind/valgrindtool.cpp
@@ -126,9 +126,8 @@ static void startLocalTool(IAnalyzerTool *tool)
"Do you want to continue and run the tool in %2 mode?</p></body></html>")
.arg(toolName).arg(currentMode).arg(toolModeString);
if (Utils::CheckableMessageBox::doNotAskAgainQuestion(ICore::mainWindow(),
- title, message, ICore::settings(), QLatin1String("AnalyzerCorrectModeWarning"),
- QDialogButtonBox::Yes|QDialogButtonBox::Cancel,
- QDialogButtonBox::Cancel, QDialogButtonBox::Yes) != QDialogButtonBox::Yes)
+ title, message, ICore::settings(), QLatin1String("AnalyzerCorrectModeWarning"))
+ != QDialogButtonBox::Yes)
return;
}
diff --git a/src/plugins/valgrind/xmlprotocol/errorlistmodel.cpp b/src/plugins/valgrind/xmlprotocol/errorlistmodel.cpp
index e5689656786..ba7cf71348b 100644
--- a/src/plugins/valgrind/xmlprotocol/errorlistmodel.cpp
+++ b/src/plugins/valgrind/xmlprotocol/errorlistmodel.cpp
@@ -113,7 +113,7 @@ QString ErrorListModel::Private::formatAbsoluteFilePath(const Error &error) cons
{
const Frame f = findRelevantFrame(error);
if (!f.directory().isEmpty() && !f.file().isEmpty())
- return QString(f.directory() + QDir::separator() + f.file());
+ return f.directory() + QLatin1Char('/') + f.file();
return QString();
}
diff --git a/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp b/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp
index 7d3c426fcfa..3b01e69b475 100644
--- a/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp
+++ b/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp
@@ -44,7 +44,7 @@ QString toolTipForFrame(const Frame &frame)
{
QString location;
if (!frame.file().isEmpty()) {
- location = frame.directory() + QDir::separator() + frame.file();
+ location = frame.directory() + QLatin1Char('/') + frame.file();
if (frame.line() > 0)
location += QLatin1Char(':') + QString::number(frame.line());
}
diff --git a/src/plugins/valgrind/xmlprotocol/stackmodel.cpp b/src/plugins/valgrind/xmlprotocol/stackmodel.cpp
index 31edadcb947..9ae8beb48e2 100644
--- a/src/plugins/valgrind/xmlprotocol/stackmodel.cpp
+++ b/src/plugins/valgrind/xmlprotocol/stackmodel.cpp
@@ -65,8 +65,8 @@ static QString makeName(const Frame &frame)
if (!fn.isEmpty())
return fn;
if (!d.isEmpty() && !f.isEmpty())
- return frame.line() > 0 ? QString::fromLatin1("%1%2%3:%4").arg(d, QDir::separator(), f, QString::number(frame.line()))
- : QString::fromLatin1("%1%2%3").arg(d, QDir::separator(), f);
+ return frame.line() > 0 ? QString::fromLatin1("%1/%2:%3").arg(d, f).arg(frame.line())
+ : QString::fromLatin1("%1/%2").arg(d, f);
return frame.object();
}
diff --git a/src/plugins/valgrind/xmlprotocol/threadedparser.cpp b/src/plugins/valgrind/xmlprotocol/threadedparser.cpp
index fbe5e8afbd1..b9bd49e2c7e 100644
--- a/src/plugins/valgrind/xmlprotocol/threadedparser.cpp
+++ b/src/plugins/valgrind/xmlprotocol/threadedparser.cpp
@@ -108,29 +108,30 @@ void ThreadedParser::parse(QIODevice *device)
Parser *parser = new Parser;
qRegisterMetaType<Valgrind::XmlProtocol::Status>();
qRegisterMetaType<Valgrind::XmlProtocol::Error>();
- connect(parser, SIGNAL(status(Valgrind::XmlProtocol::Status)),
- SIGNAL(status(Valgrind::XmlProtocol::Status)),
+ connect(parser, &Parser::status,
+ this, &ThreadedParser::status,
Qt::QueuedConnection);
- connect(parser, SIGNAL(error(Valgrind::XmlProtocol::Error)),
- SIGNAL(error(Valgrind::XmlProtocol::Error)),
+ connect(parser, &Parser::error,
+ this, &ThreadedParser::error,
Qt::QueuedConnection);
- connect(parser, SIGNAL(internalError(QString)),
- SLOT(slotInternalError(QString)),
+ connect(parser, &Parser::internalError,
+ this, &ThreadedParser::slotInternalError,
Qt::QueuedConnection);
- connect(parser, SIGNAL(errorCount(qint64,qint64)),
- SIGNAL(errorCount(qint64,qint64)),
+ connect(parser, &Parser::errorCount,
+ this, &ThreadedParser::errorCount,
Qt::QueuedConnection);
- connect(parser, SIGNAL(suppressionCount(QString,qint64)),
- SIGNAL(suppressionCount(QString,qint64)),
+ connect(parser, &Parser::suppressionCount,
+ this, &ThreadedParser::suppressionCount,
Qt::QueuedConnection);
- connect(parser, SIGNAL(finished()), SIGNAL(finished()),
+ connect(parser, &Parser::finished,
+ this, &ThreadedParser::finished,
Qt::QueuedConnection);
Thread *thread = new Thread;
d->parserThread = thread;
- connect(thread, SIGNAL(finished()),
- thread, SLOT(deleteLater()));
+ connect(thread, &QThread::finished,
+ thread, &QObject::deleteLater);
device->setParent(0);
device->moveToThread(thread);
parser->moveToThread(thread);
diff --git a/src/plugins/vcsbase/basecheckoutwizardfactory.cpp b/src/plugins/vcsbase/basecheckoutwizardfactory.cpp
index fc701ad6a43..dfb29ccc6b9 100644
--- a/src/plugins/vcsbase/basecheckoutwizardfactory.cpp
+++ b/src/plugins/vcsbase/basecheckoutwizardfactory.cpp
@@ -31,6 +31,8 @@
#include "basecheckoutwizardfactory.h"
#include "basecheckoutwizard.h"
+#include <coreplugin/icontext.h>
+#include <coreplugin/icore.h>
#include <coreplugin/featureprovider.h>
#include <projectexplorer/projectexplorer.h>
@@ -86,6 +88,7 @@ void BaseCheckoutWizardFactory::runWizard(const QString &path, QWidget *parent,
{
QScopedPointer<BaseCheckoutWizard> wizard(m_wizardCreator(Utils::FileName::fromString(path), parent));
wizard->setWindowTitle(displayName());
+ Core::ICore::registerWindow(wizard.data(), Core::Context("New.CheckoutWizard"));
checkoutPath = wizard->run();
}
diff --git a/src/plugins/vcsbase/checkoutprogresswizardpage.cpp b/src/plugins/vcsbase/checkoutprogresswizardpage.cpp
index 2681cddf5aa..4efaee4b155 100644
--- a/src/plugins/vcsbase/checkoutprogresswizardpage.cpp
+++ b/src/plugins/vcsbase/checkoutprogresswizardpage.cpp
@@ -61,7 +61,7 @@ CheckoutProgressWizardPage::CheckoutProgressWizardPage(QWidget *parent) :
m_state(Idle)
{
resize(264, 200);
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
+ auto verticalLayout = new QVBoxLayout(this);
m_logPlainTextEdit = new QPlainTextEdit;
m_formatter = new Utils::OutputFormatter;
m_logPlainTextEdit->setReadOnly(true);
diff --git a/src/plugins/vcsbase/cleandialog.cpp b/src/plugins/vcsbase/cleandialog.cpp
index 3ab7591d9bd..aa8c5ef1038 100644
--- a/src/plugins/vcsbase/cleandialog.cpp
+++ b/src/plugins/vcsbase/cleandialog.cpp
@@ -214,7 +214,7 @@ void CleanDialog::addFile(const QString &workingDirectory, QString fileName, boo
bool isDir = fi.isDir();
if (isDir)
checked = false;
- QStandardItem *nameItem = new QStandardItem(QDir::toNativeSeparators(fileName));
+ auto nameItem = new QStandardItem(QDir::toNativeSeparators(fileName));
nameItem->setFlags(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
nameItem->setIcon(isDir ? folderIcon : fileIcon);
nameItem->setCheckable(true);
@@ -261,7 +261,7 @@ bool CleanDialog::promptToDelete()
return false;
// Remove in background
- Internal::CleanFilesTask *cleanTask = new Internal::CleanFilesTask(d->m_workingDirectory, selectedFiles);
+ auto cleanTask = new Internal::CleanFilesTask(d->m_workingDirectory, selectedFiles);
connect(cleanTask, SIGNAL(error(QString)),
VcsOutputWindow::instance(), SLOT(appendSilently(QString)),
Qt::QueuedConnection);
diff --git a/src/plugins/vcsbase/nicknamedialog.cpp b/src/plugins/vcsbase/nicknamedialog.cpp
index e805941060c..d28c0226db7 100644
--- a/src/plugins/vcsbase/nicknamedialog.cpp
+++ b/src/plugins/vcsbase/nicknamedialog.cpp
@@ -137,16 +137,16 @@ QList<QStandardItem *> NickNameEntry::toModelRow() const
{
const QVariant nickNameData = nickName();
const Qt::ItemFlags flags = Qt::ItemIsSelectable|Qt::ItemIsEnabled;
- QStandardItem *i1 = new QStandardItem(name);
+ auto i1 = new QStandardItem(name);
i1->setFlags(flags);
i1->setData(nickNameData, NickNameRole);
- QStandardItem *i2 = new QStandardItem(email);
+ auto i2 = new QStandardItem(email);
i1->setFlags(flags);
i2->setData(nickNameData, NickNameRole);
- QStandardItem *i3 = new QStandardItem(aliasName);
+ auto i3 = new QStandardItem(aliasName);
i3->setFlags(flags);
i3->setData(nickNameData, NickNameRole);
- QStandardItem *i4 = new QStandardItem(aliasEmail);
+ auto i4 = new QStandardItem(aliasEmail);
i4->setFlags(flags);
i4->setData(nickNameData, NickNameRole);
QList<QStandardItem *> row;
@@ -231,7 +231,7 @@ QString NickNameDialog::nickName() const
QStandardItemModel *NickNameDialog::createModel(QObject *parent)
{
- QStandardItemModel *model = new QStandardItemModel(parent);
+ auto model = new QStandardItemModel(parent);
QStringList headers;
headers << tr("Name") << tr("Email")
<< tr("Alias") << tr("Alias email");
diff --git a/src/plugins/vcsbase/submiteditorfile.cpp b/src/plugins/vcsbase/submiteditorfile.cpp
index d8c10533c07..cc5175849e4 100644
--- a/src/plugins/vcsbase/submiteditorfile.cpp
+++ b/src/plugins/vcsbase/submiteditorfile.cpp
@@ -38,6 +38,7 @@
using namespace VcsBase;
using namespace VcsBase::Internal;
+using namespace Utils;
/*!
\class VcsBase::Internal::SubmitEditorFile
@@ -71,15 +72,15 @@ void SubmitEditorFile::setModified(bool modified)
bool SubmitEditorFile::save(QString *errorString, const QString &fileName, bool autoSave)
{
- const QString fName = fileName.isEmpty() ? filePath() : fileName;
- Utils::FileSaver saver(fName, QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
+ const FileName fName = fileName.isEmpty() ? filePath() : FileName::fromString(fileName);
+ FileSaver saver(fName.toString(),
+ 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());
+ setFilePath(FileName::fromUserInput(fName.toFileInfo().absoluteFilePath()));
setModified(false);
if (!errorString->isEmpty())
return false;
diff --git a/src/plugins/vcsbase/submiteditorwidget.cpp b/src/plugins/vcsbase/submiteditorwidget.cpp
index c0c9905f268..0a031ca3f39 100644
--- a/src/plugins/vcsbase/submiteditorwidget.cpp
+++ b/src/plugins/vcsbase/submiteditorwidget.cpp
@@ -600,7 +600,7 @@ void SubmitEditorWidget::addSubmitFieldWidget(SubmitFieldWidget *f)
if (!d->m_fieldLayout) {
// VBox with horizontal, expanding spacer
d->m_fieldLayout = new QVBoxLayout;
- QHBoxLayout *outerLayout = new QHBoxLayout;
+ auto outerLayout = new QHBoxLayout;
outerLayout->addLayout(d->m_fieldLayout);
outerLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
d->m_ui.descriptionLayout->addLayout(outerLayout);
diff --git a/src/plugins/vcsbase/submiteditorwidget.ui b/src/plugins/vcsbase/submiteditorwidget.ui
index 3bde1b3feb5..654fc52e010 100644
--- a/src/plugins/vcsbase/submiteditorwidget.ui
+++ b/src/plugins/vcsbase/submiteditorwidget.ui
@@ -6,21 +6,24 @@
<rect>
<x>0</x>
<y>0</y>
- <width>582</width>
- <height>502</height>
+ <width>720</width>
+ <height>485</height>
</rect>
</property>
<property name="windowTitle">
<string>Subversion Submit</string>
</property>
- <layout class="QVBoxLayout">
+ <layout class="QVBoxLayout" name="vboxLayout">
<item>
- <widget class="QSplitter" name="splitter">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
+ <widget class="Core::MiniSplitter" name="splitter">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
</property>
- <property name="childrenCollapsible">
- <bool>false</bool>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
</property>
<widget class="QGroupBox" name="descriptionBox">
<property name="title">
@@ -39,60 +42,51 @@
</item>
</layout>
</widget>
- <widget class="QWidget" name="verticalLayoutWidget">
- <layout class="QVBoxLayout" name="verticalLayout_3">
- <property name="topMargin">
- <number>0</number>
- </property>
+ <widget class="QGroupBox" name="groupBox">
+ <property name="title">
+ <string>F&amp;iles</string>
+ </property>
+ <property name="flat">
+ <bool>true</bool>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
<item>
- <widget class="QGroupBox" name="groupBox">
- <property name="title">
- <string>F&amp;iles</string>
+ <widget class="QCheckBox" name="checkAllCheckBox">
+ <property name="text">
+ <string>Select a&amp;ll</string>
</property>
- <property name="flat">
- <bool>true</bool>
+ <property name="tristate">
+ <bool>false</bool>
</property>
- <layout class="QVBoxLayout" name="verticalLayout_2">
- <item>
- <widget class="QCheckBox" name="checkAllCheckBox">
- <property name="text">
- <string>Select a&amp;ll</string>
- </property>
- <property name="tristate">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QTreeView" name="fileView"/>
- </item>
- </layout>
</widget>
</item>
<item>
- <layout class="QHBoxLayout" name="buttonLayout">
- <property name="leftMargin">
- <number>0</number>
- </property>
- <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 class="QTreeView" name="fileView"/>
</item>
</layout>
</widget>
</widget>
</item>
+ <item>
+ <layout class="QHBoxLayout" name="buttonLayout">
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
</layout>
</widget>
<customwidgets>
@@ -101,6 +95,12 @@
<extends>QTextEdit</extends>
<header location="global">utils/completingtextedit.h</header>
</customwidget>
+ <customwidget>
+ <class>Core::MiniSplitter</class>
+ <extends>QSplitter</extends>
+ <header location="global">coreplugin/minisplitter.h</header>
+ <container>1</container>
+ </customwidget>
</customwidgets>
<resources/>
<connections/>
diff --git a/src/plugins/vcsbase/submitfilemodel.cpp b/src/plugins/vcsbase/submitfilemodel.cpp
index 97b578ff6f5..354bd39c660 100644
--- a/src/plugins/vcsbase/submitfilemodel.cpp
+++ b/src/plugins/vcsbase/submitfilemodel.cpp
@@ -48,7 +48,7 @@ enum { fileColumn = 1 };
static QList<QStandardItem *> createFileRow(const QString &fileName, const QString &status,
CheckMode checked, const QVariant &v)
{
- QStandardItem *statusItem = new QStandardItem(status);
+ auto statusItem = new QStandardItem(status);
Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
if (checked != Uncheckable) {
flags |= Qt::ItemIsUserCheckable;
@@ -56,7 +56,7 @@ static QList<QStandardItem *> createFileRow(const QString &fileName, const QStri
}
statusItem->setFlags(flags);
statusItem->setData(v);
- QStandardItem *fileItem = new QStandardItem(fileName);
+ auto fileItem = new QStandardItem(fileName);
fileItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
fileItem->setIcon(Core::FileIconProvider::icon(fileName));
QList<QStandardItem *> row;
@@ -131,8 +131,11 @@ void SubmitFileModel::setChecked(int row, bool check)
void SubmitFileModel::setAllChecked(bool check)
{
int rows = rowCount();
- for (int row = 0; row < rows; ++row)
- item(row)->setCheckState(check ? Qt::Checked : Qt::Unchecked);
+ for (int row = 0; row < rows; ++row) {
+ QStandardItem *i = item(row);
+ if (i->isCheckable())
+ i->setCheckState(check ? Qt::Checked : Qt::Unchecked);
+ }
}
QVariant SubmitFileModel::extraData(int row) const
diff --git a/src/plugins/vcsbase/vcsbase.pro b/src/plugins/vcsbase/vcsbase.pro
index b90ae857c73..91b4e110136 100644
--- a/src/plugins/vcsbase/vcsbase.pro
+++ b/src/plugins/vcsbase/vcsbase.pro
@@ -2,7 +2,8 @@ DEFINES += VCSBASE_LIBRARY
include(../../qtcreatorplugin.pri)
HEADERS += vcsbase_global.h \
vcsbaseconstants.h \
- vcsconfigurationpage.h \
+ wizard/vcsconfigurationpage.h \
+ wizard/vcsjsextension.h \
vcsplugin.h \
corelistener.h \
vcsbaseplugin.h \
@@ -33,7 +34,8 @@ HEADERS += vcsbase_global.h \
SOURCES += vcsplugin.cpp \
vcsbaseplugin.cpp \
- vcsconfigurationpage.cpp \
+ wizard/vcsconfigurationpage.cpp \
+ wizard/vcsjsextension.cpp \
corelistener.cpp \
baseannotationhighlighter.cpp \
diffhighlighter.cpp \
diff --git a/src/plugins/vcsbase/vcsbase.qbs b/src/plugins/vcsbase/vcsbase.qbs
index c6a0bbe879a..36072b9e25b 100644
--- a/src/plugins/vcsbase/vcsbase.qbs
+++ b/src/plugins/vcsbase/vcsbase.qbs
@@ -72,8 +72,6 @@ QtcPlugin {
"vcsbasesubmiteditor.h",
"vcscommand.cpp",
"vcscommand.h",
- "vcsconfigurationpage.cpp",
- "vcsconfigurationpage.h",
"vcsoutputwindow.cpp",
"vcsoutputwindow.h",
"vcsplugin.cpp",
@@ -81,5 +79,9 @@ QtcPlugin {
"images/diff.png",
"images/removesubmitfield.png",
"images/submit.png",
+ "wizard/vcsconfigurationpage.cpp",
+ "wizard/vcsconfigurationpage.h",
+ "wizard/vcsjsextension.cpp",
+ "wizard/vcsjsextension.h",
]
}
diff --git a/src/plugins/vcsbase/vcsbaseclient.cpp b/src/plugins/vcsbase/vcsbaseclient.cpp
index a290804efea..e38abbd3e10 100644
--- a/src/plugins/vcsbase/vcsbaseclient.cpp
+++ b/src/plugins/vcsbase/vcsbaseclient.cpp
@@ -81,93 +81,53 @@ class VcsBaseClientPrivate
public:
VcsBaseClientPrivate(VcsBaseClient *client, VcsBaseClientSettings *settings);
- void statusParser(const QString &text);
- void annotateRevision(const QString &workingDirectory, const QString &file,
- QString change, int lineNumber);
- void saveSettings();
-
void bindCommandToEditor(VcsCommand *cmd, VcsBaseEditorWidget *editor);
- void commandFinishedGotoLine(QWidget *editorObject);
+
+ VcsBaseEditorParameterWidget *createDiffEditor();
+ VcsBaseEditorParameterWidget *createLogEditor();
VcsBaseClientSettings *m_clientSettings;
QSignalMapper *m_cmdFinishedMapper;
-private:
- VcsBaseClient *m_client;
+ VcsBaseClient::ParameterWidgetCreator m_diffParamWidgetCreator;
+ VcsBaseClient::ParameterWidgetCreator m_logParamWidgetCreator;
};
VcsBaseClientPrivate::VcsBaseClientPrivate(VcsBaseClient *client, VcsBaseClientSettings *settings) :
m_clientSettings(settings),
- m_cmdFinishedMapper(new QSignalMapper(client)),
- m_client(client)
-{
-}
-
-void VcsBaseClientPrivate::statusParser(const QString &text)
-{
- QList<VcsBaseClient::StatusItem> lineInfoList;
-
- QStringList rawStatusList = text.split(QLatin1Char('\n'));
-
- foreach (const QString &string, rawStatusList) {
- const VcsBaseClient::StatusItem lineInfo = m_client->parseStatusLine(string);
- if (!lineInfo.flags.isEmpty() && !lineInfo.file.isEmpty())
- lineInfoList.append(lineInfo);
- }
-
- emit m_client->parsedStatus(lineInfoList);
-}
-
-void VcsBaseClientPrivate::annotateRevision(const QString &workingDirectory, const QString &file,
- QString change, int lineNumber)
-{
- // This might be invoked with a verbose revision description
- // "SHA1 author subject" from the annotation context menu. Strip the rest.
- const int blankPos = change.indexOf(QLatin1Char(' '));
- if (blankPos != -1)
- change.truncate(blankPos);
- m_client->annotate(workingDirectory, file, change, lineNumber);
-}
-
-void VcsBaseClientPrivate::saveSettings()
-{
- m_clientSettings->writeSettings(Core::ICore::settings());
-}
+ m_cmdFinishedMapper(new QSignalMapper(client))
+{ }
void VcsBaseClientPrivate::bindCommandToEditor(VcsCommand *cmd, VcsBaseEditorWidget *editor)
{
editor->setCommand(cmd);
- QObject::connect(cmd, SIGNAL(finished(bool,int,QVariant)), m_cmdFinishedMapper, SLOT(map()));
+ QObject::connect(cmd, &VcsCommand::finished,
+ m_cmdFinishedMapper, static_cast<void (QSignalMapper::*)()>(&QSignalMapper::map));
m_cmdFinishedMapper->setMapping(cmd, editor);
}
-void VcsBaseClientPrivate::commandFinishedGotoLine(QWidget *editorObject)
+VcsBaseEditorParameterWidget *VcsBaseClientPrivate::createDiffEditor()
{
- VcsBaseEditorWidget *editor = qobject_cast<VcsBaseEditorWidget *>(editorObject);
- VcsCommand *cmd = qobject_cast<VcsCommand *>(m_cmdFinishedMapper->mapping(editor));
- if (editor && cmd) {
- if (!cmd->lastExecutionSuccess()) {
- editor->reportCommandFinished(false, cmd->lastExecutionExitCode(), cmd->cookie());
- } else if (cmd->cookie().type() == QVariant::Int) {
- const int line = cmd->cookie().toInt();
- if (line >= 0)
- editor->gotoLine(line);
- }
- m_cmdFinishedMapper->removeMappings(cmd);
- }
+ return m_diffParamWidgetCreator ? m_diffParamWidgetCreator() : 0;
}
-VcsBaseClient::StatusItem::StatusItem(const QString &s, const QString &f) :
- flags(s), file(f)
+VcsBaseEditorParameterWidget *VcsBaseClientPrivate::createLogEditor()
{
+ return m_logParamWidgetCreator ? m_logParamWidgetCreator() : 0;
}
+VcsBaseClient::StatusItem::StatusItem(const QString &s, const QString &f) :
+ flags(s), file(f)
+{ }
+
VcsBaseClient::VcsBaseClient(VcsBaseClientSettings *settings) :
d(new VcsBaseClientPrivate(this, settings))
{
qRegisterMetaType<QVariant>();
- connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSettings()));
- connect(d->m_cmdFinishedMapper, SIGNAL(mapped(QWidget*)), this, SLOT(commandFinishedGotoLine(QWidget*)));
+ connect(Core::ICore::instance(), &Core::ICore::saveSettingsRequested,
+ this, &VcsBaseClient::saveSettings);
+ connect(d->m_cmdFinishedMapper, static_cast<void (QSignalMapper::*)(QWidget*)>(&QSignalMapper::mapped),
+ this, &VcsBaseClient::commandFinishedGotoLine);
}
VcsBaseClient::~VcsBaseClient()
@@ -350,10 +310,12 @@ void VcsBaseClient::diff(const QString &workingDir, const QStringList &files,
editor->setWorkingDirectory(workingDir);
VcsBaseEditorParameterWidget *paramWidget = editor->configurationWidget();
- if (!paramWidget && (paramWidget = createDiffEditor(workingDir, files, extraOptions))) {
+ if (!paramWidget && (paramWidget = d->createDiffEditor())) {
// editor has been just created, createVcsEditor() didn't set a configuration widget yet
connect(editor, &VcsBaseEditorWidget::diffChunkReverted,
paramWidget, &VcsBaseEditorParameterWidget::executeCommand);
+ connect(paramWidget, &VcsBaseEditorParameterWidget::commandExecutionRequested,
+ [=] { diff(workingDir, files, extraOptions); } );
editor->setConfigurationWidget(paramWidget);
}
@@ -380,8 +342,10 @@ void VcsBaseClient::log(const QString &workingDir, const QStringList &files,
editor->setFileLogAnnotateEnabled(enableAnnotationContextMenu);
VcsBaseEditorParameterWidget *paramWidget = editor->configurationWidget();
- if (!paramWidget && (paramWidget = createLogEditor(workingDir, files, extraOptions))) {
+ if (!paramWidget && (paramWidget = d->createLogEditor())) {
// editor has been just created, createVcsEditor() didn't set a configuration widget yet
+ connect(paramWidget, &VcsBaseEditorParameterWidget::commandExecutionRequested,
+ [=]() { this->log(workingDir, files, extraOptions, enableAnnotationContextMenu); } );
editor->setConfigurationWidget(paramWidget);
}
@@ -401,7 +365,7 @@ void VcsBaseClient::revertFile(const QString &workingDir,
// Indicate repository change or file list
VcsCommand *cmd = createCommand(workingDir);
cmd->setCookie(QStringList(workingDir + QLatin1Char('/') + file));
- connect(cmd, SIGNAL(success(QVariant)), this, SIGNAL(changed(QVariant)), Qt::QueuedConnection);
+ connect(cmd, &VcsCommand::success, this, &VcsBaseClient::changed, Qt::QueuedConnection);
enqueueJob(cmd, args);
}
@@ -413,7 +377,7 @@ void VcsBaseClient::revertAll(const QString &workingDir, const QString &revision
// Indicate repository change or file list
VcsCommand *cmd = createCommand(workingDir);
cmd->setCookie(QStringList(workingDir));
- connect(cmd, SIGNAL(success(QVariant)), this, SIGNAL(changed(QVariant)), Qt::QueuedConnection);
+ connect(cmd, &VcsCommand::success, this, &VcsBaseClient::changed, Qt::QueuedConnection);
enqueueJob(createCommand(workingDir), args);
}
@@ -424,7 +388,8 @@ void VcsBaseClient::status(const QString &workingDir, const QString &file,
args << extraOptions << file;
VcsOutputWindow::setRepository(workingDir);
VcsCommand *cmd = createCommand(workingDir, 0, VcsWindowOutputBind);
- connect(cmd, SIGNAL(finished(bool,int,QVariant)), VcsOutputWindow::instance(), SLOT(clearRepository()),
+ connect(cmd, &VcsCommand::finished,
+ VcsOutputWindow::instance(), &VcsOutputWindow::clearRepository,
Qt::QueuedConnection);
enqueueJob(cmd, args);
}
@@ -434,7 +399,7 @@ void VcsBaseClient::emitParsedStatus(const QString &repository, const QStringLis
QStringList args(vcsCommandString(StatusCommand));
args << extraOptions;
VcsCommand *cmd = createCommand(repository);
- connect(cmd, SIGNAL(output(QString)), this, SLOT(statusParser(QString)));
+ connect(cmd, &VcsCommand::output, this, &VcsBaseClient::statusParser);
enqueueJob(cmd, args);
}
@@ -467,6 +432,16 @@ Utils::ExitCodeInterpreter *VcsBaseClient::exitCodeInterpreter(VcsCommandTag cmd
return 0;
}
+void VcsBaseClient::setDiffParameterWidgetCreator(ParameterWidgetCreator creator)
+{
+ d->m_diffParamWidgetCreator = std::move(creator);
+}
+
+void VcsBaseClient::setLogParameterWidgetCreator(ParameterWidgetCreator creator)
+{
+ d->m_logParamWidgetCreator = std::move(creator);
+}
+
void VcsBaseClient::import(const QString &repositoryRoot, const QStringList &files,
const QStringList &extraOptions)
{
@@ -497,7 +472,7 @@ void VcsBaseClient::update(const QString &repositoryRoot, const QString &revisio
args << revisionSpec(revision) << extraOptions;
VcsCommand *cmd = createCommand(repositoryRoot);
cmd->setCookie(repositoryRoot);
- connect(cmd, SIGNAL(success(QVariant)), this, SIGNAL(changed(QVariant)), Qt::QueuedConnection);
+ connect(cmd, &VcsCommand::success, this, &VcsBaseClient::changed, Qt::QueuedConnection);
enqueueJob(cmd, args);
}
@@ -514,10 +489,12 @@ void VcsBaseClient::commit(const QString &repositoryRoot,
// So descendants of VcsBaseClient *must* redefine commit() and extend
// extraOptions with the usage for commitMessageFile (see BazaarClient::commit()
// for example)
- Q_UNUSED(commitMessageFile);
QStringList args(vcsCommandString(CommitCommand));
args << extraOptions << files;
- enqueueJob(createCommand(repositoryRoot), args);
+ VcsCommand *cmd = createCommand(repositoryRoot, 0, VcsWindowOutputBind);
+ if (!commitMessageFile.isEmpty())
+ connect(cmd, &VcsCommand::finished, [commitMessageFile]() { QFile(commitMessageFile).remove(); });
+ enqueueJob(cmd, args);
}
VcsBaseClientSettings *VcsBaseClient::settings() const
@@ -525,32 +502,12 @@ VcsBaseClientSettings *VcsBaseClient::settings() const
return d->m_clientSettings;
}
-VcsBaseEditorParameterWidget *VcsBaseClient::createDiffEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions)
-{
- Q_UNUSED(workingDir);
- Q_UNUSED(files);
- Q_UNUSED(extraOptions);
- return 0;
-}
-
-VcsBaseEditorParameterWidget *VcsBaseClient::createLogEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions)
-{
- Q_UNUSED(workingDir);
- Q_UNUSED(files);
- Q_UNUSED(extraOptions);
- return 0;
-}
-
QString VcsBaseClient::vcsEditorTitle(const QString &vcsCmd, const QString &sourceId) const
{
const Utils::FileName binary = settings()->binaryPath();
return binary.toFileInfo().baseName() +
QLatin1Char(' ') + vcsCmd + QLatin1Char(' ') +
- QFileInfo(sourceId).fileName();
+ Utils::FileName::fromString(sourceId).fileName();
}
VcsBaseEditorWidget *VcsBaseClient::createVcsEditor(Core::Id kind, QString title,
@@ -571,8 +528,8 @@ VcsBaseEditorWidget *VcsBaseClient::createVcsEditor(Core::Id kind, QString title
outputEditor = Core::EditorManager::openEditorWithContents(kind, &title, progressMsg.toUtf8());
outputEditor->document()->setProperty(registerDynamicProperty, dynamicPropertyValue);
baseEditor = VcsBaseEditor::getVcsBaseEditor(outputEditor);
- connect(baseEditor, SIGNAL(annotateRevisionRequested(QString,QString,QString,int)),
- this, SLOT(annotateRevision(QString,QString,QString,int)));
+ connect(baseEditor, &VcsBaseEditorWidget::annotateRevisionRequested,
+ this, &VcsBaseClient::annotateRevision);
QTC_ASSERT(baseEditor, return 0);
baseEditor->setSource(source);
if (setSourceCodec)
@@ -594,8 +551,8 @@ VcsCommand *VcsBaseClient::createCommand(const QString &workingDirectory,
VcsBaseEditorWidget *editor,
JobOutputBindMode mode) const
{
- VcsCommand *cmd = new VcsCommand(d->m_clientSettings->binaryPath(), workingDirectory,
- processEnvironment());
+ auto cmd = new VcsCommand(d->m_clientSettings->binaryPath(), workingDirectory,
+ processEnvironment());
cmd->setDefaultTimeout(d->m_clientSettings->intValue(VcsBaseClientSettings::timeoutKey));
if (editor)
d->bindCommandToEditor(cmd, editor);
@@ -604,7 +561,7 @@ VcsCommand *VcsBaseClient::createCommand(const QString &workingDirectory,
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)));
+ connect(cmd, &VcsCommand::output, editor, &VcsBaseEditorWidget::setPlainText);
}
return cmd;
@@ -621,6 +578,54 @@ void VcsBaseClient::resetCachedVcsInfo(const QString &workingDir)
Core::VcsManager::resetVersionControlForDirectory(workingDir);
}
+void VcsBaseClient::statusParser(const QString &text)
+{
+ QList<VcsBaseClient::StatusItem> lineInfoList;
+
+ QStringList rawStatusList = text.split(QLatin1Char('\n'));
+
+ foreach (const QString &string, rawStatusList) {
+ const VcsBaseClient::StatusItem lineInfo = parseStatusLine(string);
+ if (!lineInfo.flags.isEmpty() && !lineInfo.file.isEmpty())
+ lineInfoList.append(lineInfo);
+ }
+
+ emit parsedStatus(lineInfoList);
+}
+
+void VcsBaseClient::annotateRevision(const QString &workingDirectory, const QString &file,
+ const QString& change, int lineNumber)
+{
+ QString changeCopy = change;
+ // This might be invoked with a verbose revision description
+ // "SHA1 author subject" from the annotation context menu. Strip the rest.
+ const int blankPos = changeCopy.indexOf(QLatin1Char(' '));
+ if (blankPos != -1)
+ changeCopy.truncate(blankPos);
+ annotate(workingDirectory, file, changeCopy, lineNumber);
+}
+
+void VcsBaseClient::saveSettings()
+{
+ settings()->writeSettings(Core::ICore::settings());
+}
+
+void VcsBaseClient::commandFinishedGotoLine(QWidget *editorObject)
+{
+ VcsBaseEditorWidget *editor = qobject_cast<VcsBaseEditorWidget *>(editorObject);
+ VcsCommand *cmd = qobject_cast<VcsCommand *>(d->m_cmdFinishedMapper->mapping(editor));
+ if (editor && cmd) {
+ if (!cmd->lastExecutionSuccess()) {
+ editor->reportCommandFinished(false, cmd->lastExecutionExitCode(), cmd->cookie());
+ } else if (cmd->cookie().type() == QVariant::Int) {
+ const int line = cmd->cookie().toInt();
+ if (line >= 0)
+ editor->gotoLine(line);
+ }
+ d->m_cmdFinishedMapper->removeMappings(cmd);
+ }
+}
+
} // namespace VcsBase
#include "moc_vcsbaseclient.cpp"
diff --git a/src/plugins/vcsbase/vcsbaseclient.h b/src/plugins/vcsbase/vcsbaseclient.h
index 65b3c2f7a48..dacc51ac94b 100644
--- a/src/plugins/vcsbase/vcsbaseclient.h
+++ b/src/plugins/vcsbase/vcsbaseclient.h
@@ -37,6 +37,8 @@
#include <QObject>
#include <QStringList>
+#include <functional>
+
QT_BEGIN_NAMESPACE
class QFileInfo;
class QVariant;
@@ -155,12 +157,11 @@ protected:
virtual Utils::ExitCodeInterpreter *exitCodeInterpreter(VcsCommandTag cmd, QObject *parent) const;
virtual QStringList revisionSpec(const QString &revision) const = 0;
- virtual VcsBaseEditorParameterWidget *createDiffEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions);
- virtual VcsBaseEditorParameterWidget *createLogEditor(const QString &workingDir,
- const QStringList &files,
- const QStringList &extraOptions);
+
+ typedef std::function<VcsBaseEditorParameterWidget *()> ParameterWidgetCreator;
+ void setDiffParameterWidgetCreator(ParameterWidgetCreator creator);
+ void setLogParameterWidgetCreator(ParameterWidgetCreator creator);
+
virtual StatusItem parseStatusLine(const QString &line) const = 0;
QString vcsEditorTitle(const QString &vcsCmd, const QString &sourceId) const;
@@ -192,13 +193,13 @@ protected:
void resetCachedVcsInfo(const QString &workingDir);
private:
+ void statusParser(const QString&);
+ void annotateRevision(const QString&, const QString&, const QString&, int);
+ void saveSettings();
+ void commandFinishedGotoLine(QWidget*);
+
friend class VcsBaseClientPrivate;
VcsBaseClientPrivate *d;
-
- Q_PRIVATE_SLOT(d, void statusParser(QString))
- Q_PRIVATE_SLOT(d, void annotateRevision(QString,QString,QString,int))
- Q_PRIVATE_SLOT(d, void saveSettings())
- Q_PRIVATE_SLOT(d, void commandFinishedGotoLine(QWidget*))
};
} //namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsbaseeditor.cpp b/src/plugins/vcsbase/vcsbaseeditor.cpp
index bc560431bdf..9b40522e355 100644
--- a/src/plugins/vcsbase/vcsbaseeditor.cpp
+++ b/src/plugins/vcsbase/vcsbaseeditor.cpp
@@ -46,6 +46,7 @@
#include <projectexplorer/session.h>
#include <texteditor/textdocument.h>
#include <texteditor/textdocumentlayout.h>
+#include <utils/progressindicator.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -343,7 +344,7 @@ void ChangeTextCursorHandler::slotCopyRevision()
QAction *ChangeTextCursorHandler::createDescribeAction(const QString &change) const
{
- QAction *a = new QAction(VcsBaseEditorWidget::tr("Describe Change %1").arg(change), 0);
+ auto a = new QAction(VcsBaseEditorWidget::tr("Describe Change %1").arg(change), 0);
connect(a, SIGNAL(triggered()), this, SLOT(slotDescribe()));
return a;
}
@@ -355,7 +356,7 @@ QAction *ChangeTextCursorHandler::createAnnotateAction(const QString &change, bo
previous && !editorWidget()->annotatePreviousRevisionTextFormat().isEmpty() ?
editorWidget()->annotatePreviousRevisionTextFormat() :
editorWidget()->annotateRevisionTextFormat();
- QAction *a = new QAction(format.arg(change), 0);
+ auto a = new QAction(format.arg(change), 0);
a->setData(change);
connect(a, SIGNAL(triggered()), editorWidget(), SLOT(slotAnnotateRevision()));
return a;
@@ -363,7 +364,7 @@ QAction *ChangeTextCursorHandler::createAnnotateAction(const QString &change, bo
QAction *ChangeTextCursorHandler::createCopyRevisionAction(const QString &change) const
{
- QAction *a = new QAction(editorWidget()->copyRevisionTextFormat().arg(change), 0);
+ auto a = new QAction(editorWidget()->copyRevisionTextFormat().arg(change), 0);
a->setData(change);
connect(a, SIGNAL(triggered()), this, SLOT(slotCopyRevision()));
return a;
@@ -495,7 +496,7 @@ void UrlTextCursorHandler::slotOpenUrl()
QAction *UrlTextCursorHandler::createOpenUrlAction(const QString &text) const
{
- QAction *a = new QAction(text, 0);
+ auto a = new QAction(text, 0);
a->setData(m_urlData.url);
connect(a, SIGNAL(triggered()), this, SLOT(slotOpenUrl()));
return a;
@@ -503,7 +504,7 @@ QAction *UrlTextCursorHandler::createOpenUrlAction(const QString &text) const
QAction *UrlTextCursorHandler::createCopyUrlAction(const QString &text) const
{
- QAction *a = new QAction(text, 0);
+ auto a = new QAction(text, 0);
a->setData(m_urlData.url);
connect(a, SIGNAL(triggered()), this, SLOT(slotCopyUrl()));
return a;
@@ -573,6 +574,7 @@ public:
QPointer<VcsCommand> m_command;
QObject *m_describeReceiver;
const char *m_describeSlot;
+ Utils::ProgressIndicator *m_progressIndicator;
private:
QComboBox *m_entriesComboBox;
@@ -589,6 +591,7 @@ VcsBaseEditorWidgetPrivate::VcsBaseEditorWidgetPrivate(VcsBaseEditorWidget *edit
m_mouseDragging(false),
m_describeReceiver(0),
m_describeSlot(0),
+ m_progressIndicator(0),
m_entriesComboBox(0)
{
m_textCursorHandlers.append(new ChangeTextCursorHandler(editorWidget));
@@ -726,7 +729,7 @@ void VcsBaseEditorWidget::init()
break;
}
if (hasDiff()) {
- DiffHighlighter *dh = new DiffHighlighter(d->m_diffFilePattern);
+ auto dh = new DiffHighlighter(d->m_diffFilePattern);
setCodeFoldingSupported(true);
textDocument()->setSyntaxHighlighter(dh);
}
@@ -848,7 +851,7 @@ void VcsBaseEditorWidget::slotPopulateDiffBrowser()
lastFileName = file;
// ignore any headers
d->m_entrySections.push_back(d->m_entrySections.empty() ? 0 : lineNumber);
- entriesComboBox->addItem(QFileInfo(file).fileName());
+ entriesComboBox->addItem(Utils::FileName::fromString(file).fileName());
}
}
}
@@ -1221,7 +1224,7 @@ static QTextCodec *findProjectCodec(const QString &dir)
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->filePath().startsWith(dir)) {
+ if (document->filePath().toString().startsWith(dir)) {
QTextCodec *codec = (*it)->editorConfiguration()->textCodec();
return codec;
}
@@ -1267,7 +1270,7 @@ int VcsBaseEditor::lineNumberOfCurrentEditor(const QString &currentFile)
return -1;
if (!currentFile.isEmpty()) {
const Core::IDocument *idocument = ed->document();
- if (!idocument || idocument->filePath() != currentFile)
+ if (!idocument || idocument->filePath().toString() != currentFile)
return -1;
}
const BaseTextEditor *eda = qobject_cast<const BaseTextEditor *>(ed);
@@ -1315,16 +1318,22 @@ QString VcsBaseEditor::getTitleId(const QString &workingDirectory,
const QStringList &fileNames,
const QString &revision)
{
+ QStringList nonEmptyFileNames;
+ foreach (const QString& fileName, fileNames) {
+ if (!fileName.trimmed().isEmpty())
+ nonEmptyFileNames.append(fileName);
+ }
+
QString rc;
- switch (fileNames.size()) {
+ switch (nonEmptyFileNames.size()) {
case 0:
rc = workingDirectory;
break;
case 1:
- rc = fileNames.front();
+ rc = nonEmptyFileNames.front();
break;
default:
- rc = fileNames.join(QLatin1String(", "));
+ rc = nonEmptyFileNames.join(QLatin1String(", "));
break;
}
if (!revision.isEmpty()) {
@@ -1352,9 +1361,18 @@ VcsBaseEditorParameterWidget *VcsBaseEditorWidget::configurationWidget() const
void VcsBaseEditorWidget::setCommand(VcsCommand *command)
{
- if (d->m_command)
+ if (d->m_command) {
d->m_command->abort();
+ hideProgressIndicator();
+ }
d->m_command = command;
+ if (d->m_command) {
+ d->m_progressIndicator = new Utils::ProgressIndicator(Utils::ProgressIndicator::Large);
+ d->m_progressIndicator->attachToWidget(this);
+ connect(d->m_command.data(), &VcsCommand::finished,
+ this, &VcsBaseEditorWidget::hideProgressIndicator);
+ QTimer::singleShot(100, this, SLOT(showProgressIndicator()));
+ }
}
// Find the complete file from a diff relative specification.
@@ -1439,6 +1457,19 @@ void VcsBaseEditorWidget::slotPaste()
}
}
+void VcsBaseEditorWidget::showProgressIndicator()
+{
+ if (!d->m_progressIndicator) // already stopped and deleted
+ return;
+ d->m_progressIndicator->show();
+}
+
+void VcsBaseEditorWidget::hideProgressIndicator()
+{
+ delete d->m_progressIndicator;
+ d->m_progressIndicator = 0;
+}
+
bool VcsBaseEditorWidget::canApplyDiffChunk(const DiffChunk &dc) const
{
if (!dc.isValid())
diff --git a/src/plugins/vcsbase/vcsbaseeditor.h b/src/plugins/vcsbase/vcsbaseeditor.h
index c43de908d54..1f17da7c139 100644
--- a/src/plugins/vcsbase/vcsbaseeditor.h
+++ b/src/plugins/vcsbase/vcsbaseeditor.h
@@ -242,6 +242,8 @@ private slots:
void slotAnnotateRevision();
void slotApplyDiffChunk();
void slotPaste();
+ void showProgressIndicator();
+ void hideProgressIndicator();
protected:
/* A helper that can be used to locate a file in a diff in case it
diff --git a/src/plugins/vcsbase/vcsbaseeditorparameterwidget.cpp b/src/plugins/vcsbase/vcsbaseeditorparameterwidget.cpp
index 587c2ba5240..35a58464ff1 100644
--- a/src/plugins/vcsbase/vcsbaseeditorparameterwidget.cpp
+++ b/src/plugins/vcsbase/vcsbaseeditorparameterwidget.cpp
@@ -119,7 +119,8 @@ VcsBaseEditorParameterWidget::VcsBaseEditorParameterWidget(QWidget *parent) :
d->m_layout = new QHBoxLayout(this);
d->m_layout->setContentsMargins(3, 0, 3, 0);
d->m_layout->setSpacing(2);
- connect(this, SIGNAL(argumentsChanged()), this, SLOT(handleArgumentsChanged()));
+ connect(this, &VcsBaseEditorParameterWidget::argumentsChanged,
+ this, &VcsBaseEditorParameterWidget::handleArgumentsChanged);
}
VcsBaseEditorParameterWidget::~VcsBaseEditorParameterWidget()
@@ -155,11 +156,11 @@ QToolButton *VcsBaseEditorParameterWidget::addToggleButton(const QString &option
QToolButton *VcsBaseEditorParameterWidget::addToggleButton(const QStringList &options, const QString &label, const QString &tooltip)
{
- QToolButton *tb = new QToolButton;
+ auto tb = new QToolButton;
tb->setText(label);
tb->setToolTip(tooltip);
tb->setCheckable(true);
- connect(tb, SIGNAL(toggled(bool)), this, SIGNAL(argumentsChanged()));
+ connect(tb, &QToolButton::toggled, this, &VcsBaseEditorParameterWidget::argumentsChanged);
d->m_layout->addWidget(tb);
d->m_optionMappings.append(OptionMapping(options, tb));
return tb;
@@ -168,10 +169,11 @@ QToolButton *VcsBaseEditorParameterWidget::addToggleButton(const QStringList &op
QComboBox *VcsBaseEditorParameterWidget::addComboBox(const QStringList &options,
const QList<ComboBoxItem> &items)
{
- QComboBox *cb = new QComboBox;
+ auto cb = new QComboBox;
foreach (const ComboBoxItem &item, items)
cb->addItem(item.displayText, item.value);
- connect(cb, SIGNAL(currentIndexChanged(int)), this, SIGNAL(argumentsChanged()));
+ connect(cb, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
+ this, &VcsBaseEditorParameterWidget::argumentsChanged);
d->m_layout->addWidget(cb);
d->m_optionMappings.append(OptionMapping(options, cb));
return cb;
@@ -218,16 +220,17 @@ void VcsBaseEditorParameterWidget::mapSetting(QComboBox *comboBox, int *setting)
comboBox->blockSignals(false);
}
-void VcsBaseEditorParameterWidget::executeCommand()
-{
-}
-
void VcsBaseEditorParameterWidget::handleArgumentsChanged()
{
updateMappedSettings();
executeCommand();
}
+void VcsBaseEditorParameterWidget::executeCommand()
+{
+ emit commandExecutionRequested();
+}
+
VcsBaseEditorParameterWidget::OptionMapping::OptionMapping() :
widget(0)
{
diff --git a/src/plugins/vcsbase/vcsbaseeditorparameterwidget.h b/src/plugins/vcsbase/vcsbaseeditorparameterwidget.h
index df179370a81..6f560acab23 100644
--- a/src/plugins/vcsbase/vcsbaseeditorparameterwidget.h
+++ b/src/plugins/vcsbase/vcsbaseeditorparameterwidget.h
@@ -80,10 +80,12 @@ public:
virtual QStringList arguments() const;
public slots:
- virtual void executeCommand();
- virtual void handleArgumentsChanged();
+ void handleArgumentsChanged();
+ void executeCommand();
signals:
+ void commandExecutionRequested();
+
// Trigger a re-run to show changed output according to new argument list.
void argumentsChanged();
diff --git a/src/plugins/vcsbase/vcsbaseplugin.cpp b/src/plugins/vcsbase/vcsbaseplugin.cpp
index 33fa11c859b..ce0bc1bc1bb 100644
--- a/src/plugins/vcsbase/vcsbaseplugin.cpp
+++ b/src/plugins/vcsbase/vcsbaseplugin.cpp
@@ -42,7 +42,7 @@
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/vcsmanager.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <projectexplorer/session.h>
#include <utils/qtcassert.h>
@@ -60,7 +60,9 @@
#include <QMessageBox>
#include <QFileDialog>
+using namespace Core;
using namespace Utils;
+using namespace ProjectExplorer;
enum { debug = 0, debugRepositorySearch = 0 };
@@ -201,27 +203,28 @@ public:
static QString windowTitleVcsTopic(const QString &filePath);
signals:
- void stateChanged(const VcsBase::Internal::State &s, Core::IVersionControl *vc);
+ void stateChanged(const VcsBase::Internal::State &s, IVersionControl *vc);
public slots:
void slotStateChanged();
};
-StateListener::StateListener(QObject *parent) :
- QObject(parent)
+StateListener::StateListener(QObject *parent) : QObject(parent)
{
- connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
- this, SLOT(slotStateChanged()));
- connect(Core::EditorManager::instance(), SIGNAL(currentDocumentStateChanged()),
- this, SLOT(slotStateChanged()));
- connect(Core::VcsManager::instance(), SIGNAL(repositoryChanged(QString)),
- this, SLOT(slotStateChanged()));
+ connect(EditorManager::instance(), &EditorManager::currentEditorChanged,
+ this, &StateListener::slotStateChanged);
+ connect(EditorManager::instance(), &EditorManager::currentDocumentStateChanged,
+ this, &StateListener::slotStateChanged);
+ connect(VcsManager::instance(), &VcsManager::repositoryChanged,
+ this, &StateListener::slotStateChanged);
- connect(ProjectExplorer::ProjectExplorerPlugin::instance(),
- SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
- this, SLOT(slotStateChanged()));
+ connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged,
+ this, &StateListener::slotStateChanged);
+ connect(SessionManager::instance(), &SessionManager::startupProjectChanged,
+ this, &StateListener::slotStateChanged);
- Core::EditorManager::setWindowTitleVcsTopicHandler(&StateListener::windowTitleVcsTopic);
+
+ EditorManager::setWindowTitleVcsTopicHandler(&StateListener::windowTitleVcsTopic);
}
QString StateListener::windowTitleVcsTopic(const QString &filePath)
@@ -231,21 +234,21 @@ QString StateListener::windowTitleVcsTopic(const QString &filePath)
searchPath = QFileInfo(filePath).absolutePath();
} else {
// use single project's information if there is only one loaded.
- const QList<ProjectExplorer::Project *> projects = ProjectExplorer::SessionManager::projects();
+ const QList<Project *> projects = SessionManager::projects();
if (projects.size() == 1)
searchPath = projects.first()->projectDirectory().toString();
}
if (searchPath.isEmpty())
return QString();
QString topLevelPath;
- Core::IVersionControl *vc = Core::VcsManager::findVersionControlForDirectory(
+ IVersionControl *vc = VcsManager::findVersionControlForDirectory(
searchPath, &topLevelPath);
return (vc && !topLevelPath.isEmpty()) ? vc->vcsTopic(topLevelPath) : QString();
}
static inline QString displayNameOfEditor(const QString &fileName)
{
- Core::IDocument *document = Core::DocumentModel::documentForFilePath(fileName);
+ IDocument *document = DocumentModel::documentForFilePath(fileName);
if (document)
return document->displayName();
return QString();
@@ -257,11 +260,11 @@ void StateListener::slotStateChanged()
// temporary path prefix or does the file contains a hash, indicating a project
// folder?
State state;
- Core::IDocument *currentDocument = Core::EditorManager::currentDocument();
+ IDocument *currentDocument = EditorManager::currentDocument();
if (!currentDocument) {
state.currentFile.clear();
} else {
- state.currentFile = currentDocument->filePath();
+ state.currentFile = currentDocument->filePath().toString();
if (state.currentFile.isEmpty() || currentDocument->isTemporary())
state.currentFile = VcsBasePlugin::source(currentDocument);
}
@@ -289,7 +292,7 @@ void StateListener::slotStateChanged()
}
// Get the file and its control. Do not use the file unless we find one
- Core::IVersionControl *fileControl = 0;
+ IVersionControl *fileControl = 0;
if (!state.currentFile.isEmpty()) {
if (currentFileInfo.isNull())
currentFileInfo.reset(new QFileInfo(state.currentFile));
@@ -300,18 +303,21 @@ void StateListener::slotStateChanged()
state.currentFileDirectory = currentFileInfo->absolutePath();
state.currentFileName = currentFileInfo->fileName();
}
- fileControl = Core::VcsManager::findVersionControlForDirectory(
+ fileControl = 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()) {
+ IVersionControl *projectControl = 0;
+ Project *currentProject = ProjectTree::currentProject();
+ if (!currentProject)
+ currentProject = SessionManager::startupProject();
+ if (currentProject) {
state.currentProjectPath = currentProject->projectDirectory().toString();
state.currentProjectName = currentProject->displayName();
- projectControl = Core::VcsManager::findVersionControlForDirectory(state.currentProjectPath,
+ projectControl = VcsManager::findVersionControlForDirectory(state.currentProjectPath,
&state.currentProjectTopLevel);
if (projectControl) {
// If we have both, let the file's one take preference
@@ -322,14 +328,14 @@ void StateListener::slotStateChanged()
}
}
// Assemble state and emit signal.
- Core::IVersionControl *vc = fileControl;
+ IVersionControl *vc = fileControl;
if (!vc)
vc = projectControl;
if (!vc)
state.clearPatchFile(); // Need a repository to patch
if (debug)
qDebug() << state << (vc ? vc->displayName() : QLatin1String("No version control"));
- Core::EditorManager::updateWindowTitles();
+ EditorManager::updateWindowTitles();
emit stateChanged(state, vc);
}
@@ -528,8 +534,8 @@ public:
inline bool supportsRepositoryCreation() const;
QPointer<VcsBaseSubmitEditor> m_submitEditor;
- Core::IVersionControl *m_versionControl;
- Core::Context m_context;
+ IVersionControl *m_versionControl;
+ Context m_context;
VcsBasePluginState m_state;
int m_actionState;
@@ -544,7 +550,7 @@ VcsBasePluginPrivate::VcsBasePluginPrivate() :
bool VcsBasePluginPrivate::supportsRepositoryCreation() const
{
- return m_versionControl && m_versionControl->supportsOperation(Core::IVersionControl::CreateRepositoryOperation);
+ return m_versionControl && m_versionControl->supportsOperation(IVersionControl::CreateRepositoryOperation);
}
Internal::StateListener *VcsBasePluginPrivate::m_listener = 0;
@@ -559,27 +565,25 @@ VcsBasePlugin::~VcsBasePlugin()
delete d;
}
-void VcsBasePlugin::initializeVcs(Core::IVersionControl *vc, const Core::Context &context)
+void VcsBasePlugin::initializeVcs(IVersionControl *vc, const Context &context)
{
d->m_versionControl = vc;
d->m_context = context;
addAutoReleasedObject(vc);
Internal::VcsPlugin *plugin = Internal::VcsPlugin::instance();
- connect(plugin->coreListener(), SIGNAL(submitEditorAboutToClose(VcsBaseSubmitEditor*,bool*)),
- this, SLOT(slotSubmitEditorAboutToClose(VcsBaseSubmitEditor*,bool*)));
+ connect(plugin->coreListener(), &Internal::CoreListener::submitEditorAboutToClose,
+ this, &VcsBasePlugin::slotSubmitEditorAboutToClose);
// First time: create new listener
if (!VcsBasePluginPrivate::m_listener)
VcsBasePluginPrivate::m_listener = new Internal::StateListener(plugin);
- connect(VcsBasePluginPrivate::m_listener,
- SIGNAL(stateChanged(VcsBase::Internal::State,Core::IVersionControl*)),
- this,
- SLOT(slotStateChanged(VcsBase::Internal::State,Core::IVersionControl*)));
+ connect(VcsBasePluginPrivate::m_listener, &Internal::StateListener::stateChanged,
+ this, &VcsBasePlugin::slotStateChanged);
// VCSes might have become (un-)available, so clear the VCS directory cache
- connect(vc, SIGNAL(configurationChanged()),
- Core::VcsManager::instance(), SLOT(clearVersionControlCache()));
- connect(vc, SIGNAL(configurationChanged()),
- VcsBasePluginPrivate::m_listener, SLOT(slotStateChanged()));
+ connect(vc, &IVersionControl::configurationChanged,
+ VcsManager::instance(), &VcsManager::clearVersionControlCache);
+ connect(vc, &IVersionControl::configurationChanged,
+ VcsBasePluginPrivate::m_listener, &Internal::StateListener::slotStateChanged);
}
void VcsBasePlugin::extensionsInitialized()
@@ -599,19 +603,19 @@ void VcsBasePlugin::slotSubmitEditorAboutToClose(VcsBaseSubmitEditor *submitEdit
*result = submitEditorAboutToClose();
}
-Core::IVersionControl *VcsBasePlugin::versionControl() const
+IVersionControl *VcsBasePlugin::versionControl() const
{
return d->m_versionControl;
}
-void VcsBasePlugin::slotStateChanged(const VcsBase::Internal::State &newInternalState, Core::IVersionControl *vc)
+void VcsBasePlugin::slotStateChanged(const VcsBase::Internal::State &newInternalState, IVersionControl *vc)
{
if (vc == d->m_versionControl) {
// We are directly affected: Change state
if (!d->m_state.equals(newInternalState)) {
d->m_state.setState(newInternalState);
updateActions(VcsEnabled);
- Core::ICore::addAdditionalContext(d->m_context);
+ ICore::addAdditionalContext(d->m_context);
}
} else {
// Some other VCS plugin or state changed: Reset us to empty state.
@@ -622,7 +626,7 @@ void VcsBasePlugin::slotStateChanged(const VcsBase::Internal::State &newInternal
d->m_state = emptyState;
updateActions(newActionState);
}
- Core::ICore::removeAdditionalContext(d->m_context);
+ ICore::removeAdditionalContext(d->m_context);
}
}
@@ -657,9 +661,9 @@ void VcsBasePlugin::promptToDeleteCurrentFile()
{
const VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasFile(), return);
- const bool rc = Core::VcsManager::promptToDelete(versionControl(), state.currentFile());
+ const bool rc = VcsManager::promptToDelete(versionControl(), state.currentFile());
if (!rc)
- QMessageBox::warning(Core::ICore::dialogParent(), tr("Version Control"),
+ QMessageBox::warning(ICore::dialogParent(), tr("Version Control"),
tr("The file \"%1\" could not be deleted.").
arg(QDir::toNativeSeparators(state.currentFile())),
QMessageBox::Ok);
@@ -674,18 +678,18 @@ static inline bool ask(QWidget *parent, const QString &title, const QString &que
void VcsBasePlugin::createRepository()
{
- QTC_ASSERT(d->m_versionControl->supportsOperation(Core::IVersionControl::CreateRepositoryOperation), return);
+ QTC_ASSERT(d->m_versionControl->supportsOperation(IVersionControl::CreateRepositoryOperation), return);
// Find current starting directory
QString directory;
- if (const ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject())
- directory = QFileInfo(currentProject->document()->filePath()).absolutePath();
+ if (const Project *currentProject = ProjectTree::currentProject())
+ directory = currentProject->document()->filePath().toFileInfo().absolutePath();
// Prompt for a directory that is not under version control yet
- QWidget *mw = Core::ICore::mainWindow();
+ QWidget *mw = ICore::mainWindow();
do {
directory = QFileDialog::getExistingDirectory(mw, tr("Choose Repository Directory"), directory);
if (directory.isEmpty())
return;
- const Core::IVersionControl *managingControl = Core::VcsManager::findVersionControlForDirectory(directory);
+ const IVersionControl *managingControl = VcsManager::findVersionControlForDirectory(directory);
if (managingControl == 0)
break;
const QString question = tr("The directory \"%1\" is already managed by a version control system (%2)."
@@ -722,7 +726,7 @@ bool VcsBasePlugin::raiseSubmitEditor() const
{
if (!d->m_submitEditor)
return false;
- Core::EditorManager::activateEditor(d->m_submitEditor, Core::EditorManager::IgnoreNavigationHistory);
+ EditorManager::activateEditor(d->m_submitEditor, EditorManager::IgnoreNavigationHistory);
return true;
}
@@ -773,13 +777,13 @@ bool VcsBasePlugin::isSshPromptConfigured()
static const char SOURCE_PROPERTY[] = "qtcreator_source";
-void VcsBasePlugin::setSource(Core::IDocument *document, const QString &source)
+void VcsBasePlugin::setSource(IDocument *document, const QString &source)
{
document->setProperty(SOURCE_PROPERTY, source);
VcsBasePluginPrivate::m_listener->slotStateChanged();
}
-QString VcsBasePlugin::source(Core::IDocument *document)
+QString VcsBasePlugin::source(IDocument *document)
{
return document->property(SOURCE_PROPERTY).toString();
}
@@ -797,7 +801,7 @@ void VcsBasePlugin::setProcessEnvironment(QProcessEnvironment *e,
// Run a process synchronously, returning Utils::SynchronousProcessResponse
// response struct and using the VcsBasePlugin flags as applicable
SynchronousProcessResponse VcsBasePlugin::runVcs(const QString &workingDir,
- const Utils::FileName &binary,
+ const FileName &binary,
const QStringList &arguments,
int timeOutMS,
unsigned flags,
diff --git a/src/plugins/vcsbase/vcsbaseplugin.h b/src/plugins/vcsbase/vcsbaseplugin.h
index 0f99d8143dd..10dbea73d08 100644
--- a/src/plugins/vcsbase/vcsbaseplugin.h
+++ b/src/plugins/vcsbase/vcsbaseplugin.h
@@ -133,10 +133,10 @@ protected:
explicit VcsBasePlugin();
void initializeVcs(Core::IVersionControl *vc, const Core::Context &context);
- virtual void extensionsInitialized();
+ void extensionsInitialized();
public:
- virtual ~VcsBasePlugin();
+ ~VcsBasePlugin();
const VcsBasePluginState &currentState() const;
Core::IVersionControl *versionControl() const;
diff --git a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
index 612b70e7e55..98b0e3e5789 100644
--- a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
+++ b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
@@ -51,7 +51,7 @@
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <QDebug>
@@ -171,7 +171,7 @@ VcsBaseSubmitEditorPrivate::VcsBaseSubmitEditorPrivate(const VcsBaseSubmitEditor
m_file(new SubmitEditorFile(parameters, q)),
m_nickNameDialog(0)
{
- QCompleter *completer = new QCompleter(q);
+ auto completer = new QCompleter(q);
completer->setCaseSensitivity(Qt::CaseSensitive);
completer->setModelSorting(QCompleter::CaseSensitivelySortedModel);
m_widget->descriptionEdit()->setCompleter(completer);
@@ -186,7 +186,7 @@ VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *pa
document()->setDisplayName(QCoreApplication::translate("VCS", d->m_parameters->displayName));
// Message font according to settings
- Utils::CompletingTextEdit *descriptionEdit = editorWidget->descriptionEdit();
+ CompletingTextEdit *descriptionEdit = editorWidget->descriptionEdit();
const TextEditor::FontSettings fs = TextEditor::TextEditorSettings::fontSettings();
const QTextCharFormat tf = fs.toTextCharFormat(TextEditor::C_TEXT);
descriptionEdit->setFont(tf.font());
@@ -209,18 +209,18 @@ VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *pa
const CommonVcsSettings settings = VcsPlugin::instance()->settings();
// Add additional context menu settings
if (!settings.submitMessageCheckScript.isEmpty() || !settings.nickNameMailMap.isEmpty()) {
- QAction *sep = new QAction(this);
+ auto sep = new QAction(this);
sep->setSeparator(true);
d->m_widget->addDescriptionEditContextMenuAction(sep);
// Run check action
if (!settings.submitMessageCheckScript.isEmpty()) {
- QAction *checkAction = new QAction(tr("Check Message"), this);
+ auto checkAction = new QAction(tr("Check Message"), this);
connect(checkAction, SIGNAL(triggered()), this, SLOT(slotCheckSubmitMessage()));
d->m_widget->addDescriptionEditContextMenuAction(checkAction);
}
// Insert nick
if (!settings.nickNameMailMap.isEmpty()) {
- QAction *insertAction = new QAction(tr("Insert Name..."), this);
+ auto insertAction = new QAction(tr("Insert Name..."), this);
connect(insertAction, SIGNAL(triggered()), this, SLOT(slotInsertNickName()));
d->m_widget->addDescriptionEditContextMenuAction(insertAction);
}
@@ -240,7 +240,7 @@ VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *pa
connect(Core::ICore::mainWindow(), SIGNAL(windowActivated()),
this, SLOT(slotRefreshCommitData()), Qt::QueuedConnection);
- Aggregation::Aggregate *aggregate = new Aggregation::Aggregate;
+ auto aggregate = new Aggregation::Aggregate;
aggregate->add(new Core::BaseTextFind(descriptionEdit));
aggregate->add(this);
}
@@ -279,7 +279,7 @@ static inline QStringList fieldTexts(const QString &fileContents)
void VcsBaseSubmitEditor::createUserFields(const QString &fieldConfigFile)
{
- Utils::FileReader reader;
+ FileReader reader;
if (!reader.fetch(fieldConfigFile, QIODevice::Text, Core::ICore::mainWindow()))
return;
// Parse into fields
@@ -288,9 +288,9 @@ void VcsBaseSubmitEditor::createUserFields(const QString &fieldConfigFile)
return;
// Create a completer on user names
const QStandardItemModel *nickNameModel = VcsPlugin::instance()->nickNameModel();
- QCompleter *completer = new QCompleter(NickNameDialog::nickNameList(nickNameModel), this);
+ auto completer = new QCompleter(NickNameDialog::nickNameList(nickNameModel), this);
- SubmitFieldWidget *fieldWidget = new SubmitFieldWidget;
+ auto fieldWidget = new SubmitFieldWidget;
connect(fieldWidget, SIGNAL(browseButtonClicked(int,QString)),
this, SLOT(slotSetFieldNickName(int)));
fieldWidget->setCompleter(completer);
@@ -364,7 +364,7 @@ bool VcsBaseSubmitEditor::open(QString *errorString, const QString &fileName, co
if (fileName.isEmpty())
return false;
- Utils::FileReader reader;
+ FileReader reader;
if (!reader.fetch(realFileName, QIODevice::Text, errorString))
return false;
@@ -372,7 +372,7 @@ bool VcsBaseSubmitEditor::open(QString *errorString, const QString &fileName, co
if (!setFileContents(text.toUtf8()))
return false;
- d->m_file->setFilePath(QFileInfo(fileName).absoluteFilePath());
+ d->m_file->setFilePath(FileName::fromString(fileName));
d->m_file->setModified(fileName != realFileName);
return true;
}
@@ -395,7 +395,7 @@ void VcsBaseSubmitEditor::setCheckScriptWorkingDirectory(const QString &s)
static QToolBar *createToolBar(const QWidget *someWidget, QAction *submitAction, QAction *diffAction)
{
// Create
- QToolBar *toolBar = new QToolBar;
+ auto toolBar = new QToolBar;
toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
const int size = someWidget->style()->pixelMetric(QStyle::PM_SmallIconSize);
toolBar->setIconSize(QSize(size, size));
@@ -565,12 +565,12 @@ VcsBaseSubmitEditor::PromptSubmitResult
// Provide check box to turn off prompt ONLY if it was not forced
if (*promptSetting && !forcePrompt) {
const QDialogButtonBox::StandardButton danswer =
- Utils::CheckableMessageBox::question(parent, title, question,
+ CheckableMessageBox::question(parent, title, question,
tr("Prompt to submit"), promptSetting,
QDialogButtonBox::Yes|QDialogButtonBox::No|
QDialogButtonBox::Cancel,
QDialogButtonBox::Yes);
- answer = Utils::CheckableMessageBox::dialogButtonBoxToMessageBoxButton(danswer);
+ answer = CheckableMessageBox::dialogButtonBoxToMessageBoxButton(danswer);
} else {
answer = QMessageBox::question(parent, title, question,
QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel,
@@ -674,15 +674,17 @@ bool VcsBaseSubmitEditor::runSubmitMessageCheckScript(const QString &checkScript
{
// Write out message
QString tempFilePattern = QDir::tempPath();
- if (!tempFilePattern.endsWith(QDir::separator()))
- tempFilePattern += QDir::separator();
+ const QChar slash = QLatin1Char('/');
+ if (!tempFilePattern.endsWith(slash))
+ tempFilePattern += slash;
tempFilePattern += QLatin1String("msgXXXXXX.txt");
TempFileSaver saver(tempFilePattern);
saver.write(fileContents());
if (!saver.finalize(errorMessage))
return false;
// Run check process
- VcsOutputWindow::appendCommand(msgCheckScript(d->m_checkScriptWorkingDirectory, checkScript));
+ VcsOutputWindow::appendShellCommandLine(msgCheckScript(d->m_checkScriptWorkingDirectory,
+ checkScript));
QProcess checkProcess;
if (!d->m_checkScriptWorkingDirectory.isEmpty())
checkProcess.setWorkingDirectory(d->m_checkScriptWorkingDirectory);
@@ -739,7 +741,7 @@ QStringList VcsBaseSubmitEditor::currentProjectFiles(bool nativeSeparators, QStr
if (name)
name->clear();
- if (const ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectExplorerPlugin::currentProject()) {
+ if (const ProjectExplorer::Project *currentProject = ProjectExplorer::ProjectTree::currentProject()) {
QStringList files = currentProject->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
if (name)
*name = currentProject->displayName();
diff --git a/src/plugins/vcsbase/vcscommand.cpp b/src/plugins/vcsbase/vcscommand.cpp
index 533c4d390ca..0cc6bbc6fbe 100644
--- a/src/plugins/vcsbase/vcscommand.cpp
+++ b/src/plugins/vcsbase/vcscommand.cpp
@@ -155,8 +155,8 @@ VcsCommand::VcsCommand(const Utils::FileName &binary,
const QProcessEnvironment &environment) :
d(new Internal::VcsCommandPrivate(binary, workingDirectory, environment))
{
- connect(Core::ICore::instance(), SIGNAL(coreAboutToClose()),
- this, SLOT(coreAboutToClose()));
+ connect(Core::ICore::instance(), &Core::ICore::coreAboutToClose,
+ this, &VcsCommand::coreAboutToClose);
}
VcsCommand::~VcsCommand()
@@ -220,7 +220,7 @@ void VcsCommand::execute()
// For some reason QtConcurrent::run() only works on this
QFuture<void> task = QtConcurrent::run(&VcsCommand::run, this);
d->m_watcher.setFuture(task);
- connect(&d->m_watcher, SIGNAL(canceled()), this, SLOT(cancel()));
+ connect(&d->m_watcher, &QFutureWatcher<void>::canceled, this, &VcsCommand::cancel);
QString binary = d->m_binaryPath.toFileInfo().baseName();
if (!binary.isEmpty())
binary = binary.replace(0, 1, binary[0].toUpper()); // Upper the first letter
@@ -315,12 +315,12 @@ public:
// 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)
VcsOutputWindow *outputWindow = VcsOutputWindow::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,Utils::FileName,QStringList)),
- outputWindow, SLOT(appendCommand(QString,Utils::FileName,QStringList)));
- connect(this, SIGNAL(appendMessage(QString)), outputWindow, SLOT(appendMessage(QString)));
+ connect(this, &OutputProxy::append,
+ outputWindow, [](const QString &txt) { VcsOutputWindow::append(txt); });
+ connect(this, &OutputProxy::appendSilently, outputWindow, &VcsOutputWindow::appendSilently);
+ connect(this, &OutputProxy::appendError, outputWindow, &VcsOutputWindow::appendError);
+ connect(this, &OutputProxy::appendCommand, outputWindow, &VcsOutputWindow::appendCommand);
+ connect(this, &OutputProxy::appendMessage, outputWindow, &VcsOutputWindow::appendMessage);
}
signals:
@@ -382,7 +382,7 @@ Utils::SynchronousProcessResponse VcsCommand::runVcs(const QStringList &argument
} else {
Utils::SynchronousProcess process;
process.setExitCodeInterpreter(interpreter);
- connect(this, SIGNAL(terminate()), &process, SLOT(terminate()));
+ connect(this, &VcsCommand::terminate, &process, &Utils::SynchronousProcess::terminate);
if (!d->m_workingDirectory.isEmpty())
process.setWorkingDirectory(d->m_workingDirectory);
@@ -405,15 +405,16 @@ Utils::SynchronousProcessResponse VcsCommand::runVcs(const QStringList &argument
} else if (d->m_progressiveOutput
|| !(d->m_flags & VcsBasePlugin::SuppressStdErrInLogWindow)) {
process.setStdErrBufferedSignalsEnabled(true);
- connect(&process, SIGNAL(stdErrBuffered(QString,bool)),
- this, SLOT(bufferedError(QString)));
+ connect(&process, &Utils::SynchronousProcess::stdErrBuffered,
+ this, &VcsCommand::bufferedError);
}
// 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)));
+ connect(&process, &Utils::SynchronousProcess::stdOutBuffered,
+ this, &VcsCommand::bufferedOutput);
}
process.setTimeOutMessageBoxEnabled(true);
diff --git a/src/plugins/vcsbase/vcsconfigurationpage.cpp b/src/plugins/vcsbase/vcsconfigurationpage.cpp
deleted file mode 100644
index 33aa54068a3..00000000000
--- a/src/plugins/vcsbase/vcsconfigurationpage.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "vcsconfigurationpage.h"
-
-#include "vcsbaseconstants.h"
-
-#include <coreplugin/icore.h>
-#include <coreplugin/iversioncontrol.h>
-
-#include <utils/qtcassert.h>
-
-#include <QPushButton>
-#include <QVBoxLayout>
-#include <QWizardPage>
-
-namespace VcsBase {
-namespace Internal {
-
-class VcsConfigurationPagePrivate
-{
-public:
- const Core::IVersionControl *m_versionControl;
- QPushButton *m_configureButton;
-};
-
-} // namespace Internal
-
-VcsConfigurationPage::VcsConfigurationPage(const Core::IVersionControl *vc, QWidget *parent) :
- QWizardPage(parent),
- d(new Internal::VcsConfigurationPagePrivate)
-{
- QTC_ASSERT(vc, return);
- setTitle(tr("Configuration"));
- setSubTitle(tr("Please configure <b>%1</b> now.").arg(vc->displayName()));
-
- d->m_versionControl = vc;
- d->m_configureButton = new QPushButton(Core::ICore::msgShowOptionsDialog(), this);
-
- QVBoxLayout *verticalLayout = new QVBoxLayout(this);
- verticalLayout->addWidget(d->m_configureButton);
-
- connect(d->m_versionControl, SIGNAL(configurationChanged()), SIGNAL(completeChanged()));
- connect(d->m_configureButton, SIGNAL(clicked()), SLOT(openConfiguration()));
-}
-
-VcsConfigurationPage::~VcsConfigurationPage()
-{
- delete d;
-}
-
-bool VcsConfigurationPage::isComplete() const
-{
- return d->m_versionControl->isConfigured();
-}
-
-void VcsConfigurationPage::openConfiguration()
-{
- Core::ICore::showOptionsDialog(Constants::VCS_SETTINGS_CATEGORY,
- d->m_versionControl->id(),
- this);
-}
-
-} // namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsoutputwindow.cpp b/src/plugins/vcsbase/vcsoutputwindow.cpp
index c4f81bb9bcd..0d81ec3c4ee 100644
--- a/src/plugins/vcsbase/vcsoutputwindow.cpp
+++ b/src/plugins/vcsbase/vcsoutputwindow.cpp
@@ -441,9 +441,13 @@ static inline QString formatArguments(const QStringList &args)
const int size = args.size();
// Skip authentication options
for (int i = 0; i < size; i++) {
- const QString &arg = args.at(i);
+ const QString arg = filterPasswordFromUrls(args.at(i));
if (i)
str << ' ';
+ if (arg.startsWith(QString::fromLatin1(passwordOptionC) + QLatin1Char('='))) {
+ str << "--password=********";
+ continue;
+ }
str << arg;
if (arg == QLatin1String(passwordOptionC)) {
str << " ********";
@@ -465,16 +469,16 @@ QString VcsOutputWindow::msgExecutionLogEntry(const QString &workingDir,
arg(QDir::toNativeSeparators(workingDir), nativeExecutable, args) + QLatin1Char('\n');
}
-void VcsOutputWindow::appendCommand(const QString &text)
+void VcsOutputWindow::appendShellCommandLine(const QString &text)
{
append(filterPasswordFromUrls(text), Command, true);
}
void VcsOutputWindow::appendCommand(const QString &workingDirectory,
- const Utils::FileName &binary,
- const QStringList &args)
+ const Utils::FileName &binary,
+ const QStringList &args)
{
- appendCommand(msgExecutionLogEntry(workingDirectory, binary, args));
+ appendShellCommandLine(msgExecutionLogEntry(workingDirectory, binary, args));
}
void VcsOutputWindow::appendMessage(const QString &text)
diff --git a/src/plugins/vcsbase/vcsoutputwindow.h b/src/plugins/vcsbase/vcsoutputwindow.h
index 4020f088f5f..9ed45c6ae64 100644
--- a/src/plugins/vcsbase/vcsoutputwindow.h
+++ b/src/plugins/vcsbase/vcsoutputwindow.h
@@ -109,7 +109,9 @@ public slots:
// Append a command, prepended by a log time stamp. "Executing: vcs -diff"
// will result in "10:00 Executing: vcs -diff" in bold
- static void appendCommand(const QString &text);
+ // Filter passwords from URLs while doing this.
+ static void appendShellCommandLine(const QString &text);
+
// Append a standard-formatted entry for command execution
// (see msgExecutionLogEntry).
static void appendCommand(const QString &workingDirectory,
diff --git a/src/plugins/vcsbase/vcsplugin.cpp b/src/plugins/vcsbase/vcsplugin.cpp
index d1042d41a81..645a6d2702a 100644
--- a/src/plugins/vcsbase/vcsplugin.cpp
+++ b/src/plugins/vcsbase/vcsplugin.cpp
@@ -36,13 +36,17 @@
#include "nicknamedialog.h"
#include "vcsoutputwindow.h"
#include "corelistener.h"
+#include "wizard/vcsconfigurationpage.h"
+#include "wizard/vcsjsextension.h"
#include <coreplugin/iversioncontrol.h>
+#include <coreplugin/jsexpander.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/vcsmanager.h>
+#include <projectexplorer/jsonwizard/jsonwizardfactory.h>
#include <projectexplorer/project.h>
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projecttree.h>
#include <utils/macroexpander.h>
@@ -74,7 +78,7 @@ bool VcsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
{
Q_UNUSED(arguments)
- if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/vcsbase/VcsBase.mimetypes.xml"), errorMessage))
+ if (!MimeDatabase::addMimeTypes(QLatin1String(":/vcsbase/VcsBase.mimetypes.xml"), errorMessage))
return false;
m_coreListener = new CoreListener;
@@ -89,12 +93,16 @@ bool VcsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
this, SLOT(slotSettingsChanged()));
slotSettingsChanged();
+ JsonWizardFactory::registerPageFactory(new Internal::VcsConfigurationPageFactory);
+
+ JsExpander::registerQObjectForJs(QLatin1String("Vcs"), new VcsJsExtension);
+
Utils::MacroExpander *expander = Utils::globalMacroExpander();
expander->registerVariable(Constants::VAR_VCS_NAME,
tr("Name of the version control system in use by the current project."),
[]() -> QString {
IVersionControl *vc = 0;
- if (Project *project = ProjectExplorerPlugin::currentProject())
+ if (Project *project = ProjectTree::currentProject())
vc = VcsManager::findVersionControlForDirectory(project->projectDirectory().toString());
return vc ? vc->displayName() : QString();
});
@@ -104,7 +112,7 @@ bool VcsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
[]() -> QString {
IVersionControl *vc = 0;
QString topLevel;
- if (Project *project = ProjectExplorerPlugin::currentProject())
+ if (Project *project = ProjectTree::currentProject())
vc = VcsManager::findVersionControlForDirectory(project->projectDirectory().toString(), &topLevel);
return vc ? vc->vcsTopic(topLevel) : QString();
});
@@ -112,7 +120,7 @@ bool VcsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
expander->registerVariable(Constants::VAR_VCS_TOPLEVELPATH,
tr("The top level path to the repository the current project is in."),
[]() -> QString {
- if (Project *project = ProjectExplorerPlugin::currentProject())
+ if (Project *project = ProjectTree::currentProject())
return VcsManager::findTopLevelForDirectory(project->projectDirectory().toString());
return QString();
});
diff --git a/src/plugins/vcsbase/wizard/vcsconfigurationpage.cpp b/src/plugins/vcsbase/wizard/vcsconfigurationpage.cpp
new file mode 100644
index 00000000000..62639eb73ff
--- /dev/null
+++ b/src/plugins/vcsbase/wizard/vcsconfigurationpage.cpp
@@ -0,0 +1,180 @@
+/****************************************************************************
+**
+** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "vcsconfigurationpage.h"
+
+#include "../vcsbaseconstants.h"
+
+#include <coreplugin/icore.h>
+#include <coreplugin/iversioncontrol.h>
+#include <coreplugin/vcsmanager.h>
+#include <projectexplorer/jsonwizard/jsonwizard.h>
+#include <projectexplorer/jsonwizard/jsonwizardfactory.h>
+
+#include <extensionsystem/pluginmanager.h>
+#include <utils/algorithm.h>
+#include <utils/qtcassert.h>
+
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QWizardPage>
+
+using namespace Core;
+using namespace ProjectExplorer;
+
+namespace VcsBase {
+namespace Internal {
+
+VcsConfigurationPageFactory::VcsConfigurationPageFactory()
+{
+ setTypeIdsSuffix(QLatin1String("VcsConfiguration"));
+}
+
+Utils::WizardPage *VcsConfigurationPageFactory::create(JsonWizard *wizard, Id typeId,
+ const QVariant &data)
+{
+ Q_UNUSED(wizard);
+
+ QTC_ASSERT(canCreate(typeId), return 0);
+
+ QVariantMap tmp = data.toMap();
+ const QString vcsId = tmp.value(QLatin1String("vcsId")).toString();
+ QTC_ASSERT(!vcsId.isEmpty(), return 0);
+
+ auto page = new VcsConfigurationPage;
+ page->setVersionControlId(vcsId);
+
+ return page;
+}
+
+bool VcsConfigurationPageFactory::validateData(Id typeId, const QVariant &data,
+ QString *errorMessage)
+{
+ QTC_ASSERT(canCreate(typeId), return false);
+
+ if (data.isNull() || data.type() != QVariant::Map) {
+ *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizard",
+ "\"data\" must be a JSON object for \"VcsConfiguration\" pages.");
+ return false;
+ }
+
+ QVariantMap tmp = data.toMap();
+ const QString vcsId = tmp.value(QLatin1String("vcsId")).toString();
+ if (vcsId.isEmpty()) {
+ *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizard",
+ "\"VcsConfiguration\" page requires a \"vcsId\" set.");
+ return false;
+ }
+ return true;
+}
+
+class VcsConfigurationPagePrivate
+{
+public:
+ const IVersionControl *m_versionControl;
+ QString m_versionControlId;
+ QPushButton *m_configureButton;
+};
+
+} // namespace Internal
+
+VcsConfigurationPage::VcsConfigurationPage() : d(new Internal::VcsConfigurationPagePrivate)
+{
+ setTitle(tr("Configuration"));
+
+ d->m_versionControl = 0;
+ d->m_configureButton = new QPushButton(ICore::msgShowOptionsDialog(), this);
+ d->m_configureButton->setEnabled(false);
+
+ auto verticalLayout = new QVBoxLayout(this);
+ verticalLayout->addWidget(d->m_configureButton);
+
+ connect(d->m_versionControl, SIGNAL(configurationChanged()), SIGNAL(completeChanged()));
+ connect(d->m_configureButton, SIGNAL(clicked()), SLOT(openConfiguration()));
+}
+
+VcsConfigurationPage::~VcsConfigurationPage()
+{
+ delete d;
+}
+
+void VcsConfigurationPage::setVersionControl(const IVersionControl *vc)
+{
+ if (vc)
+ d->m_versionControlId = vc->id().toString();
+ else
+ d->m_versionControlId.clear();
+ d->m_versionControl = 0;
+}
+
+void VcsConfigurationPage::setVersionControlId(const QString &id)
+{
+ d->m_versionControlId = id;
+}
+
+void VcsConfigurationPage::initializePage()
+{
+ if (!d->m_versionControlId.isEmpty()) {
+ auto jw = qobject_cast<JsonWizard *>(wizard());
+ if (!jw)
+ emit reportError(tr("No version control set on \"VcsConfiguration\" page."));
+
+ const QString vcsId = jw ? jw->expander()->expand(d->m_versionControlId) : d->m_versionControlId;
+
+ d->m_versionControl = VcsManager::versionControl(Id::fromString(vcsId));
+ if (!d->m_versionControl) {
+ emit reportError(
+ tr("\"vcsId\" (\"%1\") is invalid for \"VcsConfiguration\" page. "
+ "Possible values are: %2.")
+ .arg(vcsId)
+ .arg(QStringList(Utils::transform(VcsManager::versionControls(), [](const IVersionControl *vc) {
+ return vc->id().toString();
+ })).join(QLatin1String(", "))));
+ }
+ }
+
+ d->m_configureButton->setEnabled(d->m_versionControl);
+ if (d->m_versionControl)
+ setSubTitle(tr("Please configure <b>%1</b> now.").arg(d->m_versionControl->displayName()));
+ else
+ setSubTitle(tr("No known version control selected."));
+}
+
+bool VcsConfigurationPage::isComplete() const
+{
+ return d->m_versionControl ? d->m_versionControl->isConfigured() : false;
+}
+
+void VcsConfigurationPage::openConfiguration()
+{
+ ICore::showOptionsDialog(Constants::VCS_SETTINGS_CATEGORY, d->m_versionControl->id(), this);
+}
+
+} // namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsconfigurationpage.h b/src/plugins/vcsbase/wizard/vcsconfigurationpage.h
index c3f5ed6e1c3..6c39248f0cc 100644
--- a/src/plugins/vcsbase/vcsconfigurationpage.h
+++ b/src/plugins/vcsbase/wizard/vcsconfigurationpage.h
@@ -31,9 +31,11 @@
#ifndef VCSCONFIGURATIONPAGE_H
#define VCSCONFIGURATIONPAGE_H
-#include "vcsbase_global.h"
+#include "../vcsbase_global.h"
-#include <QWizardPage>
+#include <projectexplorer/jsonwizard/jsonwizardpagefactory.h>
+
+#include <utils/wizardpage.h>
namespace Core { class IVersionControl; }
@@ -41,14 +43,31 @@ namespace VcsBase {
namespace Internal { class VcsConfigurationPagePrivate; }
-class VCSBASE_EXPORT VcsConfigurationPage : public QWizardPage
+namespace Internal {
+
+class VcsConfigurationPageFactory : public ProjectExplorer::JsonWizardPageFactory
+{
+public:
+ VcsConfigurationPageFactory();
+
+ Utils::WizardPage *create(ProjectExplorer::JsonWizard *wizard, Core::Id typeId, const QVariant &data);
+ bool validateData(Core::Id typeId, const QVariant &data, QString *errorMessage);
+};
+
+} // namespace Internal
+
+class VCSBASE_EXPORT VcsConfigurationPage : public Utils::WizardPage
{
Q_OBJECT
public:
- explicit VcsConfigurationPage(const Core::IVersionControl *, QWidget *parent = 0);
+ VcsConfigurationPage();
~VcsConfigurationPage();
+ void setVersionControl(const Core::IVersionControl *vc);
+ void setVersionControlId(const QString &id);
+
+ void initializePage();
bool isComplete() const;
private slots:
diff --git a/src/plugins/vcsbase/wizard/vcsjsextension.cpp b/src/plugins/vcsbase/wizard/vcsjsextension.cpp
new file mode 100644
index 00000000000..ba394113124
--- /dev/null
+++ b/src/plugins/vcsbase/wizard/vcsjsextension.cpp
@@ -0,0 +1,54 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 "vcsjsextension.h"
+
+#include <coreplugin/iversioncontrol.h>
+#include <coreplugin/vcsmanager.h>
+
+using namespace Core;
+
+namespace VcsBase {
+namespace Internal {
+
+bool VcsJsExtension::isConfigured(const QString &vcsId) const
+{
+ IVersionControl *vc = VcsManager::versionControl(Id::fromString(vcsId));
+ return vc && vc->isConfigured();
+}
+
+QString VcsJsExtension::displayName(const QString &vcsId) const
+{
+ IVersionControl *vc = VcsManager::versionControl(Id::fromString(vcsId));
+ return vc ? vc->displayName() : QString();
+}
+
+} // namespace Internal
+} // namespace VcsBase
diff --git a/src/plugins/vcsbase/wizard/vcsjsextension.h b/src/plugins/vcsbase/wizard/vcsjsextension.h
new file mode 100644
index 00000000000..289f9186c8d
--- /dev/null
+++ b/src/plugins/vcsbase/wizard/vcsjsextension.h
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://www.qt.io/licensing. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** 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 VCSJSEXTENSION_H
+#define VCSJSEXTENSION_H
+
+#include <QObject>
+
+namespace VcsBase {
+namespace Internal {
+
+class VcsJsExtension : public QObject
+{
+ Q_OBJECT
+
+public:
+ Q_INVOKABLE bool isConfigured(const QString &vcsId) const;
+ Q_INVOKABLE QString displayName(const QString &vcsId) const;
+};
+
+} // namespace Internal
+} // namespace VcsBase
+
+#endif // VCSJSEXTENSION_H
diff --git a/src/plugins/welcome/welcome.qbs b/src/plugins/welcome/welcome.qbs
index 8bdafc044c0..4d3067c0eca 100644
--- a/src/plugins/welcome/welcome.qbs
+++ b/src/plugins/welcome/welcome.qbs
@@ -13,5 +13,6 @@ QtcPlugin {
files: [
"welcomeplugin.cpp",
"welcomeplugin.h",
+ "welcome.qrc",
]
}
diff --git a/src/plugins/welcome/welcomeplugin.cpp b/src/plugins/welcome/welcomeplugin.cpp
index 4cec3f24590..651194e31ad 100644
--- a/src/plugins/welcome/welcomeplugin.cpp
+++ b/src/plugins/welcome/welcomeplugin.cpp
@@ -35,14 +35,15 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/imode.h>
-#include <coreplugin/modemanager.h>
+#include <coreplugin/iwelcomepage.h>
#include <coreplugin/iwizardfactory.h>
+#include <coreplugin/modemanager.h>
#include <utils/algorithm.h>
#include <utils/fileutils.h>
#include <utils/hostosinfo.h>
+#include <utils/qtcassert.h>
#include <utils/styledbar.h>
-#include <utils/iwelcomepage.h>
#include <utils/theme/theme.h>
@@ -64,6 +65,7 @@
enum { debug = 0 };
+using namespace Core;
using namespace ExtensionSystem;
using namespace Utils;
@@ -72,7 +74,19 @@ static const char currentPageSettingsKeyC[] = "WelcomeTab";
namespace Welcome {
namespace Internal {
-class WelcomeMode : public Core::IMode
+static QString applicationDirPath()
+{
+ // normalize paths so QML doesn't freak out if it's wrongly capitalized on Windows
+ return FileUtils::normalizePathName(QCoreApplication::applicationDirPath());
+}
+
+static QString resourcePath()
+{
+ // normalize paths so QML doesn't freak out if it's wrongly capitalized on Windows
+ return FileUtils::normalizePathName(ICore::resourcePath());
+}
+
+class WelcomeMode : public IMode
{
Q_OBJECT
Q_PROPERTY(int activePlugin READ activePlugin WRITE setActivePlugin NOTIFY activePluginChanged)
@@ -84,8 +98,6 @@ public:
void initPlugins();
int activePlugin() const { return m_activePlugin; }
-// bool eventFilter(QObject *, QEvent *);
-
public slots:
void onThemeChanged();
@@ -100,30 +112,29 @@ public slots:
signals:
void activePluginChanged(int pos);
-private slots:
+private:
void welcomePluginAdded(QObject*);
void sceneGraphError(QQuickWindow::SceneGraphError, const QString &message);
-
-private:
void facilitateQml(QQmlEngine *engine);
+ void addPages(const QList<IWelcomePage *> &pages);
QWidget *m_modeWidget;
QuickContainer *m_welcomePage;
- QList<QObject*> m_pluginList;
+ QMap<Id, IWelcomePage *> m_idPageMap;
+ QList<IWelcomePage *> m_pluginList;
int m_activePlugin;
QQmlPropertyMap m_themeProperties;
};
-// --- WelcomeMode
WelcomeMode::WelcomeMode()
: m_activePlugin(0)
{
setDisplayName(tr("Welcome"));
setIcon(QIcon(QLatin1String(":/welcome/images/mode_welcome.png")));
- setPriority(Core::Constants::P_MODE_WELCOME);
- setId(Core::Constants::MODE_WELCOME);
+ setPriority(Constants::P_MODE_WELCOME);
+ setId(Constants::MODE_WELCOME);
setContextHelpId(QLatin1String("Qt Creator Manual"));
- setContext(Core::Context(Core::Constants::C_WELCOME_MODE));
+ setContext(Context(Constants::C_WELCOME_MODE));
m_modeWidget = new QWidget;
m_modeWidget->setObjectName(QLatin1String("WelcomePageModeWidget"));
@@ -132,15 +143,15 @@ WelcomeMode::WelcomeMode()
layout->setSpacing(0);
m_welcomePage = new QuickContainer();
- onThemeChanged(); //initialize background color
+ onThemeChanged(); // initialize background color and theme properties
m_welcomePage->setResizeMode(QuickContainer::SizeRootObjectToView);
m_welcomePage->setObjectName(QLatin1String("WelcomePage"));
- connect(m_welcomePage, SIGNAL(sceneGraphError(QQuickWindow::SceneGraphError,QString)),
- this, SLOT(sceneGraphError(QQuickWindow::SceneGraphError,QString)));
+ connect(m_welcomePage, &QuickContainer::sceneGraphError,
+ this, &WelcomeMode::sceneGraphError);
- Utils::StyledBar* styledBar = new Utils::StyledBar(m_modeWidget);
+ StyledBar *styledBar = new StyledBar(m_modeWidget);
styledBar->setObjectName(QLatin1String("WelcomePageStyledBar"));
layout->addWidget(styledBar);
@@ -154,23 +165,21 @@ WelcomeMode::WelcomeMode()
layout->addWidget(container);
#endif // USE_QUICK_WIDGET
- connect(PluginManager::instance(), SIGNAL(objectAdded(QObject*)), SLOT(welcomePluginAdded(QObject*)));
+ connect(ICore::instance(), &ICore::themeChanged, this, &WelcomeMode::onThemeChanged);
setWidget(m_modeWidget);
}
void WelcomeMode::onThemeChanged()
{
- m_welcomePage->setColor(creatorTheme()->color(Theme::BackgroundColorNormal));
const QVariantHash creatorTheme = Utils::creatorTheme()->values();
- QVariantHash::const_iterator it;
- for (it = creatorTheme.constBegin(); it != creatorTheme.constEnd(); ++it)
+ for (auto it = creatorTheme.constBegin(); it != creatorTheme.constEnd(); ++it)
m_themeProperties.insert(it.key(), it.value());
}
WelcomeMode::~WelcomeMode()
{
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
settings->setValue(QLatin1String(currentPageSettingsKeyC), activePlugin());
delete m_modeWidget;
}
@@ -186,119 +195,90 @@ void WelcomeMode::sceneGraphError(QQuickWindow::SceneGraphError, const QString &
messageBox->show();
}
-void WelcomeMode::facilitateQml(QQmlEngine * /*engine*/)
+void WelcomeMode::facilitateQml(QQmlEngine *engine)
{
-}
-
-static QString applicationDirPath()
-{
- // normalize paths so QML doesn't freak out if it's wrongly capitalized on Windows
- return Utils::FileUtils::normalizePathName(QCoreApplication::applicationDirPath());
-}
-
-static QString resourcePath()
-{
- // normalize paths so QML doesn't freak out if it's wrongly capitalized on Windows
- return Utils::FileUtils::normalizePathName(Core::ICore::resourcePath());
-}
-
-void WelcomeMode::initPlugins()
-{
- QSettings *settings = Core::ICore::settings();
- setActivePlugin(settings->value(QLatin1String(currentPageSettingsKeyC)).toInt());
-
- QQmlContext *ctx = m_welcomePage->rootContext();
- ctx->setContextProperty(QLatin1String("welcomeMode"), this);
-
- QList<Utils::IWelcomePage*> duplicatePlugins = PluginManager::getObjects<Utils::IWelcomePage>();
- Utils::sort(duplicatePlugins, [](const Utils::IWelcomePage *l, const Utils::IWelcomePage *r) {
- return l->priority() < r->priority();
- });
-
- QList<Utils::IWelcomePage*> plugins;
- QHash<Utils::IWelcomePage::Id, Utils::IWelcomePage*> pluginHash;
-
- //avoid duplicate ids - choose by priority
- foreach (Utils::IWelcomePage* plugin, duplicatePlugins) {
- if (pluginHash.contains(plugin->id())) {
- Utils::IWelcomePage* pluginOther = pluginHash.value(plugin->id());
-
- if (pluginOther->priority() > plugin->priority()) {
- plugins.removeAll(pluginOther);
- pluginHash.remove(pluginOther->id());
- plugins << plugin;
- pluginHash.insert(plugin->id(), plugin);
- }
-
- } else {
- plugins << plugin;
- pluginHash.insert(plugin->id(), plugin);
- }
- }
-
-
- QQmlEngine *engine = m_welcomePage->engine();
QStringList importPathList = engine->importPathList();
importPathList << resourcePath() + QLatin1String("/welcomescreen");
engine->setImportPathList(importPathList);
if (!debug)
engine->setOutputWarningsToStandardError(false);
+
QString pluginPath = applicationDirPath();
if (HostOsInfo::isMacHost())
pluginPath += QLatin1String("/../PlugIns");
else
pluginPath += QLatin1String("/../" IDE_LIBRARY_BASENAME "/qtcreator");
engine->addImportPath(QDir::cleanPath(pluginPath));
- facilitateQml(engine);
- foreach (Utils::IWelcomePage *plugin, plugins) {
- plugin->facilitateQml(engine);
- m_pluginList.append(plugin);
- }
- ctx->setContextProperty(QLatin1String("pagesModel"), QVariant::fromValue(m_pluginList));
+ QQmlContext *ctx = engine->rootContext();
+ ctx->setContextProperty(QLatin1String("welcomeMode"), this);
- onThemeChanged();
- connect(Core::ICore::instance(), &Core::ICore::themeChanged, this, &WelcomeMode::onThemeChanged);
ctx->setContextProperty(QLatin1String("creatorTheme"), &m_themeProperties);
+#if defined(USE_QUICK_WIDGET)
+ bool useNativeText = !HostOsInfo::isMacHost();
+#else
+ bool useNativeText = true;
+#endif
+ ctx->setContextProperty(QLatin1String("useNativeText"), useNativeText);
+}
+
+void WelcomeMode::initPlugins()
+{
+ QSettings *settings = ICore::settings();
+ setActivePlugin(settings->value(QLatin1String(currentPageSettingsKeyC)).toInt());
+
+ facilitateQml(m_welcomePage->engine());
+
+ QList<IWelcomePage *> availablePages = PluginManager::getObjects<IWelcomePage>();
+ addPages(availablePages);
+ // make sure later added pages are made available too:
+ connect(PluginManager::instance(), &PluginManager::objectAdded,
+ this, &WelcomeMode::welcomePluginAdded);
+
QString path = resourcePath() + QLatin1String("/welcomescreen/welcomescreen.qml");
// finally, load the root page
- m_welcomePage->setSource(
- QUrl::fromLocalFile(path));
+ m_welcomePage->setSource(QUrl::fromLocalFile(path));
}
void WelcomeMode::welcomePluginAdded(QObject *obj)
{
- QHash<Utils::IWelcomePage::Id, Utils::IWelcomePage*> pluginHash;
-
- foreach (QObject *obj, m_pluginList) {
- Utils::IWelcomePage *plugin = qobject_cast<Utils::IWelcomePage*>(obj);
- pluginHash.insert(plugin->id(), plugin);
- }
- if (Utils::IWelcomePage *plugin = qobject_cast<Utils::IWelcomePage*>(obj)) {
- //check for duplicated id
- if (pluginHash.contains(plugin->id())) {
- Utils::IWelcomePage* pluginOther = pluginHash.value(plugin->id());
-
- if (pluginOther->priority() > plugin->priority())
- m_pluginList.removeAll(pluginOther);
- else
- return;
- }
+ IWelcomePage *page = qobject_cast<IWelcomePage*>(obj);
+ if (!page)
+ return;
+ addPages(QList<IWelcomePage *>() << page);
+}
- int insertPos = 0;
- foreach (Utils::IWelcomePage* p, PluginManager::getObjects<Utils::IWelcomePage>()) {
- if (plugin->priority() < p->priority())
- insertPos++;
- else
- break;
- }
- m_pluginList.insert(insertPos, plugin);
- // update model through reset
- QQmlContext *ctx = m_welcomePage->rootContext();
- ctx->setContextProperty(QLatin1String("pagesModel"), QVariant::fromValue(m_pluginList));
+void WelcomeMode::addPages(const QList<IWelcomePage *> &pages)
+{
+ QList<IWelcomePage *> addedPages = pages;
+ Utils::sort(addedPages, [](const IWelcomePage *l, const IWelcomePage *r) {
+ return l->priority() < r->priority();
+ });
+ // insert into m_pluginList, keeping m_pluginList sorted by priority
+ QQmlEngine *engine = m_welcomePage->engine();
+ auto addIt = addedPages.begin();
+ auto currentIt = m_pluginList.begin();
+ while (addIt != addedPages.end()) {
+ IWelcomePage *page = *addIt;
+ QTC_ASSERT(!m_idPageMap.contains(page->id()), ++addIt; continue);
+ while (currentIt != m_pluginList.end() && (*currentIt)->priority() <= page->priority())
+ ++currentIt;
+ // currentIt is now either end() or a page with higher value
+ currentIt = m_pluginList.insert(currentIt, page);
+ m_idPageMap.insert(page->id(), page);
+ page->facilitateQml(engine);
+ ++currentIt;
+ ++addIt;
}
+ // update model through reset
+ QQmlContext *ctx = engine->rootContext();
+ ctx->setContextProperty(QLatin1String("pagesModel"), QVariant::fromValue(
+ Utils::transform(m_pluginList, // transform into QList<QObject *>
+ [](IWelcomePage *page) -> QObject * {
+ return page;
+ })));
}
WelcomePlugin::WelcomePlugin()
@@ -306,12 +286,6 @@ WelcomePlugin::WelcomePlugin()
{
}
-/*! Initializes the plugin. Returns true on success.
- Plugins want to register objects with the plugin manager here.
-
- \a errorMessage can be used to pass an error message to the plugin system,
- if there was any.
-*/
bool WelcomePlugin::initialize(const QStringList & /* arguments */, QString * /* errorMessage */)
{
m_welcomeMode = new WelcomeMode;
@@ -320,21 +294,10 @@ bool WelcomePlugin::initialize(const QStringList & /* arguments */, QString * /*
return true;
}
-/*! Notification that all extensions that this plugin depends on have been
- initialized. The dependencies are defined in the plugins .qwp file.
-
- Normally this function is used for things that rely on other plugins to have
- added objects to the plugin manager, that implement interfaces that we're
- interested in. These objects can now be requested through the
- PluginManagerInterface.
-
- The WelcomePlugin doesn't need things from other plugins, so it does
- nothing here.
-*/
void WelcomePlugin::extensionsInitialized()
{
m_welcomeMode->initPlugins();
- Core::ModeManager::activateMode(m_welcomeMode->id());
+ ModeManager::activateMode(m_welcomeMode->id());
}
} // namespace Internal
diff --git a/src/plugins/winrt/winrtdebugsupport.cpp b/src/plugins/winrt/winrtdebugsupport.cpp
index eb401b9849b..bf2dfbf4033 100644
--- a/src/plugins/winrt/winrtdebugsupport.cpp
+++ b/src/plugins/winrt/winrtdebugsupport.cpp
@@ -32,7 +32,6 @@
#include "winrtrunconfiguration.h"
#include "winrtrunnerhelper.h"
-#include <debugger/debuggerengine.h>
#include <debugger/debuggerkitinformation.h>
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggerstartparameters.h>
@@ -120,8 +119,9 @@ RunControl *WinRtDebugSupport::createDebugRunControl(WinRtRunConfiguration *runC
return 0;
}
server.close();
+ params.runConfiguration = runConfig;
Debugger::DebuggerRunControl *debugRunControl
- = DebuggerRunControlFactory::doCreate(params, runConfig, errorMessage);
+ = DebuggerRunControlFactory::doCreate(params, errorMessage);
runner->setRunControl(debugRunControl);
new WinRtDebugSupport(debugRunControl, runner);
return debugRunControl;
diff --git a/src/plugins/winrt/winrtdevice.cpp b/src/plugins/winrt/winrtdevice.cpp
index 1e2689c0460..f6ab151db75 100644
--- a/src/plugins/winrt/winrtdevice.cpp
+++ b/src/plugins/winrt/winrtdevice.cpp
@@ -88,7 +88,7 @@ void WinRtDevice::executeAction(Core::Id actionId, QWidget *parent)
DeviceProcessSignalOperation::Ptr WinRtDevice::signalOperation() const
{
- class WinRtDesktopSignalOperation : public ProjectExplorer::DesktopProcessSignalOperation
+ class WinRtDesktopSignalOperation : public DesktopProcessSignalOperation
{
public:
WinRtDesktopSignalOperation() {}
diff --git a/src/plugins/winrt/winrtpackagedeploymentstep.cpp b/src/plugins/winrt/winrtpackagedeploymentstep.cpp
index f604b6fdaa8..4d0fca6e9df 100644
--- a/src/plugins/winrt/winrtpackagedeploymentstep.cpp
+++ b/src/plugins/winrt/winrtpackagedeploymentstep.cpp
@@ -244,15 +244,15 @@ QString WinRtPackageDeploymentStep::defaultWinDeployQtArguments() const
void WinRtPackageDeploymentStep::raiseError(const QString &errorMessage)
{
emit addOutput(errorMessage, BuildStep::ErrorMessageOutput);
- emit addTask(ProjectExplorer::Task(ProjectExplorer::Task::Error, errorMessage, Utils::FileName(), -1,
- ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT));
+ emit addTask(Task(Task::Error, errorMessage, Utils::FileName(), -1,
+ ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT));
}
void WinRtPackageDeploymentStep::raiseWarning(const QString &warningMessage)
{
emit addOutput(warningMessage, BuildStep::MessageOutput);
- emit addTask(ProjectExplorer::Task(ProjectExplorer::Task::Warning, warningMessage, Utils::FileName(), -1,
- ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT));
+ emit addTask(Task(Task::Warning, warningMessage, Utils::FileName(), -1,
+ ProjectExplorer::Constants::TASK_CATEGORY_DEPLOYMENT));
}
bool WinRtPackageDeploymentStep::fromMap(const QVariantMap &map)
diff --git a/src/plugins/winrt/winrtrunfactories.cpp b/src/plugins/winrt/winrtrunfactories.cpp
index 2e49bef7c18..14336fb5306 100644
--- a/src/plugins/winrt/winrtrunfactories.cpp
+++ b/src/plugins/winrt/winrtrunfactories.cpp
@@ -136,8 +136,8 @@ WinRtRunControlFactory::WinRtRunControlFactory()
{
}
-bool WinRtRunControlFactory::canRun(ProjectExplorer::RunConfiguration *runConfiguration,
- ProjectExplorer::RunMode mode) const
+bool WinRtRunControlFactory::canRun(RunConfiguration *runConfiguration,
+ RunMode mode) const
{
if (!runConfiguration)
return false;
@@ -158,7 +158,7 @@ bool WinRtRunControlFactory::canRun(ProjectExplorer::RunConfiguration *runConfig
}
}
-ProjectExplorer::RunControl *WinRtRunControlFactory::create(
+RunControl *WinRtRunControlFactory::create(
RunConfiguration *runConfiguration, RunMode mode, QString *errorMessage)
{
WinRtRunConfiguration *rc = qobject_cast<WinRtRunConfiguration *>(runConfiguration);
diff --git a/src/share/qtcreator/externaltools/qmlscene.xml b/src/share/qtcreator/externaltools/qmlscene.xml
index 503ab259e77..9f35bfb6fd3 100644
--- a/src/share/qtcreator/externaltools/qmlscene.xml
+++ b/src/share/qtcreator/externaltools/qmlscene.xml
@@ -40,5 +40,6 @@
<path>qmlscene</path>
<arguments>%{CurrentDocument:FilePath}</arguments>
<workingdirectory>%{CurrentDocument:Path}</workingdirectory>
+ <environment>QT_LOGGING_TO_CONSOLE%3D1</environment>
</executable>
</externaltool>
diff --git a/src/share/qtcreator/externaltools/qmlviewer.xml b/src/share/qtcreator/externaltools/qmlviewer.xml
index 41007817acc..7f2f92725c3 100644
--- a/src/share/qtcreator/externaltools/qmlviewer.xml
+++ b/src/share/qtcreator/externaltools/qmlviewer.xml
@@ -40,5 +40,6 @@
<path>qmlviewer</path>
<arguments>%{CurrentDocument:FilePath}</arguments>
<workingdirectory>%{CurrentDocument:Path}</workingdirectory>
+ <environment>QT_LOGGING_TO_CONSOLE%3D1</environment>
</executable>
</externaltool>
diff --git a/src/shared/help/bookmarkmanager.cpp b/src/shared/help/bookmarkmanager.cpp
index 6feda6618db..68225ae1324 100644
--- a/src/shared/help/bookmarkmanager.cpp
+++ b/src/shared/help/bookmarkmanager.cpp
@@ -85,25 +85,25 @@ BookmarkDialog::BookmarkDialog(BookmarkManager *manager, const QString &title,
ui.treeView->header()->setVisible(false);
ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui.buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
- connect(ui.buttonBox, SIGNAL(accepted()), this, SLOT(addAccepted()));
- connect(ui.newFolderButton, SIGNAL(clicked()), this, SLOT(addNewFolder()));
- connect(ui.toolButton, SIGNAL(clicked()), this, SLOT(toolButtonClicked()));
- connect(ui.bookmarkEdit, SIGNAL(textChanged(QString)), this,
- SLOT(textChanged(QString)));
+ connect(ui.buttonBox, &QDialogButtonBox::rejected, this, &BookmarkDialog::reject);
+ connect(ui.buttonBox, &QDialogButtonBox::accepted, this, &BookmarkDialog::addAccepted);
+ connect(ui.newFolderButton, &QPushButton::clicked, this, &BookmarkDialog::addNewFolder);
+ connect(ui.toolButton, &QToolButton::clicked, this, &BookmarkDialog::toolButtonClicked);
+ connect(ui.bookmarkEdit, &QLineEdit::textChanged, this, &BookmarkDialog::textChanged);
connect(bookmarkManager->treeBookmarkModel(),
- SIGNAL(itemChanged(QStandardItem*)),
- this, SLOT(itemChanged(QStandardItem*)));
+ &QStandardItemModel::itemChanged,
+ this, &BookmarkDialog::itemChanged);
- connect(ui.bookmarkFolders, SIGNAL(currentIndexChanged(QString)), this,
- SLOT(selectBookmarkFolder(QString)));
+ connect(ui.bookmarkFolders,
+ static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::currentIndexChanged),
+ this, &BookmarkDialog::selectBookmarkFolder);
- connect(ui.treeView, SIGNAL(customContextMenuRequested(QPoint)), this,
- SLOT(customContextMenuRequested(QPoint)));
+ connect(ui.treeView, &TreeView::customContextMenuRequested,
+ this, &BookmarkDialog::customContextMenuRequested);
- connect(ui.treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,
- QModelIndex)), this, SLOT(currentChanged(QModelIndex)));
+ connect(ui.treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)),
+ this, SLOT(currentChanged(QModelIndex)));
}
BookmarkDialog::~BookmarkDialog()
@@ -437,8 +437,8 @@ void BookmarkWidget::setup()
vlayout->addWidget(toolbar);
searchField->installEventFilter(this);
- connect(searchField, SIGNAL(textChanged(QString)), this,
- SLOT(filterChanged()));
+ connect(searchField, &Utils::FancyLineEdit::textChanged,
+ this, &BookmarkWidget::filterChanged);
treeView = new TreeView(this);
vlayout->addWidget(treeView);
@@ -453,14 +453,11 @@ void BookmarkWidget::setup()
treeView->viewport()->installEventFilter(this);
treeView->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(treeView, SIGNAL(expanded(QModelIndex)), this,
- SLOT(expand(QModelIndex)));
- connect(treeView, SIGNAL(collapsed(QModelIndex)), this,
- SLOT(expand(QModelIndex)));
- connect(treeView, SIGNAL(activated(QModelIndex)), this,
- SLOT(activated(QModelIndex)));
- connect(treeView, SIGNAL(customContextMenuRequested(QPoint)),
- this, SLOT(customContextMenuRequested(QPoint)));
+ connect(treeView, &TreeView::expanded, this, &BookmarkWidget::expand);
+ connect(treeView, &TreeView::collapsed, this, &BookmarkWidget::expand);
+ connect(treeView, &TreeView::activated, this, &BookmarkWidget::activated);
+ connect(treeView, &TreeView::customContextMenuRequested,
+ this, &BookmarkWidget::customContextMenuRequested);
filterBookmarkModel->setFilterKeyColumn(0);
filterBookmarkModel->setDynamicSortFilter(true);
@@ -582,8 +579,8 @@ BookmarkManager::BookmarkManager()
, treeModel(new BookmarkModel(0, 1, this))
, listModel(new BookmarkModel(0, 1, this))
{
- connect(treeModel, SIGNAL(itemChanged(QStandardItem*)), this,
- SLOT(itemChanged(QStandardItem*)));
+ connect(treeModel, &BookmarkModel::itemChanged,
+ this, &BookmarkManager::itemChanged);
}
BookmarkManager::~BookmarkManager()
diff --git a/src/shared/help/topicchooser.cpp b/src/shared/help/topicchooser.cpp
index dabd5ad1765..84b1f2cdeb4 100644
--- a/src/shared/help/topicchooser.cpp
+++ b/src/shared/help/topicchooser.cpp
@@ -69,12 +69,14 @@ TopicChooser::TopicChooser(QWidget *parent, const QString &keyword,
if (m_filterModel->rowCount() != 0)
ui.listWidget->setCurrentIndex(m_filterModel->index(0, 0));
- connect(ui.buttonDisplay, SIGNAL(clicked()), this, SLOT(acceptDialog()));
- connect(ui.buttonCancel, SIGNAL(clicked()), this, SLOT(reject()));
- connect(ui.listWidget, SIGNAL(activated(QModelIndex)), this,
- SLOT(activated(QModelIndex)));
- connect(ui.lineEdit, SIGNAL(filterChanged(QString)), this,
- SLOT(setFilter(QString)));
+ connect(ui.buttonDisplay, &QPushButton::clicked,
+ this, &TopicChooser::acceptDialog);
+ connect(ui.buttonCancel, &QPushButton::clicked,
+ this, &TopicChooser::reject);
+ connect(ui.listWidget, &QListView::activated,
+ this, &TopicChooser::activated);
+ connect(ui.lineEdit, &Utils::FancyLineEdit::filterChanged,
+ this, &TopicChooser::setFilter);
}
QUrl TopicChooser::link() const
diff --git a/src/shared/proparser/profileevaluator.cpp b/src/shared/proparser/profileevaluator.cpp
index 98776e9a08a..af823daf84a 100644
--- a/src/shared/proparser/profileevaluator.cpp
+++ b/src/shared/proparser/profileevaluator.cpp
@@ -197,7 +197,44 @@ bool ProFileEvaluator::loadNamedSpec(const QString &specDir, bool hostSpec)
bool ProFileEvaluator::accept(ProFile *pro, QMakeEvaluator::LoadFlags flags)
{
- return d->visitProFile(pro, QMakeHandler::EvalProjectFile, flags) == QMakeEvaluator::ReturnTrue;
+ if (d->visitProFile(pro, QMakeHandler::EvalProjectFile, flags) != QMakeEvaluator::ReturnTrue)
+ return false;
+
+ if (flags & QMakeEvaluator::LoadPostFiles) {
+ // This is postprocessing which is hard-coded inside qmake's generators.
+
+ ProStringList &incpath = d->valuesRef(ProKey("INCLUDEPATH"));
+ incpath += d->values(ProKey("QMAKE_INCDIR"));
+ if (!d->isActiveConfig(QStringLiteral("no_include_pwd"))) {
+ incpath.prepend(ProString(pro->directoryName()));
+ // It's pretty stupid that this is appended - it should be the second entry.
+ if (pro->directoryName() != d->m_outputDir)
+ incpath << ProString(d->m_outputDir);
+ }
+ // The location of this is inconsistent among generators.
+ incpath << ProString(d->m_qmakespec);
+
+ // We ignore CFLAGS and LFLAGS, as they are not used higher up anyway.
+ ProStringList &cxxflags = d->valuesRef(ProKey("QMAKE_CXXFLAGS"));
+ switch (templateType()) {
+ case TT_Application:
+ cxxflags += d->values(ProKey("QMAKE_CXXFLAGS_APP"));
+ break;
+ case TT_Library:
+ if (d->isActiveConfig(QStringLiteral("dll"))) {
+ bool plugin = d->isActiveConfig(QStringLiteral("plugin"));
+ if (!plugin || !d->isActiveConfig(QStringLiteral("plugin_no_share_shlib_cflags")))
+ cxxflags += d->values(ProKey("QMAKE_CXXFLAGS_SHLIB"));
+ if (plugin)
+ cxxflags += d->values(ProKey("QMAKE_CXXFLAGS_PLUGIN"));
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ return true;
}
QString ProFileEvaluator::propertyValue(const QString &name) const
@@ -205,11 +242,6 @@ QString ProFileEvaluator::propertyValue(const QString &name) const
return d->m_option->propertyValue(ProKey(name)).toQString();
}
-QString ProFileEvaluator::resolvedMkSpec() const
-{
- return d->m_qmakespec;
-}
-
#ifdef PROEVALUATOR_CUMULATIVE
void ProFileEvaluator::setCumulative(bool on)
{
diff --git a/src/shared/proparser/profileevaluator.h b/src/shared/proparser/profileevaluator.h
index f630a3ecde5..5ededbc1764 100644
--- a/src/shared/proparser/profileevaluator.h
+++ b/src/shared/proparser/profileevaluator.h
@@ -93,8 +93,6 @@ public:
const ProFile *pro) const;
QString propertyValue(const QString &val) const;
- QString resolvedMkSpec() const;
-
private:
QString sysrootify(const QString &path, const QString &baseDir) const;
diff --git a/src/shared/qbs b/src/shared/qbs
-Subproject 86e872bd99184fe862bfe30ef43acd9806e34bc
+Subproject 9567f37d9f7b5f47caa01ba2d0dca61314d4deb
diff --git a/src/shared/scriptwrapper/README b/src/shared/scriptwrapper/README
deleted file mode 100644
index dd7f4bf14a7..00000000000
--- a/src/shared/scriptwrapper/README
+++ /dev/null
@@ -1,58 +0,0 @@
-Some wrap helpers for Script support.
-
-How to wrap an interface:
-=========================
-
-1) Prototypes (preferred)
--------------------------
-
-- Interface must inherit QObjectInterface and be qvariant-castable, that is,
- declared as Q-MetaType.
-
-- Register a prototype with the engine for each interface:
- - Provide an informative toString()-slot.
- - Use properties and slots for everything, can be non-void as well
- - Accessors to interfaces should be properties.
-
-- In the toScriptValue() function passed on to qScriptRegisterMetaType, create
- an newQObject on the QObject obtained from the QObjectInterface and assign it the prototype
- registered for the interface (obtained from the engine) using QScriptValue::setDefaultPrototype
- The prototype can then qobject (-extension)-cast to the interface as each
- implementing class returns 'this' as qObject() of QObjectInterface.
-
-- If sequences of the interface are used, declare them as Q-MetaType
- and do qScriptRegisterSequenceMetaType().
-
-The template registerQObjectInterface does the magic.
-
-2) Manually bless a script value with properties
-------------------------------------------------
-
-Typically, a qobject-derived wrapper will be used
-that provides an accessor to the wrapped class.
-The wrapper contains a QScriptValue 'm_self' which
-typically is initialized using:
-
-- engine.newQObject(this, QScriptEngine::ScriptOwnership))
- for interfaces that are always present.
-
-- m_self(engine.newQObject(this, QScriptEngine::QtOwnership)),
- can be used when setting the qObject() of an QObjectInterface
- as parent of the qobject-derived wrapper. If the QObject goes
- out of scope while running the script, the script object
- will stop working.
-
-A conversion cast to QScriptValue can then be provided.
-
-How to wrap functions:
-
-Most functions can then be implemented as slots, property-like
-things as such.
-
-The other functions have to be implemented via script-callbacks.
-(Parameter checking required).
-
-The templates in here can help in writing the wrapper
-objects. For examples, see
-
-src/plugins/core/scriptmanager/qworkbench_wrapper.h
diff --git a/src/shared/scriptwrapper/interface_wrap_helpers.h b/src/shared/scriptwrapper/interface_wrap_helpers.h
deleted file mode 100644
index 8a89e40e05e..00000000000
--- a/src/shared/scriptwrapper/interface_wrap_helpers.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef INTERFACE_WRAP_HELPERS_H
-#define INTERFACE_WRAP_HELPERS_H
-
-#include <QScriptEngine>
-
-namespace SharedTools {
-
-// Convert a QObjectInterface to Scriptvalue
-// To be registered as a magic creation function with qScriptRegisterMetaType().
-// (see registerQObjectInterface)
-
-template <class QObjectInterface>
-static QScriptValue qObjectInterfaceToScriptValue(QScriptEngine *engine, QObjectInterface* const &qoif)
-{
- if (!qoif)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- QObject *qObject = const_cast<QObjectInterface *>(qoif);
-
- const QScriptEngine::QObjectWrapOptions wrapOptions =
- QScriptEngine::ExcludeChildObjects|QScriptEngine::ExcludeSuperClassMethods|QScriptEngine::ExcludeSuperClassProperties;
- return engine->newQObject(qObject, QScriptEngine::QtOwnership, wrapOptions);
-}
-
-// Convert Scriptvalue back to QObjectInterface
-// To be registered as a magic conversion function with qScriptRegisterMetaType().
-// (see registerQObjectInterface)
-
-template <class QObjectInterface>
-static void scriptValueToQObjectInterface(const QScriptValue &sv, QObjectInterface *&p)
-{
- QObject *qObject = sv.toQObject();
- p = qobject_cast<QObjectInterface*>(qObject);
-}
-
-// Magically register a Workbench interface derived from
-// ExtensionSystem::QObjectInterface class with the engine.
-// To avoid lifecycle issues, the script value is created on the QObject returned
-// by ExtensionSystem::QObjectInterface::qObject() and given the specified
-// prototype. By convention, ExtensionSystem::QObjectInterface::qObject() returns an
-// QObject that implements the interface, so it can be casted to it.
-
-template <class QObjectInterface, class Prototype>
-static void registerQObjectInterface(QScriptEngine *engine)
-{
- Prototype *protoType = new Prototype(engine);
- const QScriptValue scriptProtoType = engine->newQObject(protoType);
-
- const int metaTypeId = qScriptRegisterMetaType<QObjectInterface*>(
- engine,
- qObjectInterfaceToScriptValue<QObjectInterface>,
- scriptValueToQObjectInterface<QObjectInterface>,
- scriptProtoType);
- Q_UNUSED(metaTypeId)
-}
-
-} // namespace SharedTools
-
-#endif // INTERFACE_WRAP_HELPERS_H
diff --git a/src/shared/scriptwrapper/scriptwrapper.pri b/src/shared/scriptwrapper/scriptwrapper.pri
deleted file mode 100644
index 49c7d607cfc..00000000000
--- a/src/shared/scriptwrapper/scriptwrapper.pri
+++ /dev/null
@@ -1,3 +0,0 @@
-INCLUDEPATH *= $$PWD
-
-HEADERS += $$PWD/wrap_helpers.h
diff --git a/src/shared/scriptwrapper/wrap_helpers.h b/src/shared/scriptwrapper/wrap_helpers.h
deleted file mode 100644
index cd2d32ecbea..00000000000
--- a/src/shared/scriptwrapper/wrap_helpers.h
+++ /dev/null
@@ -1,332 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 The Qt Company Ltd.
-** Contact: http://www.qt.io/licensing
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms and
-** conditions see http://www.qt.io/terms-conditions. For further information
-** use the contact form at http://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 or version 3 as published by the Free
-** Software Foundation and appearing in the file LICENSE.LGPLv21 and
-** LICENSE.LGPLv3 included in the packaging of this file. Please review the
-** following information to ensure the GNU Lesser General Public License
-** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
-** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, The Qt Company gives you certain additional
-** rights. These rights are described in The Qt Company LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef WRAP_HELPERS_H
-#define WRAP_HELPERS_H
-
-#include <QScriptEngine>
-#include <QScriptContext>
-#include <QScriptValue>
-
-namespace SharedTools {
-
-// Strip a const ref from a type via template specialization trick.
-// Use for determining function call args
-
-template <class T>
- struct RemoveConstRef {
- typedef T Result;
- };
-
-template <class T>
- struct RemoveConstRef<const T &> {
- typedef T Result;
- };
-
-// Template that retrieves a QObject-derived class from a QScriptValue.
-
-template <class QObjectDerived>
- QObjectDerived *qObjectFromScriptValue(const QScriptValue &v)
-{
- if (!v.isQObject())
- return 0;
- QObject *o = v.toQObject();
- return qobject_cast<QObjectDerived *>(o);
-}
-
-// Template that retrieves a wrapped object from a QScriptValue.
-// The wrapped object is accessed through an accessor of
-// the QObject-derived wrapper.
-
-template <class Wrapper, class Wrapped>
- Wrapped *wrappedFromScriptValue(const QScriptValue &v,
- Wrapped * (Wrapper::*wrappedAccessor) () const)
-{
- Wrapper *wrapper = qObjectFromScriptValue<Wrapper>(v);
- if (!wrapper)
- return 0;
- return (wrapper->*wrappedAccessor)();
-}
-
-// Template that retrieves a wrapped object from
-// a QObject-derived script wrapper object that is set as 'this' in
-// a script context via accessor.
-
-template <class Wrapper, class Wrapped>
- static inline Wrapped *wrappedThisFromContext(QScriptContext *context,
- Wrapped * (Wrapper::*wrappedAccessor) () const)
-{
- Wrapped *wrapped = wrappedFromScriptValue(context->thisObject(), wrappedAccessor);
- Q_ASSERT(wrapped);
- return wrapped;
-}
-
-// Template that retrieves an object contained in a wrapped object
-// in a script getter call (namely the interfaces returned by
-// the core interface accessors). Mangles out the wrapper object from
-// thisObject(), accesses the wrapped object and returns the contained object.
-
-template <class Contained, class Wrapper, class Wrapped>
- static inline Contained *containedFromContext(QScriptContext *context,
- Wrapped * (Wrapper::*wrappedAccessor) () const,
- Contained * (Wrapped::*containedAccessor)() const)
-{
- Wrapped *wrapped = wrappedThisFromContext(context, wrappedAccessor);
- return (wrapped->*containedAccessor)();
-}
-
-// Template that retrieves a contained QObject-type object
-// in a script getter call and creates a new script-object via engine->newQObject().
-// To be called from a script getter callback.
-
-template <class Contained, class Wrapper, class Wrapped>
- static inline QScriptValue containedQObjectFromContextToScriptValue(QScriptContext *context, QScriptEngine *engine,
- Wrapped * (Wrapper::*wrappedAccessor) () const,
- Contained * (Wrapped::*containedAccessor)() const)
-{
- return engine->newQObject(containedFromContext(context, wrappedAccessor, containedAccessor));
-}
-
-// Template that retrieves a contained Non-QObject-type object
-// in a script getter call and creates a new script-object by wrapping it into
-// a new instance of ContainedWrapper (which casts to QScriptValue).
-// To be called from a script getter callback.
-
-template <class ContainedWrapper, class Contained, class Wrapper, class Wrapped>
- static inline QScriptValue wrapContainedFromContextAsScriptValue(QScriptContext *context, QScriptEngine *engine,
- Wrapped * (Wrapper::*wrappedAccessor) () const,
- Contained * (Wrapped::*containedAccessor)() const)
-{
- Contained *c = containedFromContext(context, wrappedAccessor, containedAccessor);
- if (!c)
- return QScriptValue(engine, QScriptValue::NullValue);
-
- ContainedWrapper *cw = new ContainedWrapper(*engine, c);
- return *cw; // cast to QScriptValue
-}
-
-// Template that retrieves a wrapped object from context (this)
-// and calls a const-member function with no parameters.
-// To be called from a script getter callback.
-
-template <class Ret, class Wrapper, class Wrapped>
- static inline QScriptValue scriptCallConstMember_0(QScriptContext *context, QScriptEngine *engine,
- Wrapped * (Wrapper::*wrappedAccessor) () const,
- Ret (Wrapped::*member)() const)
-{
- Wrapped *wrapped = wrappedThisFromContext(context, wrappedAccessor);
- return engine->toScriptValue( (wrapped->*member)() );
-}
-
-// Ditto for non-const
-
-template <class Ret, class Wrapper, class Wrapped>
- static inline QScriptValue scriptCallMember_0(QScriptContext *context, QScriptEngine *engine,
- Wrapped * (Wrapper::*wrappedAccessor) () const,
- Ret (Wrapped::*member)())
-{
- Wrapped *wrapped = wrappedThisFromContext(context, wrappedAccessor);
- return engine->toScriptValue( (wrapped->*member)() );
-}
-
-// Template that retrieves a wrapped object from context (this)
-// and calls a const-member function with 1 parameter on it.
-// To be called from a script getter callback.
-
-template <class Ret, class Argument, class Wrapper, class Wrapped>
- static inline QScriptValue scriptCallConstMember_1(QScriptContext *context, QScriptEngine *engine,
- Wrapped * (Wrapper::*wrappedAccessor) () const,
- Ret (Wrapped::*member)(Argument a1) const)
-{
- const int argumentCount = context->argumentCount();
- if ( argumentCount != 1)
- return QScriptValue (engine, QScriptValue::NullValue);
-
- Wrapped *wrapped = wrappedThisFromContext(context, wrappedAccessor);
- // call member. If the argument is a const ref, strip it.
- typedef typename RemoveConstRef<Argument>::Result ArgumentBase;
- ArgumentBase a = qscriptvalue_cast<ArgumentBase>(context->argument(0));
- return engine->toScriptValue( (wrapped->*member)(a) );
-}
-
-// Template that retrieves a wrapped object
-// and calls a member function with 1 parameter on it.
-// To be called from a script getter callback.
-
-template <class Ret, class Argument, class Wrapper, class Wrapped>
- static inline QScriptValue scriptCallMember_1(QScriptContext *context, QScriptEngine *engine,
- Wrapped * (Wrapper::*wrappedAccessor) () const,
- Ret (Wrapped::*member)(Argument a1))
-{
- const int argumentCount = context->argumentCount();
- if ( argumentCount != 1)
- return QScriptValue (engine, QScriptValue::NullValue);
-
- Wrapped *wrapped = wrappedThisFromContext(context, wrappedAccessor);
- // call member. If the argument is a const ref, strip it.
- typedef typename RemoveConstRef<Argument>::Result ArgumentBase;
- ArgumentBase a = qscriptvalue_cast<ArgumentBase>(context->argument(0));
- return engine->toScriptValue( (wrapped->*member)(a) );
-}
-
-// Template that retrieves a wrapped object
-// and calls a void member function with 1 parameter that is a wrapper of
-// of some interface.
-// Typically used for something like 'setCurrentEditor(Editor*)'
-// To be called from a script callback.
-
-template <class ThisWrapper, class ThisWrapped, class ArgumentWrapper, class ArgumentWrapped>
-static QScriptValue scriptCallVoidMember_Wrapped1(QScriptContext *context, QScriptEngine *engine,
- ThisWrapped * (ThisWrapper::*thisWrappedAccessor) () const,
- ArgumentWrapped *(ArgumentWrapper::*argumentWrappedAccessor)() const,
- void (ThisWrapped::*member)(ArgumentWrapped *a1),
- bool acceptNullArgument = false)
-{
- const QScriptValue voidRC = QScriptValue(engine, QScriptValue::UndefinedValue);
- if (context->argumentCount() < 1)
- return voidRC;
-
- ThisWrapped *thisWrapped = wrappedThisFromContext(context, thisWrappedAccessor);
- ArgumentWrapped *aw = wrappedFromScriptValue(context->argument(0), argumentWrappedAccessor);
- if (acceptNullArgument || aw)
- (thisWrapped->*member)(aw);
- return voidRC;
-}
-
-// Macros that define the static functions to call members
-
-#define SCRIPT_CALL_CONST_MEMBER_0(funcName, accessor, member) \
-static QScriptValue funcName(QScriptContext *context, QScriptEngine *engine) \
-{ return SharedTools::scriptCallConstMember_0(context, engine, accessor, member); }
-
-#define SCRIPT_CALL_MEMBER_0(funcName, accessor, member) \
-static QScriptValue funcName(QScriptContext *context, QScriptEngine *engine) \
-{ return SharedTools::scriptCallMember_0(context, engine, accessor, member); }
-
-#define SCRIPT_CALL_CONST_MEMBER_1(funcName, accessor, member) \
-static QScriptValue funcName(QScriptContext *context, QScriptEngine *engine) \
-{ return SharedTools::scriptCallConstMember_1(context, engine, accessor, member); }
-
-#define SCRIPT_CALL_MEMBER_1(funcName, accessor, member) \
-static QScriptValue funcName(QScriptContext *context, QScriptEngine *engine) \
-{ return SharedTools::scriptCallMember_1(context, engine, accessor, member); }
-
-// Create a script list of wrapped non-qobjects by wrapping them.
-// Wrapper must cast to QScriptValue.
-
-template <class Wrapper, class Iterator>
- static inline QScriptValue wrapObjectList( QScriptEngine *engine, Iterator i1, Iterator i2)
-{
- QScriptValue rc = engine->newArray(i2 - i1); // Grrr!
- quint32 i = 0;
- for ( ; i1 != i2 ; ++i1, i++) {
- Wrapper * wrapper = new Wrapper(*engine, *i1);
- rc.setProperty(i, *wrapper);
- }
- return rc;
-}
-
-// Unwrap a list of wrapped objects from a script list.
-
-template <class Wrapper, class Wrapped>
- static inline QList<Wrapped*> unwrapObjectList(const QScriptValue &v,
- Wrapped *(Wrapper::*wrappedAccessor)() const)
-{
- QList<Wrapped*> rc;
-
- if (!v.isArray())
- return rc;
-
- const quint32 len = v.property(QLatin1String("length")).toUInt32();
- if (!len)
- return rc;
-
- for (quint32 i = 0; i < len; i++) {
- const QScriptValue e = v.property(i);
- if (e.isQObject()) {
- QObject *o = e.toQObject();
- if (Wrapper * wrapper = qobject_cast<Wrapper *>(o))
- rc.push_back((wrapper->*wrappedAccessor)());
- }
- }
- return rc;
-}
-
-// Traditional registration of a prototype for an interface.
-// that can be converted via script value casts via Q_DECLARE_METATYPE.
-
-template <class Interface, class Prototype>
- static void registerInterfaceWithDefaultPrototype(QScriptEngine &engine)
-{
- Prototype *protoType = new Prototype(&engine);
- const QScriptValue scriptProtoType = engine.newQObject(protoType);
-
- engine.setDefaultPrototype(qMetaTypeId<Interface*>(), scriptProtoType);
-}
-
-// Convert a class derived from QObject to Scriptvalue via engine->newQObject() to make
-// the signals, slots and properties visible.
-// To be registered as a magic creation function with qScriptRegisterMetaType().
-// (see registerQObject()
-
-template <class SomeQObject>
-static QScriptValue qObjectToScriptValue(QScriptEngine *engine, SomeQObject * const &qo)
-{
- return engine->newQObject(qo, QScriptEngine::QtOwnership, QScriptEngine::ExcludeChildObjects);
-}
-
-// Convert Scriptvalue back to a class derived from QObject via QScriptValue::toQObject()
-// To be registered as a magic conversion function with qScriptRegisterMetaType().
-// (see registerQObject)
-
-template <class SomeQObject>
-static void scriptValueToQObject(const QScriptValue &sv, SomeQObject * &p)
-{
- QObject *qObject = sv.toQObject();
- p = qobject_cast<SomeQObject*>(qObject);
- Q_ASSERT(p);
-}
-
-// Register a QObject-derived class which has Q_DECLARE_METATYPE(Ptr*)
-// with the engine using qObjectToScriptValue/scriptValueToQObject as
-// conversion functions to make it possible to use for example
-// Q_PROPERTY(QMainWindow*).
-
-template <class SomeQObject>
-static void registerQObject(QScriptEngine *engine)
-{
- qScriptRegisterMetaType<SomeQObject*>(engine,
- qObjectToScriptValue<SomeQObject>,
- scriptValueToQObject<SomeQObject>);
-}
-
-} // namespace SharedTools
-
-#endif // WRAP_HELPERS_H
diff --git a/src/src.qbs b/src/src.qbs
index 0ef11cb4a01..34118460ac9 100644
--- a/src/src.qbs
+++ b/src/src.qbs
@@ -21,6 +21,7 @@ Project {
id: qbsProject
property string qbsBaseDir: path + "/shared/qbs"
condition: qbsSubModuleExists && !useExternalQbs
+ qbsSearchPaths: [qbsBaseDir + "/qbs-resources"]
property bool enableUnitTests: false
property bool enableProjectFileUpdates: true
diff --git a/src/tools/3rdparty/iossim/iossim.pro b/src/tools/3rdparty/iossim/iossim.pro
index 413ad342ff2..3b67b2d8cc5 100644
--- a/src/tools/3rdparty/iossim/iossim.pro
+++ b/src/tools/3rdparty/iossim/iossim.pro
@@ -11,7 +11,7 @@ include(../../../../qtcreator.pri)
# Prevent from popping up in the dock when launched.
# We embed the Info.plist file, so the application doesn't need to
# be a bundle.
-QMAKE_LFLAGS += -sectcreate __TEXT __info_plist \"$$PWD/Info.plist\" \
+QMAKE_LFLAGS += -Wl,-sectcreate,__TEXT,__info_plist,\"$$PWD/Info.plist\"
-fobjc-link-runtime
LIBS += \
diff --git a/src/tools/3rdparty/iossim_1_8_2/iossim_1_8_2.pro b/src/tools/3rdparty/iossim_1_8_2/iossim_1_8_2.pro
index 773776ab7c1..f1439be4a14 100644
--- a/src/tools/3rdparty/iossim_1_8_2/iossim_1_8_2.pro
+++ b/src/tools/3rdparty/iossim_1_8_2/iossim_1_8_2.pro
@@ -10,7 +10,7 @@ include(../../../../qtcreator.pri)
# Prevent from popping up in the dock when launched.
# We embed the Info.plist file, so the application doesn't need to
# be a bundle.
-QMAKE_LFLAGS += -sectcreate __TEXT __info_plist \"$$PWD/Info.plist\" \
+QMAKE_LFLAGS += -Wl,-sectcreate,__TEXT,__info_plist,\"$$PWD/Info.plist\" \
-fobjc-link-runtime
LIBS += \
diff --git a/src/tools/cplusplus-ast2png/cplusplus-ast2png.cpp b/src/tools/cplusplus-ast2png/cplusplus-ast2png.cpp
new file mode 100644
index 00000000000..490065e2672
--- /dev/null
+++ b/src/tools/cplusplus-ast2png/cplusplus-ast2png.cpp
@@ -0,0 +1,653 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include <cplusplus/AST.h>
+#include <cplusplus/ASTMatcher.h>
+#include <cplusplus/ASTPatternBuilder.h>
+#include <cplusplus/ASTVisitor.h>
+#include <cplusplus/Control.h>
+#include <cplusplus/CoreTypes.h>
+#include <cplusplus/CppDocument.h>
+#include <cplusplus/Literals.h>
+#include <cplusplus/Names.h>
+#include <cplusplus/Overview.h>
+#include <cplusplus/Scope.h>
+#include <cplusplus/SymbolVisitor.h>
+#include <cplusplus/Symbols.h>
+#include <cplusplus/TranslationUnit.h>
+
+#include "utils.h"
+
+#include <QDir>
+#include <QFile>
+#include <QList>
+#include <QCoreApplication>
+#include <QStringList>
+#include <QFileInfo>
+#include <QTime>
+#include <QDebug>
+
+#include <cstdio>
+#include <cstdlib>
+#include <fstream>
+#include <iostream>
+#include <string>
+#ifdef __GNUC__
+# include <cxxabi.h>
+#endif
+
+// For isatty(), _isatty()
+#if defined(Q_OS_WIN)
+# include <io.h>
+#else
+# include <unistd.h>
+#endif
+
+bool tty_for_stdin()
+{
+#if defined(Q_OS_WIN)
+ return _isatty(_fileno(stdin));
+#else
+ return isatty(fileno(stdin));
+#endif
+}
+
+using namespace CPlusPlus;
+
+class ASTDump: protected ASTVisitor
+{
+public:
+ ASTDump(TranslationUnit *unit)
+ : ASTVisitor(unit) {}
+
+ void operator()(AST *ast) {
+ QByteArray basename = translationUnit()->fileName();
+ basename.append(".ast.dot");
+ out.open(basename.constData());
+
+ out << "digraph AST { ordering=out;" << std::endl;
+ // std::cout << "rankdir = \"LR\";" << std::endl;
+
+ generateTokens();
+ accept(ast);
+
+ typedef QPair<QByteArray, QByteArray> Pair;
+
+ foreach (const Pair &conn, _connections)
+ out << conn.first.constData() << " -> " << conn.second.constData() << std::endl;
+
+ alignTerminals();
+
+ out << "}" << std::endl;
+ out.close();
+ }
+
+ // the following file can be generated by using:
+ // cplusplus-update-frontend <frontend-dir> <dumpers-file>
+#include "dumpers.inc"
+
+protected:
+ void alignTerminals() {
+ out<<"{ rank=same;" << std::endl;
+ foreach (const QByteArray &terminalShape, _terminalShapes) {
+ out << " " << std::string(terminalShape.constData(), terminalShape.size()).c_str() << ";" << std::endl;
+ }
+ out<<"}"<<std::endl;
+ }
+
+ static QByteArray name(AST *ast) {
+#ifdef __GNUC__
+ QByteArray name = abi::__cxa_demangle(typeid(*ast).name(), 0, 0, 0) + 11;
+ name.truncate(name.length() - 3);
+#else
+ QByteArray name = typeid(*ast).name();
+#endif
+ return name;
+ }
+
+ QByteArray terminalId(unsigned token)
+ { return 't' + QByteArray::number(token); }
+
+ void terminal(unsigned token, AST *node) {
+ _connections.append(qMakePair(_id[node], terminalId(token)));
+ }
+
+ void generateTokens() {
+ for (unsigned token = 1; token < translationUnit()->tokenCount(); ++token) {
+ if (translationUnit()->tokenKind(token) == T_EOF_SYMBOL)
+ break;
+
+ QByteArray t;
+
+ t.append(terminalId(token));
+ t.append(" [shape=rect label = \"");
+ t.append(spell(token));
+ t.append("\"]");
+
+ if (token > 1) {
+ t.append("; ");
+ t.append(terminalId(token - 1));
+ t.append(" -> ");
+ t.append(terminalId(token));
+ t.append(" [arrowhead=\"vee\" color=\"transparent\"]");
+ }
+
+ _terminalShapes.append(t);
+ }
+ }
+
+ virtual void nonterminal(AST *ast) {
+ accept(ast);
+ }
+
+ virtual void node(AST *ast) {
+ out << _id[ast].constData() << " [label=\"" << name(ast).constData() << "\"];" << std::endl;
+ }
+
+ virtual bool preVisit(AST *ast) {
+ static int count = 1;
+ const QByteArray id = 'n' + QByteArray::number(count++);
+ _id[ast] = id;
+
+
+ if (! _stack.isEmpty())
+ _connections.append(qMakePair(_id[_stack.last()], id));
+
+ _stack.append(ast);
+
+ node(ast);
+
+ return true;
+ }
+
+ virtual void postVisit(AST *) {
+ _stack.removeLast();
+ }
+
+private:
+ QHash<AST *, QByteArray> _id;
+ QList<QPair<QByteArray, QByteArray> > _connections;
+ QList<AST *> _stack;
+ QList<QByteArray> _terminalShapes;
+ std::ofstream out;
+};
+
+class SymbolDump: protected SymbolVisitor
+{
+public:
+ SymbolDump(TranslationUnit *unit)
+ : translationUnit(unit)
+ {
+ o.showArgumentNames = true;
+ o.showFunctionSignatures = true;
+ o.showReturnTypes = true;
+ }
+
+ void operator()(Symbol *s) {
+ QByteArray basename = translationUnit->fileName();
+ basename.append(".symbols.dot");
+ out.open(basename.constData());
+
+ out << "digraph Symbols { ordering=out;" << std::endl;
+ // std::cout << "rankdir = \"LR\";" << std::endl;
+ accept(s);
+
+ for (int i = 0; i < _connections.size(); ++i) {
+ QPair<Symbol*,Symbol*> connection = _connections.at(i);
+ QByteArray from = _id.value(connection.first);
+ if (from.isEmpty())
+ from = name(connection.first);
+ QByteArray to = _id.value(connection.second);
+ if (to.isEmpty())
+ to = name(connection.second);
+ out << from.constData() << " -> " << to.constData() << ";" << std::endl;
+ }
+
+ out << "}" << std::endl;
+ out.close();
+ }
+
+protected:
+ QByteArray name(Symbol *s) {
+#ifdef __GNUC__
+ QByteArray result = abi::__cxa_demangle(typeid(*s).name(), 0, 0, 0) + 11;
+#else
+ QByteArray result = typeid(*s).name();
+#endif
+ if (s->identifier()) {
+ result.append("\\nid: ");
+ result.append(s->identifier()->chars());
+ }
+ if (s->isDeprecated())
+ result.append("\\n(deprecated)");
+
+ return result;
+ }
+
+ virtual bool preVisit(Symbol *s) {
+ static int count = 0;
+ QByteArray nodeId("s");
+ nodeId.append(QByteArray::number(++count));
+ _id[s] = nodeId;
+
+ if (!_stack.isEmpty())
+ _connections.append(qMakePair(_stack.last(), s));
+
+ _stack.append(s);
+
+ return true;
+ }
+
+ virtual void postVisit(Symbol *) {
+ _stack.removeLast();
+ }
+
+ virtual void simpleNode(Symbol *symbol) {
+ out << _id[symbol].constData() << " [label=\"" << name(symbol).constData() << "\"];" << std::endl;
+ }
+
+ virtual bool visit(Class *symbol) {
+ const char *id = _id.value(symbol).constData();
+ out << id << " [label=\"";
+ if (symbol->isClass()) {
+ out << "class";
+ } else if (symbol->isStruct()) {
+ out << "struct";
+ } else if (symbol->isUnion()) {
+ out << "union";
+ } else {
+ out << "UNKNOWN";
+ }
+
+ out << "\\nid: ";
+ if (symbol->identifier()) {
+ out << symbol->identifier()->chars();
+ } else {
+ out << "NO ID";
+ }
+ if (symbol->isDeprecated())
+ out << "\\n(deprecated)";
+ out << "\"];" << std::endl;
+
+ return true;
+ }
+
+ virtual bool visit(UsingNamespaceDirective *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(UsingDeclaration *symbol) { simpleNode(symbol); return true; }
+
+ virtual bool visit(Declaration *symbol) {
+ out << _id[symbol].constData() << " [label=\"";
+ out << "Declaration\\n";
+ out << qPrintable(o(symbol->name()));
+ out << ": ";
+ out << qPrintable(o(symbol->type()));
+ if (symbol->isDeprecated())
+ out << "\\n(deprecated)";
+ if (Function *funTy = symbol->type()->asFunctionType()) {
+ if (funTy->isPureVirtual())
+ out << "\\n(pure virtual)";
+ else if (funTy->isVirtual())
+ out << "\\n(virtual)";
+
+ if (funTy->isSignal())
+ out << "\\n(signal)";
+ if (funTy->isSlot())
+ out << "\\n(slot)";
+ if (funTy->isInvokable())
+ out << "\\n(invokable)";
+ }
+ out << "\"];" << std::endl;
+
+ return true;
+ }
+
+ virtual bool visit(Argument *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(TypenameArgument *symbol) { simpleNode(symbol); return true; }
+
+ virtual bool visit(BaseClass *symbol) {
+ out << _id[symbol].constData() << " [label=\"BaseClass\\n";
+ out << qPrintable(o(symbol->name()));
+ if (symbol->isDeprecated())
+ out << "\\n(deprecated)";
+ out << "\"];" << std::endl;
+
+ return true;
+ }
+
+ virtual bool visit(Enum *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(Function *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(Namespace *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(Block *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ForwardClassDeclaration *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCBaseClass *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCBaseProtocol *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCClass *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCForwardClassDeclaration *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCProtocol *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCForwardProtocolDeclaration *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCMethod *symbol) { simpleNode(symbol); return true; }
+ virtual bool visit(ObjCPropertyDeclaration *symbol) { simpleNode(symbol); return true; }
+
+private:
+ TranslationUnit *translationUnit;
+ QHash<Symbol *, QByteArray> _id;
+ QList<QPair<Symbol *,Symbol*> >_connections;
+ QList<Symbol *> _stack;
+ std::ofstream out;
+ Overview o;
+};
+
+static void createImageFromDot(const QString &inputFile, const QString &outputFile, bool verbose)
+{
+ const QString command = CplusplusToolsUtils::portableExecutableName(QLatin1String("dot"));
+ const QStringList arguments = QStringList()
+ << QLatin1String("-Tpng") << QLatin1String("-o") << outputFile << inputFile;
+ CplusplusToolsUtils::executeCommand(command, arguments, QString(), verbose);
+}
+
+static const char PATH_STDIN_FILE[] = "_stdincontents.cpp";
+
+static QString example()
+{
+ return
+#if defined(Q_OS_WIN)
+ QString::fromLatin1("> echo int foo() {} | %1 && %2.ast.png")
+#elif defined(Q_OS_MAC)
+ QString::fromLatin1("$ echo \"int foo() {}\" | ./%1 && open %2.ast.png")
+#else
+ QString::fromLatin1("$ echo \"int foo() {}\" | ./%1 && xdg-open %2.ast.png")
+#endif
+ .arg(QFileInfo(qApp->arguments().at(0)).fileName(), QLatin1String(PATH_STDIN_FILE));
+}
+
+static QString parseModeToString(Document::ParseMode parseMode)
+{
+ switch (parseMode) {
+ case Document::ParseTranlationUnit:
+ return QLatin1String("TranlationUnit");
+ case Document::ParseDeclaration:
+ return QLatin1String("Declaration");
+ case Document::ParseExpression:
+ return QLatin1String("Expression");
+ case Document::ParseDeclarator:
+ return QLatin1String("Declarator");
+ case Document::ParseStatement:
+ return QLatin1String("Statement");
+ default:
+ return QLatin1String("UnknownParseMode");
+ }
+}
+
+/// Counts errors and appends error messages containing the parse mode to an error string
+class ErrorHandler: public DiagnosticClient {
+public:
+ int m_errorCount;
+ QByteArray *m_errorString;
+ Document::ParseMode m_parseMode;
+
+ ErrorHandler(Document::ParseMode parseMode, QByteArray *errorStringOutput)
+ : m_errorCount(0)
+ , m_errorString(errorStringOutput)
+ , m_parseMode(parseMode) {}
+
+ void report(int level,
+ const StringLiteral *fileName,
+ unsigned line, unsigned column,
+ const char *format, va_list ap)
+ {
+ ++m_errorCount;
+
+ if (! m_errorString)
+ return;
+
+ static const char *const pretty[] = { "warning", "error", "fatal" };
+
+ QString str;
+ str.sprintf("%s:%d:%d: When parsing as %s: %s: ", fileName->chars(), line, column,
+ parseModeToString(m_parseMode).toUtf8().constData(), pretty[level]);
+ m_errorString->append(str.toUtf8());
+
+ str.vsprintf(format, ap);
+ m_errorString->append(str.toUtf8());
+ m_errorString->append('\n');
+ }
+};
+
+/// Try to parse with given parseModes. Returns a document pointer if it was possible to
+/// successfully parse with one of the given parseModes (one parse mode after the other
+/// is tried), otherwise a null pointer.
+static Document::Ptr parse(const QString &fileName, const QByteArray &source,
+ QList<Document::ParseMode> parseModes, QByteArray *errors,
+ bool verbose = false)
+{
+ foreach (const Document::ParseMode parseMode, parseModes) {
+ ErrorHandler *errorHandler = new ErrorHandler(parseMode, errors); // Deleted by ~Document.
+ if (verbose)
+ std::cout << "Parsing as " << qPrintable(parseModeToString(parseMode)) << "...";
+
+ Document::Ptr doc = Document::create(fileName);
+ doc->control()->setDiagnosticClient(errorHandler);
+ doc->setUtf8Source(source);
+ const bool parsed = doc->parse(parseMode);
+ if (parsed && errorHandler->m_errorCount == 0) {
+ if (verbose)
+ std::cout << "succeeded." << std::endl;
+ return doc;
+ }
+
+ if (verbose)
+ std::cout << "failed." << std::endl;
+ }
+
+ return Document::Ptr();
+}
+
+/// Convenience function
+static Document::Ptr parse(const QString &fileName, const QByteArray &source,
+ Document::ParseMode parseMode, QByteArray *errors,
+ bool verbose = false)
+{
+ QList<Document::ParseMode> parseModes = QList<Document::ParseMode>() << parseMode;
+ return parse(fileName, source, parseModes, errors, verbose);
+}
+
+static void printUsage()
+{
+ std::cout << "Usage: " << qPrintable(QFileInfo(qApp->arguments().at(0)).fileName())
+ << " [-v] [-p ast] <file1> <file2> ...\n\n";
+
+ std::cout
+ << "Visualize AST and symbol hierarchy of given C++ files by generating png image files\n"
+ << "in the same directory as the input files. Print paths to generated image files.\n"
+ << "\n"
+ << "Options:\n"
+ << " -v Run with increased verbosity.\n"
+ << " -p <ast> Parse each file as <ast>. <ast> is one of:\n"
+ << " - 'declarator' or 'dr'\n"
+ << " - 'expression' or 'ex'\n"
+ << " - 'declaration' or 'dn'\n"
+ << " - 'statement' or 'st'\n"
+ << " - 'translationunit' or 'tr'\n"
+ << " If this option is not provided, each file is tried to be parsed as\n"
+ << " declarator, expression, etc. using the stated order.\n"
+ << "\n";
+
+ std::cout << QString::fromLatin1(
+ "Standard input is also read. The resulting files start with \"%1\"\n"
+ "and are created in the current working directory. To show the AST for simple snippets\n"
+ "you might want to execute:\n"
+ "\n"
+ " %2\n"
+ "\n"
+ "Prerequisites:\n"
+ " 1) Make sure to have 'dot' from graphviz locatable by PATH.\n"
+ " 2) Make sure to have an up to date dumpers file by using 'cplusplus-update-frontend'.\n"
+ ).arg(QLatin1String(PATH_STDIN_FILE), example()).toLocal8Bit().constData();
+}
+
+int main(int argc, char *argv[])
+{
+ QCoreApplication app(argc, argv);
+ QStringList args = app.arguments();
+ args.removeFirst();
+
+ bool optionVerbose = false;
+ int optionParseMode = -1;
+
+ // Test only for stdin if not input files are specified.
+ const bool doTestForStdIn = args.isEmpty()
+ || (args.count() == 1 && args.contains(QLatin1String("-v")));
+ if (doTestForStdIn && !tty_for_stdin()) {
+ QFile file((QLatin1String(PATH_STDIN_FILE)));
+ if (! file.open(QFile::WriteOnly)) {
+ std::cerr << "Error: Cannot open file for writing\"" << qPrintable(file.fileName())
+ << "\"" << std::endl;
+ exit(EXIT_FAILURE);
+ }
+ file.write(QTextStream(stdin).readAll().toLocal8Bit());
+ file.close();
+ args.append(file.fileName());
+ }
+
+ // Process options & arguments
+ const bool helpRequested = args.contains(QLatin1String("-h"))
+ || args.contains(QLatin1String("-help"));
+ if (helpRequested) {
+ printUsage();
+ return helpRequested ? EXIT_SUCCESS : EXIT_FAILURE;
+ }
+
+ if (args.contains(QLatin1String("-v"))) {
+ optionVerbose = true;
+ args.removeOne(QLatin1String("-v"));
+ }
+ if (args.contains(QLatin1String("-p"))) {
+ args.removeOne(QLatin1String("-p"));
+ if (args.isEmpty()) {
+ std::cerr << "Error: Expected ast after option \"-p\"." << std::endl;
+ printUsage();
+ exit(EXIT_FAILURE);
+ }
+ const QString parseAs = args.first();
+ if (parseAs == QLatin1String("declarator") || parseAs == QLatin1String("dr")) {
+ optionParseMode = Document::ParseDeclarator;
+ } else if (parseAs == QLatin1String("expression") || parseAs == QLatin1String("ex")) {
+ optionParseMode = Document::ParseExpression;
+ } else if (parseAs == QLatin1String("declaration") || parseAs == QLatin1String("dn")) {
+ optionParseMode = Document::ParseDeclaration;
+ } else if (parseAs == QLatin1String("statement") || parseAs == QLatin1String("st")) {
+ optionParseMode = Document::ParseStatement;
+ } else if (parseAs == QLatin1String("translationunit") || parseAs == QLatin1String("tr")) {
+ optionParseMode = Document::ParseTranlationUnit;
+ } else {
+ std::cerr << "Error: Invalid ast for option \"-p\"." << std::endl;
+ printUsage();
+ exit(EXIT_FAILURE);
+ }
+ args.removeOne(parseAs);
+ }
+
+ if (args.isEmpty()) {
+ printUsage();
+ return EXIT_SUCCESS;
+ }
+
+ // Process files
+ const QStringList files = args;
+ foreach (const QString &fileName, files) {
+ if (! QFile::exists(fileName)) {
+ std::cerr << "Error: File \"" << qPrintable(fileName) << "\" does not exist."
+ << std::endl;
+ exit(EXIT_FAILURE);
+ }
+
+ // Run the preprocessor
+ const QString fileNamePreprocessed = fileName + QLatin1String(".preprocessed");
+ CplusplusToolsUtils::SystemPreprocessor preprocessor(optionVerbose);
+ preprocessor.preprocessFile(fileName, fileNamePreprocessed);
+
+ // Convert to dot
+ QFile file(fileNamePreprocessed);
+ if (! file.open(QFile::ReadOnly)) {
+ std::cerr << "Error: Could not open file \"" << qPrintable(fileNamePreprocessed)
+ << "\"" << std::endl;
+ exit(EXIT_FAILURE);
+ }
+
+ const QByteArray source = file.readAll();
+ file.close();
+
+ // Parse Document
+ QByteArray errors;
+ Document::Ptr doc;
+ if (optionParseMode == -1) {
+ QList<Document::ParseMode> parseModes;
+ parseModes
+ << Document::ParseDeclarator
+ << Document::ParseExpression
+ << Document::ParseDeclaration
+ << Document::ParseStatement
+ << Document::ParseTranlationUnit;
+ doc = parse(fileName, source, parseModes, &errors, optionVerbose);
+ } else {
+ doc = parse(fileName, source, static_cast<Document::ParseMode>(optionParseMode),
+ &errors, optionVerbose);
+ }
+
+ if (!doc) {
+ std::cerr << "Error: Could not parse file \"" << qPrintable(fileName) << "\".\n";
+ std::cerr << errors.constData();
+ exit(EXIT_FAILURE);
+ }
+
+ doc->check();
+
+ // Run AST dumper
+ ASTDump dump(doc->translationUnit());
+ dump(doc->translationUnit()->ast());
+
+ SymbolDump dump2(doc->translationUnit());
+ dump2(doc->globalNamespace());
+
+ // Create images
+ typedef QPair<QString, QString> Pair;
+ QList<Pair> inputOutputFiles;
+ inputOutputFiles.append(qMakePair(QString(fileName + QLatin1String(".ast.dot")),
+ QString(fileName + QLatin1String(".ast.png"))));
+ inputOutputFiles.append(qMakePair(QString(fileName + QLatin1String(".symbols.dot")),
+ QString(fileName + QLatin1String(".symbols.png"))));
+ foreach (const Pair &pair, inputOutputFiles) {
+ createImageFromDot(pair.first, pair.second, optionVerbose);
+ std::cout << qPrintable(QDir::toNativeSeparators(pair.second)) << std::endl;
+ }
+ }
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/tools/cplusplus-ast2png/cplusplus-ast2png.pro b/src/tools/cplusplus-ast2png/cplusplus-ast2png.pro
new file mode 100644
index 00000000000..21781006848
--- /dev/null
+++ b/src/tools/cplusplus-ast2png/cplusplus-ast2png.pro
@@ -0,0 +1,4 @@
+include(../cplusplus-shared/tool.pri)
+include(../cplusplus-shared/utils.pri)
+
+SOURCES += cplusplus-ast2png.cpp
diff --git a/src/tools/cplusplus-ast2png/cplusplus-ast2png.qbs b/src/tools/cplusplus-ast2png/cplusplus-ast2png.qbs
new file mode 100644
index 00000000000..060176e2b30
--- /dev/null
+++ b/src/tools/cplusplus-ast2png/cplusplus-ast2png.qbs
@@ -0,0 +1,6 @@
+import "../cplusplus-shared/CPlusPlusToolUsingCustomUtils.qbs" as CPlusPlusToolUsingCustomUtils
+
+CPlusPlusToolUsingCustomUtils {
+ name: "cplusplus-ast2png"
+ files: base.concat(["cplusplus-ast2png.cpp"])
+}
diff --git a/src/tools/cplusplus-ast2png/dumpers.inc b/src/tools/cplusplus-ast2png/dumpers.inc
new file mode 100644
index 00000000000..5e5bb1a10b7
--- /dev/null
+++ b/src/tools/cplusplus-ast2png/dumpers.inc
@@ -0,0 +1,1743 @@
+// Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com>
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+//
+// W A R N I N G
+// -------------
+//
+// This file is automatically generated by "cplusplus-update-frontend".
+// Changes will be lost.
+//
+
+
+virtual bool visit(ObjCSelectorArgumentAST *ast)
+{
+ if (ast->name_token)
+ terminal(ast->name_token, ast);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCSelectorAST *ast)
+{
+ for (ObjCSelectorArgumentListAST *iter = ast->selector_argument_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(SimpleSpecifierAST *ast)
+{
+ if (ast->specifier_token)
+ terminal(ast->specifier_token, ast);
+ return false;
+}
+
+virtual bool visit(AlignmentSpecifierAST *ast)
+{
+ if (ast->align_token)
+ terminal(ast->align_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->typeIdExprOrAlignmentExpr);
+ if (ast->ellipses_token)
+ terminal(ast->ellipses_token, ast);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(GnuAttributeSpecifierAST *ast)
+{
+ if (ast->attribute_token)
+ terminal(ast->attribute_token, ast);
+ if (ast->first_lparen_token)
+ terminal(ast->first_lparen_token, ast);
+ if (ast->second_lparen_token)
+ terminal(ast->second_lparen_token, ast);
+ for (GnuAttributeListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->first_rparen_token)
+ terminal(ast->first_rparen_token, ast);
+ if (ast->second_rparen_token)
+ terminal(ast->second_rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(GnuAttributeAST *ast)
+{
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ if (ast->tag_token)
+ terminal(ast->tag_token, ast);
+ for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(TypeofSpecifierAST *ast)
+{
+ if (ast->typeof_token)
+ terminal(ast->typeof_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(DecltypeSpecifierAST *ast)
+{
+ if (ast->decltype_token)
+ terminal(ast->decltype_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(DeclaratorAST *ast)
+{
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ for (PtrOperatorListAST *iter = ast->ptr_operator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->core_declarator);
+ for (PostfixDeclaratorListAST *iter = ast->postfix_declarator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ for (SpecifierListAST *iter = ast->post_attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->initializer);
+ return false;
+}
+
+virtual bool visit(SimpleDeclarationAST *ast)
+{
+ if (ast->qt_invokable_token)
+ terminal(ast->qt_invokable_token, ast);
+ for (SpecifierListAST *iter = ast->decl_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ for (DeclaratorListAST *iter = ast->declarator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(EmptyDeclarationAST *ast)
+{
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(AccessDeclarationAST *ast)
+{
+ if (ast->access_specifier_token)
+ terminal(ast->access_specifier_token, ast);
+ if (ast->slots_token)
+ terminal(ast->slots_token, ast);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ return false;
+}
+
+virtual bool visit(QtObjectTagAST *ast)
+{
+ if (ast->q_object_token)
+ terminal(ast->q_object_token, ast);
+ return false;
+}
+
+virtual bool visit(QtPrivateSlotAST *ast)
+{
+ if (ast->q_private_slot_token)
+ terminal(ast->q_private_slot_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ if (ast->dptr_token)
+ terminal(ast->dptr_token, ast);
+ if (ast->dptr_lparen_token)
+ terminal(ast->dptr_lparen_token, ast);
+ if (ast->dptr_rparen_token)
+ terminal(ast->dptr_rparen_token, ast);
+ if (ast->comma_token)
+ terminal(ast->comma_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(QtPropertyDeclarationItemAST *ast)
+{
+ if (ast->item_name_token)
+ terminal(ast->item_name_token, ast);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(QtPropertyDeclarationAST *ast)
+{
+ if (ast->property_specifier_token)
+ terminal(ast->property_specifier_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->comma_token)
+ terminal(ast->comma_token, ast);
+ nonterminal(ast->type_id);
+ nonterminal(ast->property_name);
+ for (QtPropertyDeclarationItemListAST *iter = ast->property_declaration_item_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(QtEnumDeclarationAST *ast)
+{
+ if (ast->enum_specifier_token)
+ terminal(ast->enum_specifier_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (NameListAST *iter = ast->enumerator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(QtFlagsDeclarationAST *ast)
+{
+ if (ast->flags_specifier_token)
+ terminal(ast->flags_specifier_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (NameListAST *iter = ast->flag_enums_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(QtInterfaceNameAST *ast)
+{
+ nonterminal(ast->interface_name);
+ for (NameListAST *iter = ast->constraint_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(QtInterfacesDeclarationAST *ast)
+{
+ if (ast->interfaces_token)
+ terminal(ast->interfaces_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (QtInterfaceNameListAST *iter = ast->interface_name_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(AsmDefinitionAST *ast)
+{
+ if (ast->asm_token)
+ terminal(ast->asm_token, ast);
+ if (ast->volatile_token)
+ terminal(ast->volatile_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(BaseSpecifierAST *ast)
+{
+ if (ast->virtual_token)
+ terminal(ast->virtual_token, ast);
+ if (ast->access_specifier_token)
+ terminal(ast->access_specifier_token, ast);
+ nonterminal(ast->name);
+ return false;
+}
+
+virtual bool visit(IdExpressionAST *ast)
+{
+ nonterminal(ast->name);
+ return false;
+}
+
+virtual bool visit(CompoundExpressionAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->statement);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(CompoundLiteralAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->type_id);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->initializer);
+ return false;
+}
+
+virtual bool visit(QtMethodAST *ast)
+{
+ if (ast->method_token)
+ terminal(ast->method_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->declarator);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(QtMemberDeclarationAST *ast)
+{
+ if (ast->q_token)
+ terminal(ast->q_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->type_id);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(BinaryExpressionAST *ast)
+{
+ nonterminal(ast->left_expression);
+ if (ast->binary_op_token)
+ terminal(ast->binary_op_token, ast);
+ nonterminal(ast->right_expression);
+ return false;
+}
+
+virtual bool visit(CastExpressionAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->type_id);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(ClassSpecifierAST *ast)
+{
+ if (ast->classkey_token)
+ terminal(ast->classkey_token, ast);
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->name);
+ if (ast->final_token)
+ terminal(ast->final_token, ast);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ for (BaseSpecifierListAST *iter = ast->base_clause_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ if (ast->lbrace_token)
+ terminal(ast->lbrace_token, ast);
+ for (DeclarationListAST *iter = ast->member_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rbrace_token)
+ terminal(ast->rbrace_token, ast);
+ return false;
+}
+
+virtual bool visit(CaseStatementAST *ast)
+{
+ if (ast->case_token)
+ terminal(ast->case_token, ast);
+ nonterminal(ast->expression);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(CompoundStatementAST *ast)
+{
+ if (ast->lbrace_token)
+ terminal(ast->lbrace_token, ast);
+ for (StatementListAST *iter = ast->statement_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rbrace_token)
+ terminal(ast->rbrace_token, ast);
+ return false;
+}
+
+virtual bool visit(ConditionAST *ast)
+{
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ return false;
+}
+
+virtual bool visit(ConditionalExpressionAST *ast)
+{
+ nonterminal(ast->condition);
+ if (ast->question_token)
+ terminal(ast->question_token, ast);
+ nonterminal(ast->left_expression);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ nonterminal(ast->right_expression);
+ return false;
+}
+
+virtual bool visit(CppCastExpressionAST *ast)
+{
+ if (ast->cast_token)
+ terminal(ast->cast_token, ast);
+ if (ast->less_token)
+ terminal(ast->less_token, ast);
+ nonterminal(ast->type_id);
+ if (ast->greater_token)
+ terminal(ast->greater_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(CtorInitializerAST *ast)
+{
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ for (MemInitializerListAST *iter = ast->member_initializer_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ return false;
+}
+
+virtual bool visit(DeclarationStatementAST *ast)
+{
+ nonterminal(ast->declaration);
+ return false;
+}
+
+virtual bool visit(DeclaratorIdAST *ast)
+{
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ nonterminal(ast->name);
+ return false;
+}
+
+virtual bool visit(NestedDeclaratorAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->declarator);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(FunctionDeclaratorAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->parameter_declaration_clause);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ for (SpecifierListAST *iter = ast->cv_qualifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->ref_qualifier_token)
+ terminal(ast->ref_qualifier_token, ast);
+ nonterminal(ast->exception_specification);
+ nonterminal(ast->trailing_return_type);
+ nonterminal(ast->as_cpp_initializer);
+ return false;
+}
+
+virtual bool visit(ArrayDeclaratorAST *ast)
+{
+ if (ast->lbracket_token)
+ terminal(ast->lbracket_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rbracket_token)
+ terminal(ast->rbracket_token, ast);
+ return false;
+}
+
+virtual bool visit(DeleteExpressionAST *ast)
+{
+ if (ast->scope_token)
+ terminal(ast->scope_token, ast);
+ if (ast->delete_token)
+ terminal(ast->delete_token, ast);
+ if (ast->lbracket_token)
+ terminal(ast->lbracket_token, ast);
+ if (ast->rbracket_token)
+ terminal(ast->rbracket_token, ast);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(DoStatementAST *ast)
+{
+ if (ast->do_token)
+ terminal(ast->do_token, ast);
+ nonterminal(ast->statement);
+ if (ast->while_token)
+ terminal(ast->while_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(NamedTypeSpecifierAST *ast)
+{
+ nonterminal(ast->name);
+ return false;
+}
+
+virtual bool visit(ElaboratedTypeSpecifierAST *ast)
+{
+ if (ast->classkey_token)
+ terminal(ast->classkey_token, ast);
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->name);
+ return false;
+}
+
+virtual bool visit(EnumSpecifierAST *ast)
+{
+ if (ast->enum_token)
+ terminal(ast->enum_token, ast);
+ if (ast->key_token)
+ terminal(ast->key_token, ast);
+ nonterminal(ast->name);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->lbrace_token)
+ terminal(ast->lbrace_token, ast);
+ for (EnumeratorListAST *iter = ast->enumerator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->stray_comma_token)
+ terminal(ast->stray_comma_token, ast);
+ if (ast->rbrace_token)
+ terminal(ast->rbrace_token, ast);
+ return false;
+}
+
+virtual bool visit(EnumeratorAST *ast)
+{
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(ExceptionDeclarationAST *ast)
+{
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ return false;
+}
+
+virtual bool visit(DynamicExceptionSpecificationAST *ast)
+{
+ if (ast->throw_token)
+ terminal(ast->throw_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ for (ExpressionListAST *iter = ast->type_id_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(NoExceptSpecificationAST *ast)
+{
+ if (ast->noexcept_token)
+ terminal(ast->noexcept_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(ExpressionOrDeclarationStatementAST *ast)
+{
+ nonterminal(ast->expression);
+ nonterminal(ast->declaration);
+ return false;
+}
+
+virtual bool visit(ExpressionStatementAST *ast)
+{
+ nonterminal(ast->expression);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(FunctionDefinitionAST *ast)
+{
+ if (ast->qt_invokable_token)
+ terminal(ast->qt_invokable_token, ast);
+ for (SpecifierListAST *iter = ast->decl_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ nonterminal(ast->ctor_initializer);
+ nonterminal(ast->function_body);
+ return false;
+}
+
+virtual bool visit(ForeachStatementAST *ast)
+{
+ if (ast->foreach_token)
+ terminal(ast->foreach_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ nonterminal(ast->initializer);
+ if (ast->comma_token)
+ terminal(ast->comma_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(RangeBasedForStatementAST *ast)
+{
+ if (ast->for_token)
+ terminal(ast->for_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(ForStatementAST *ast)
+{
+ if (ast->for_token)
+ terminal(ast->for_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->initializer);
+ nonterminal(ast->condition);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(IfStatementAST *ast)
+{
+ if (ast->if_token)
+ terminal(ast->if_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->condition);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ if (ast->else_token)
+ terminal(ast->else_token, ast);
+ nonterminal(ast->else_statement);
+ return false;
+}
+
+virtual bool visit(ArrayInitializerAST *ast)
+{
+ if (ast->lbrace_token)
+ terminal(ast->lbrace_token, ast);
+ for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rbrace_token)
+ terminal(ast->rbrace_token, ast);
+ return false;
+}
+
+virtual bool visit(LabeledStatementAST *ast)
+{
+ if (ast->label_token)
+ terminal(ast->label_token, ast);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(LinkageBodyAST *ast)
+{
+ if (ast->lbrace_token)
+ terminal(ast->lbrace_token, ast);
+ for (DeclarationListAST *iter = ast->declaration_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rbrace_token)
+ terminal(ast->rbrace_token, ast);
+ return false;
+}
+
+virtual bool visit(LinkageSpecificationAST *ast)
+{
+ if (ast->extern_token)
+ terminal(ast->extern_token, ast);
+ if (ast->extern_type_token)
+ terminal(ast->extern_type_token, ast);
+ nonterminal(ast->declaration);
+ return false;
+}
+
+virtual bool visit(MemInitializerAST *ast)
+{
+ nonterminal(ast->name);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(NestedNameSpecifierAST *ast)
+{
+ nonterminal(ast->class_or_namespace_name);
+ if (ast->scope_token)
+ terminal(ast->scope_token, ast);
+ return false;
+}
+
+virtual bool visit(QualifiedNameAST *ast)
+{
+ if (ast->global_scope_token)
+ terminal(ast->global_scope_token, ast);
+ for (NestedNameSpecifierListAST *iter = ast->nested_name_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->unqualified_name);
+ return false;
+}
+
+virtual bool visit(OperatorFunctionIdAST *ast)
+{
+ if (ast->operator_token)
+ terminal(ast->operator_token, ast);
+ nonterminal(ast->op);
+ return false;
+}
+
+virtual bool visit(ConversionFunctionIdAST *ast)
+{
+ if (ast->operator_token)
+ terminal(ast->operator_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ for (PtrOperatorListAST *iter = ast->ptr_operator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(AnonymousNameAST *ast)
+{
+ if (ast->class_token)
+ terminal(ast->class_token, ast);
+ return false;
+}
+
+virtual bool visit(SimpleNameAST *ast)
+{
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ return false;
+}
+
+virtual bool visit(DestructorNameAST *ast)
+{
+ if (ast->tilde_token)
+ terminal(ast->tilde_token, ast);
+ nonterminal(ast->unqualified_name);
+ return false;
+}
+
+virtual bool visit(TemplateIdAST *ast)
+{
+ if (ast->template_token)
+ terminal(ast->template_token, ast);
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ if (ast->less_token)
+ terminal(ast->less_token, ast);
+ for (ExpressionListAST *iter = ast->template_argument_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->greater_token)
+ terminal(ast->greater_token, ast);
+ return false;
+}
+
+virtual bool visit(NamespaceAST *ast)
+{
+ if (ast->inline_token)
+ terminal(ast->inline_token, ast);
+ if (ast->namespace_token)
+ terminal(ast->namespace_token, ast);
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->linkage_body);
+ return false;
+}
+
+virtual bool visit(NamespaceAliasDefinitionAST *ast)
+{
+ if (ast->namespace_token)
+ terminal(ast->namespace_token, ast);
+ if (ast->namespace_name_token)
+ terminal(ast->namespace_name_token, ast);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->name);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(AliasDeclarationAST *ast)
+{
+ if (ast->using_token)
+ terminal(ast->using_token, ast);
+ nonterminal(ast->name);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->typeId);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ExpressionListParenAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(NewArrayDeclaratorAST *ast)
+{
+ if (ast->lbracket_token)
+ terminal(ast->lbracket_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rbracket_token)
+ terminal(ast->rbracket_token, ast);
+ return false;
+}
+
+virtual bool visit(NewExpressionAST *ast)
+{
+ if (ast->scope_token)
+ terminal(ast->scope_token, ast);
+ if (ast->new_token)
+ terminal(ast->new_token, ast);
+ nonterminal(ast->new_placement);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->type_id);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->new_type_id);
+ nonterminal(ast->new_initializer);
+ return false;
+}
+
+virtual bool visit(NewTypeIdAST *ast)
+{
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ for (PtrOperatorListAST *iter = ast->ptr_operator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ for (NewArrayDeclaratorListAST *iter = ast->new_array_declarator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(OperatorAST *ast)
+{
+ if (ast->op_token)
+ terminal(ast->op_token, ast);
+ if (ast->open_token)
+ terminal(ast->open_token, ast);
+ if (ast->close_token)
+ terminal(ast->close_token, ast);
+ return false;
+}
+
+virtual bool visit(ParameterDeclarationAST *ast)
+{
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(ParameterDeclarationClauseAST *ast)
+{
+ for (ParameterDeclarationListAST *iter = ast->parameter_declaration_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ return false;
+}
+
+virtual bool visit(CallAST *ast)
+{
+ nonterminal(ast->base_expression);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(ArrayAccessAST *ast)
+{
+ nonterminal(ast->base_expression);
+ if (ast->lbracket_token)
+ terminal(ast->lbracket_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rbracket_token)
+ terminal(ast->rbracket_token, ast);
+ return false;
+}
+
+virtual bool visit(PostIncrDecrAST *ast)
+{
+ nonterminal(ast->base_expression);
+ if (ast->incr_decr_token)
+ terminal(ast->incr_decr_token, ast);
+ return false;
+}
+
+virtual bool visit(MemberAccessAST *ast)
+{
+ nonterminal(ast->base_expression);
+ if (ast->access_token)
+ terminal(ast->access_token, ast);
+ if (ast->template_token)
+ terminal(ast->template_token, ast);
+ nonterminal(ast->member_name);
+ return false;
+}
+
+virtual bool visit(TypeidExpressionAST *ast)
+{
+ if (ast->typeid_token)
+ terminal(ast->typeid_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(TypenameCallExpressionAST *ast)
+{
+ if (ast->typename_token)
+ terminal(ast->typename_token, ast);
+ nonterminal(ast->name);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(TypeConstructorCallAST *ast)
+{
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(PointerToMemberAST *ast)
+{
+ if (ast->global_scope_token)
+ terminal(ast->global_scope_token, ast);
+ for (NestedNameSpecifierListAST *iter = ast->nested_name_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->star_token)
+ terminal(ast->star_token, ast);
+ for (SpecifierListAST *iter = ast->cv_qualifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->ref_qualifier_token)
+ terminal(ast->ref_qualifier_token, ast);
+ return false;
+}
+
+virtual bool visit(PointerAST *ast)
+{
+ if (ast->star_token)
+ terminal(ast->star_token, ast);
+ for (SpecifierListAST *iter = ast->cv_qualifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(ReferenceAST *ast)
+{
+ if (ast->reference_token)
+ terminal(ast->reference_token, ast);
+ return false;
+}
+
+virtual bool visit(BreakStatementAST *ast)
+{
+ if (ast->break_token)
+ terminal(ast->break_token, ast);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ContinueStatementAST *ast)
+{
+ if (ast->continue_token)
+ terminal(ast->continue_token, ast);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(GotoStatementAST *ast)
+{
+ if (ast->goto_token)
+ terminal(ast->goto_token, ast);
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ReturnStatementAST *ast)
+{
+ if (ast->return_token)
+ terminal(ast->return_token, ast);
+ nonterminal(ast->expression);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(SizeofExpressionAST *ast)
+{
+ if (ast->sizeof_token)
+ terminal(ast->sizeof_token, ast);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(AlignofExpressionAST *ast)
+{
+ if (ast->alignof_token)
+ terminal(ast->alignof_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->typeId);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(PointerLiteralAST *ast)
+{
+ if (ast->literal_token)
+ terminal(ast->literal_token, ast);
+ return false;
+}
+
+virtual bool visit(NumericLiteralAST *ast)
+{
+ if (ast->literal_token)
+ terminal(ast->literal_token, ast);
+ return false;
+}
+
+virtual bool visit(BoolLiteralAST *ast)
+{
+ if (ast->literal_token)
+ terminal(ast->literal_token, ast);
+ return false;
+}
+
+virtual bool visit(ThisExpressionAST *ast)
+{
+ if (ast->this_token)
+ terminal(ast->this_token, ast);
+ return false;
+}
+
+virtual bool visit(NestedExpressionAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(StaticAssertDeclarationAST *ast)
+{
+ if (ast->static_assert_token)
+ terminal(ast->static_assert_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->expression);
+ if (ast->comma_token)
+ terminal(ast->comma_token, ast);
+ nonterminal(ast->string_literal);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(StringLiteralAST *ast)
+{
+ if (ast->literal_token)
+ terminal(ast->literal_token, ast);
+ nonterminal(ast->next);
+ return false;
+}
+
+virtual bool visit(SwitchStatementAST *ast)
+{
+ if (ast->switch_token)
+ terminal(ast->switch_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->condition);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(TemplateDeclarationAST *ast)
+{
+ if (ast->export_token)
+ terminal(ast->export_token, ast);
+ if (ast->template_token)
+ terminal(ast->template_token, ast);
+ if (ast->less_token)
+ terminal(ast->less_token, ast);
+ for (DeclarationListAST *iter = ast->template_parameter_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->greater_token)
+ terminal(ast->greater_token, ast);
+ nonterminal(ast->declaration);
+ return false;
+}
+
+virtual bool visit(ThrowExpressionAST *ast)
+{
+ if (ast->throw_token)
+ terminal(ast->throw_token, ast);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(TranslationUnitAST *ast)
+{
+ for (DeclarationListAST *iter = ast->declaration_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(TryBlockStatementAST *ast)
+{
+ if (ast->try_token)
+ terminal(ast->try_token, ast);
+ nonterminal(ast->statement);
+ for (CatchClauseListAST *iter = ast->catch_clause_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(CatchClauseAST *ast)
+{
+ if (ast->catch_token)
+ terminal(ast->catch_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->exception_declaration);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(TypeIdAST *ast)
+{
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ return false;
+}
+
+virtual bool visit(TypenameTypeParameterAST *ast)
+{
+ if (ast->classkey_token)
+ terminal(ast->classkey_token, ast);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ nonterminal(ast->name);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->type_id);
+ return false;
+}
+
+virtual bool visit(TemplateTypeParameterAST *ast)
+{
+ if (ast->template_token)
+ terminal(ast->template_token, ast);
+ if (ast->less_token)
+ terminal(ast->less_token, ast);
+ for (DeclarationListAST *iter = ast->template_parameter_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->greater_token)
+ terminal(ast->greater_token, ast);
+ if (ast->class_token)
+ terminal(ast->class_token, ast);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ nonterminal(ast->name);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->type_id);
+ return false;
+}
+
+virtual bool visit(UnaryExpressionAST *ast)
+{
+ if (ast->unary_op_token)
+ terminal(ast->unary_op_token, ast);
+ nonterminal(ast->expression);
+ return false;
+}
+
+virtual bool visit(UsingAST *ast)
+{
+ if (ast->using_token)
+ terminal(ast->using_token, ast);
+ if (ast->typename_token)
+ terminal(ast->typename_token, ast);
+ nonterminal(ast->name);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(UsingDirectiveAST *ast)
+{
+ if (ast->using_token)
+ terminal(ast->using_token, ast);
+ if (ast->namespace_token)
+ terminal(ast->namespace_token, ast);
+ nonterminal(ast->name);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(WhileStatementAST *ast)
+{
+ if (ast->while_token)
+ terminal(ast->while_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->condition);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(ObjCClassForwardDeclarationAST *ast)
+{
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->class_token)
+ terminal(ast->class_token, ast);
+ for (NameListAST *iter = ast->identifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCClassDeclarationAST *ast)
+{
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->interface_token)
+ terminal(ast->interface_token, ast);
+ if (ast->implementation_token)
+ terminal(ast->implementation_token, ast);
+ nonterminal(ast->class_name);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->category_name);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ nonterminal(ast->superclass);
+ nonterminal(ast->protocol_refs);
+ nonterminal(ast->inst_vars_decl);
+ for (DeclarationListAST *iter = ast->member_declaration_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->end_token)
+ terminal(ast->end_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCProtocolForwardDeclarationAST *ast)
+{
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->protocol_token)
+ terminal(ast->protocol_token, ast);
+ for (NameListAST *iter = ast->identifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCProtocolDeclarationAST *ast)
+{
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->protocol_token)
+ terminal(ast->protocol_token, ast);
+ nonterminal(ast->name);
+ nonterminal(ast->protocol_refs);
+ for (DeclarationListAST *iter = ast->member_declaration_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->end_token)
+ terminal(ast->end_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCProtocolRefsAST *ast)
+{
+ if (ast->less_token)
+ terminal(ast->less_token, ast);
+ for (NameListAST *iter = ast->identifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->greater_token)
+ terminal(ast->greater_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCMessageArgumentAST *ast)
+{
+ nonterminal(ast->parameter_value_expression);
+ return false;
+}
+
+virtual bool visit(ObjCMessageExpressionAST *ast)
+{
+ if (ast->lbracket_token)
+ terminal(ast->lbracket_token, ast);
+ nonterminal(ast->receiver_expression);
+ nonterminal(ast->selector);
+ for (ObjCMessageArgumentListAST *iter = ast->argument_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rbracket_token)
+ terminal(ast->rbracket_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCProtocolExpressionAST *ast)
+{
+ if (ast->protocol_token)
+ terminal(ast->protocol_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCTypeNameAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ if (ast->type_qualifier_token)
+ terminal(ast->type_qualifier_token, ast);
+ nonterminal(ast->type_id);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCEncodeExpressionAST *ast)
+{
+ if (ast->encode_token)
+ terminal(ast->encode_token, ast);
+ nonterminal(ast->type_name);
+ return false;
+}
+
+virtual bool visit(ObjCSelectorExpressionAST *ast)
+{
+ if (ast->selector_token)
+ terminal(ast->selector_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->selector);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCInstanceVariablesDeclarationAST *ast)
+{
+ if (ast->lbrace_token)
+ terminal(ast->lbrace_token, ast);
+ for (DeclarationListAST *iter = ast->instance_variable_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rbrace_token)
+ terminal(ast->rbrace_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCVisibilityDeclarationAST *ast)
+{
+ if (ast->visibility_token)
+ terminal(ast->visibility_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCPropertyAttributeAST *ast)
+{
+ if (ast->attribute_identifier_token)
+ terminal(ast->attribute_identifier_token, ast);
+ if (ast->equals_token)
+ terminal(ast->equals_token, ast);
+ nonterminal(ast->method_selector);
+ return false;
+}
+
+virtual bool visit(ObjCPropertyDeclarationAST *ast)
+{
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->property_token)
+ terminal(ast->property_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (ObjCPropertyAttributeListAST *iter = ast->property_attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->simple_declaration);
+ return false;
+}
+
+virtual bool visit(ObjCMessageArgumentDeclarationAST *ast)
+{
+ nonterminal(ast->type_name);
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->param_name);
+ return false;
+}
+
+virtual bool visit(ObjCMethodPrototypeAST *ast)
+{
+ if (ast->method_type_token)
+ terminal(ast->method_type_token, ast);
+ nonterminal(ast->type_name);
+ nonterminal(ast->selector);
+ for (ObjCMessageArgumentDeclarationListAST *iter = ast->argument_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->dot_dot_dot_token)
+ terminal(ast->dot_dot_dot_token, ast);
+ for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(ObjCMethodDeclarationAST *ast)
+{
+ nonterminal(ast->method_prototype);
+ nonterminal(ast->function_body);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCSynthesizedPropertyAST *ast)
+{
+ if (ast->property_identifier_token)
+ terminal(ast->property_identifier_token, ast);
+ if (ast->equals_token)
+ terminal(ast->equals_token, ast);
+ if (ast->alias_identifier_token)
+ terminal(ast->alias_identifier_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCSynthesizedPropertiesDeclarationAST *ast)
+{
+ if (ast->synthesized_token)
+ terminal(ast->synthesized_token, ast);
+ for (ObjCSynthesizedPropertyListAST *iter = ast->property_identifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCDynamicPropertiesDeclarationAST *ast)
+{
+ if (ast->dynamic_token)
+ terminal(ast->dynamic_token, ast);
+ for (NameListAST *iter = ast->property_identifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ObjCFastEnumerationAST *ast)
+{
+ if (ast->for_token)
+ terminal(ast->for_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ nonterminal(ast->initializer);
+ if (ast->in_token)
+ terminal(ast->in_token, ast);
+ nonterminal(ast->fast_enumeratable_expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(ObjCSynchronizedStatementAST *ast)
+{
+ if (ast->synchronized_token)
+ terminal(ast->synchronized_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->synchronized_object);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(LambdaExpressionAST *ast)
+{
+ nonterminal(ast->lambda_introducer);
+ nonterminal(ast->lambda_declarator);
+ nonterminal(ast->statement);
+ return false;
+}
+
+virtual bool visit(LambdaIntroducerAST *ast)
+{
+ if (ast->lbracket_token)
+ terminal(ast->lbracket_token, ast);
+ nonterminal(ast->lambda_capture);
+ if (ast->rbracket_token)
+ terminal(ast->rbracket_token, ast);
+ return false;
+}
+
+virtual bool visit(LambdaCaptureAST *ast)
+{
+ if (ast->default_capture_token)
+ terminal(ast->default_capture_token, ast);
+ for (CaptureListAST *iter = ast->capture_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ return false;
+}
+
+virtual bool visit(CaptureAST *ast)
+{
+ if (ast->amper_token)
+ terminal(ast->amper_token, ast);
+ nonterminal(ast->identifier);
+ return false;
+}
+
+virtual bool visit(LambdaDeclaratorAST *ast)
+{
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->parameter_declaration_clause);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ for (SpecifierListAST *iter = ast->attributes; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->mutable_token)
+ terminal(ast->mutable_token, ast);
+ nonterminal(ast->exception_specification);
+ nonterminal(ast->trailing_return_type);
+ return false;
+}
+
+virtual bool visit(TrailingReturnTypeAST *ast)
+{
+ if (ast->arrow_token)
+ terminal(ast->arrow_token, ast);
+ for (SpecifierListAST *iter = ast->attributes; iter; iter = iter->next)
+ nonterminal(iter->value);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ return false;
+}
+
+virtual bool visit(BracedInitializerAST *ast)
+{
+ if (ast->lbrace_token)
+ terminal(ast->lbrace_token, ast);
+ for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->comma_token)
+ terminal(ast->comma_token, ast);
+ if (ast->rbrace_token)
+ terminal(ast->rbrace_token, ast);
+ return false;
+}
+
+virtual bool visit(DotDesignatorAST *ast)
+{
+ if (ast->dot_token)
+ terminal(ast->dot_token, ast);
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ return false;
+}
+
+virtual bool visit(BracketDesignatorAST *ast)
+{
+ if (ast->lbracket_token)
+ terminal(ast->lbracket_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rbracket_token)
+ terminal(ast->rbracket_token, ast);
+ return false;
+}
+
+virtual bool visit(DesignatedInitializerAST *ast)
+{
+ for (DesignatorListAST *iter = ast->designator_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->initializer);
+ return false;
+}
+
diff --git a/src/plugins/qmldesigner/qmldesignerwarning.h b/src/tools/cplusplus-ast2png/tests/templ01.cpp
index 4e6f6585d49..0a363abfdd7 100644
--- a/src/plugins/qmldesigner/qmldesignerwarning.h
+++ b/src/tools/cplusplus-ast2png/tests/templ01.cpp
@@ -28,19 +28,19 @@
**
****************************************************************************/
-#ifndef QMLDESIGNERWARNING_H
-#define QMLDESIGNERWARNING_H
-
-#include <QString>
-
-namespace QmlDesigner {
-
-class QmlDesignerWarning
+struct QString
{
-public:
- static void show(const QString &title, const QString &desciption);
+ void append(char ch);
};
-} //QmlDesigner
+template <typename _Tp> struct QList {
+ const _Tp &at(int index);
+};
+
+struct QStringList: public QList<QString> {};
-#endif // QMLDESIGNERWARNING_H
+int main()
+{
+ QStringList l;
+ l.at(0).append('a');
+}
diff --git a/src/tools/cplusplus-frontend/cplusplus-frontend.cpp b/src/tools/cplusplus-frontend/cplusplus-frontend.cpp
new file mode 100644
index 00000000000..26e1941715e
--- /dev/null
+++ b/src/tools/cplusplus-frontend/cplusplus-frontend.cpp
@@ -0,0 +1,111 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include <cplusplus/AST.h>
+#include <cplusplus/ASTMatcher.h>
+#include <cplusplus/ASTPatternBuilder.h>
+#include <cplusplus/ASTVisitor.h>
+#include <cplusplus/Control.h>
+#include <cplusplus/CoreTypes.h>
+#include <cplusplus/CppDocument.h>
+#include <cplusplus/Literals.h>
+#include <cplusplus/Names.h>
+#include <cplusplus/Scope.h>
+#include <cplusplus/Symbols.h>
+#include <cplusplus/TranslationUnit.h>
+
+#include "utils.h"
+
+#include <QFile>
+#include <QList>
+#include <QCoreApplication>
+#include <QStringList>
+#include <QFileInfo>
+#include <QTime>
+#include <QDebug>
+
+#include <cstdio>
+#include <cstdlib>
+#include <iostream>
+
+using namespace CPlusPlus;
+
+void printUsage()
+{
+ std::cout << "Usage: " << qPrintable(QFileInfo(qApp->arguments().at(0)).fileName())
+ << " [-v] <file1> <file2> ...\n\n"
+ << "Run the parser with the given files.\n";
+}
+
+int main(int argc, char *argv[])
+{
+ QCoreApplication app(argc, argv);
+ QStringList args = app.arguments();
+ args.removeFirst();
+
+ bool optionVerbose = false;
+
+ // Process options & arguments
+ if (args.contains(QLatin1String("-v"))) {
+ optionVerbose = true;
+ args.removeOne(QLatin1String("-v"));
+ }
+ const bool helpRequested = args.contains(QLatin1String("-h")) || args.contains(QLatin1String("-help"));
+ if (args.isEmpty() || helpRequested) {
+ printUsage();
+ return helpRequested ? EXIT_SUCCESS : EXIT_FAILURE;
+ }
+
+ // Process files
+ const QStringList files = args;
+ foreach (const QString &fileName, files) {
+ // Run preprocessor
+ const QString fileNamePreprocessed = fileName + QLatin1String(".preprocessed");
+ CplusplusToolsUtils::SystemPreprocessor preprocessor(optionVerbose);
+ preprocessor.preprocessFile(fileName, fileNamePreprocessed);
+
+ // Run parser
+ QFile file(fileNamePreprocessed);
+ if (! file.open(QFile::ReadOnly)) {
+ std::cerr << "Error: Could not open file \"" << qPrintable(file.fileName()) << "\"."
+ << std::endl;
+ return EXIT_FAILURE;
+ }
+ const QByteArray source = file.readAll();
+ file.close();
+
+ Document::Ptr doc = Document::create(fileName);
+ doc->control()->setDiagnosticClient(0);
+ doc->setUtf8Source(source);
+ doc->parse();
+ }
+
+ return EXIT_SUCCESS;
+}
diff --git a/src/tools/cplusplus-frontend/cplusplus-frontend.pro b/src/tools/cplusplus-frontend/cplusplus-frontend.pro
new file mode 100644
index 00000000000..4ab5b86dc57
--- /dev/null
+++ b/src/tools/cplusplus-frontend/cplusplus-frontend.pro
@@ -0,0 +1,4 @@
+include(../cplusplus-shared/tool.pri)
+include(../cplusplus-shared/utils.pri)
+
+SOURCES += cplusplus-frontend.cpp
diff --git a/src/tools/cplusplus-frontend/cplusplus-frontend.qbs b/src/tools/cplusplus-frontend/cplusplus-frontend.qbs
new file mode 100644
index 00000000000..56b3d28c194
--- /dev/null
+++ b/src/tools/cplusplus-frontend/cplusplus-frontend.qbs
@@ -0,0 +1,6 @@
+import "../cplusplus-shared/CPlusPlusToolUsingCustomUtils.qbs" as CPlusPlusToolUsingCustomUtils
+
+CPlusPlusToolUsingCustomUtils {
+ name: "cplusplus-frontend"
+ files: base.concat("cplusplus-frontend.cpp")
+}
diff --git a/src/tools/cplusplus-frontend/tests/t1.cpp b/src/tools/cplusplus-frontend/tests/t1.cpp
new file mode 100644
index 00000000000..c0ca61076ce
--- /dev/null
+++ b/src/tools/cplusplus-frontend/tests/t1.cpp
@@ -0,0 +1,85 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms and
+** conditions see http://www.qt.io/terms-conditions. For further information
+** use the contact form at http://www.qt.io/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 or version 3 as published by the Free
+** Software Foundation and appearing in the file LICENSE.LGPLv21 and
+** LICENSE.LGPLv3 included in the packaging of this file. Please review the
+** following information to ensure the GNU Lesser General Public License
+** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, The Qt Company gives you certain additional
+** rights. These rights are described in The Qt Company LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+class Class {
+ int a, b;
+
+ enum zoo { a = 1, b = a + 2 + x::y<10>::value };
+
+ enum {};
+
+ typedef enum { k };
+
+ void foo() {}
+ inline void bar() {}
+
+ void another_foo() {
+ int a = static_cast<int>(1+2/3*4-5%6+(7&8));
+ }
+
+ void test_if() {
+ if (a == 10) return 1;
+ else if (b == 20) return 2;
+ else if (c == 30) { x = 1; }
+ }
+
+ void test_while() {
+ while (int a = 1) {
+ exit();
+ }
+
+ while (x==1) do_something_here();
+
+ while (x==2) if(a==1) c(); else if (a==2) c(); else c3();
+ }
+
+ void test_switch() {
+ switch (int k = 1) {
+ case 'a': case 'b': case '\\':
+ return 1;
+ case 1|2: { return 3; } break;
+ case x: break;
+ case y:
+ foo();
+ break;
+ default:
+ return 2;
+ }
+ s = L"ci\"aa\"ao" L"blah!";
+ s2 = "ciao \"ciao\" ciao";
+ }
+};
+
+class Derived: public Class {
+ operator bool() const volatile throw () { return 1; }
+ Derived &operator++() {}
+};
+
+class Derived2: public Class, public virtual Derived {};
diff --git a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp
index 99f14837dda..3b7e4c52d0f 100644
--- a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp
+++ b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp
@@ -45,7 +45,7 @@
#include <cplusplus/Overview.h>
#include <cplusplus/LookupContext.h>
-#include "cplusplus-tools-utils.h"
+#include "utils.h"
#include <QFile>
#include <QList>
diff --git a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro
index ce0a4bc7aa7..905e0570be9 100644
--- a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro
+++ b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro
@@ -1,14 +1,6 @@
-QT = core gui
-macx:CONFIG -= app_bundle
-win32:CONFIG += console
-TEMPLATE = app
-TARGET = cplusplus-mkvisitor
-DESTDIR = ./
+include(../cplusplus-shared/tool.pri)
+include(../cplusplus-shared/utils.pri)
-include(../../../qtcreator.pri)
-include(../../libs/cplusplus/cplusplus-lib.pri)
-include(../../../src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri)
-
-DEFINES *= QT_NO_CAST_FROM_ASCII
DEFINES += PATH_AST_H=\\\"$$PWD/../../libs/3rdparty/cplusplus/AST.h\\\"
+
SOURCES += cplusplus-mkvisitor.cpp
diff --git a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.qbs b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.qbs
new file mode 100644
index 00000000000..064e1967984
--- /dev/null
+++ b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.qbs
@@ -0,0 +1,7 @@
+import "../cplusplus-shared/CPlusPlusToolUsingCustomUtils.qbs" as CPlusPlusToolUsingCustomUtils
+
+CPlusPlusToolUsingCustomUtils {
+ name: "cplusplus-mkvisitor"
+ cpp.defines: base.concat('PATH_AST_H="' + path + '/../../libs/3rdparty/cplusplus/AST.h"')
+ files: base.concat("cplusplus-mkvisitor.cpp")
+}
diff --git a/src/tools/cplusplus-shared/CPlusPlusTool.qbs b/src/tools/cplusplus-shared/CPlusPlusTool.qbs
new file mode 100644
index 00000000000..55c4aff9409
--- /dev/null
+++ b/src/tools/cplusplus-shared/CPlusPlusTool.qbs
@@ -0,0 +1,7 @@
+import qbs 1.0
+
+QtcTool {
+ Depends { name: "Qt"; submodules: ["core", "widgets"]; }
+ Depends { name: "CPlusPlus" }
+ Depends { name: "Utils" }
+}
diff --git a/src/tools/cplusplus-shared/CPlusPlusToolUsingCustomUtils.qbs b/src/tools/cplusplus-shared/CPlusPlusToolUsingCustomUtils.qbs
new file mode 100644
index 00000000000..4b7c607ce3e
--- /dev/null
+++ b/src/tools/cplusplus-shared/CPlusPlusToolUsingCustomUtils.qbs
@@ -0,0 +1,15 @@
+import "../cplusplus-shared/CPlusPlusTool.qbs" as CPlusPlusTool
+
+CPlusPlusTool {
+ Depends { name: "Qt"; submodules: ["core", "widgets"]; }
+ Depends { name: "CPlusPlus" }
+ Depends { name: "Utils" }
+
+ cpp.includePaths: base.concat(path)
+ cpp.defines: base.concat('PATH_PREPROCESSOR_CONFIG="' + path + '/pp-configuration.inc"')
+
+ files: [
+ path + '/utils.h',
+ path + '/utils.cpp',
+ ]
+}
diff --git a/src/tools/cplusplus-tools-utils/pp-configuration.inc b/src/tools/cplusplus-shared/pp-configuration.inc
index 5d6b0678c91..5d6b0678c91 100644
--- a/src/tools/cplusplus-tools-utils/pp-configuration.inc
+++ b/src/tools/cplusplus-shared/pp-configuration.inc
diff --git a/src/tools/cplusplus-shared/tool.pri b/src/tools/cplusplus-shared/tool.pri
new file mode 100644
index 00000000000..569d099e2fb
--- /dev/null
+++ b/src/tools/cplusplus-shared/tool.pri
@@ -0,0 +1,12 @@
+QTC_LIB_DEPENDS += cplusplus
+
+include(../../../qtcreator.pri)
+include(../../rpath.pri)
+
+DESTDIR = $$IDE_BIN_PATH
+
+QT = core gui
+TEMPLATE = app
+
+osx:CONFIG -= app_bundle
+CONFIG += console
diff --git a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp b/src/tools/cplusplus-shared/utils.cpp
index 8bc96e95a86..e773245ce32 100644
--- a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp
+++ b/src/tools/cplusplus-shared/utils.cpp
@@ -29,7 +29,7 @@
****************************************************************************/
-#include "cplusplus-tools-utils.h"
+#include "utils.h"
#include <utils/environment.h>
diff --git a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.h b/src/tools/cplusplus-shared/utils.h
index 223863d49be..223863d49be 100644
--- a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.h
+++ b/src/tools/cplusplus-shared/utils.h
diff --git a/src/tools/cplusplus-shared/utils.pri b/src/tools/cplusplus-shared/utils.pri
new file mode 100644
index 00000000000..69e2e2bb3c6
--- /dev/null
+++ b/src/tools/cplusplus-shared/utils.pri
@@ -0,0 +1,6 @@
+INCLUDEPATH += $$PWD
+
+DEFINES += PATH_PREPROCESSOR_CONFIG=\\\"$$PWD/pp-configuration.inc\\\"
+
+HEADERS += $$PWD/utils.h
+SOURCES += $$PWD/utils.cpp
diff --git a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri b/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri
deleted file mode 100644
index 07ac4e645c8..00000000000
--- a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri
+++ /dev/null
@@ -1,22 +0,0 @@
-DEPENDPATH += $$PWD
-INCLUDEPATH += $$PWD
-
-DEFINES *= QT_NO_CAST_FROM_ASCII
-DEFINES += PATH_PREPROCESSOR_CONFIG=\\\"$$PWD/pp-configuration.inc\\\"
-DEFINES += QTCREATOR_UTILS_STATIC_LIB
-
-HEADERS += \
- $$PWD/cplusplus-tools-utils.h \
- $$PWD/../../libs/utils/environment.h \
- $$PWD/../../libs/utils/fileutils.h \
- $$PWD/../../libs/utils/qtcassert.h \
- $$PWD/../../libs/utils/savefile.h
-
-SOURCES += \
- $$PWD/cplusplus-tools-utils.cpp \
- $$PWD/../../libs/utils/environment.cpp \
- $$PWD/../../libs/utils/fileutils.cpp \
- $$PWD/../../libs/utils/qtcassert.cpp \
- $$PWD/../../libs/utils/savefile.cpp
-
-win32:LIBS += -luser32 -lshell32
diff --git a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp
index ed1b762e2bd..e477eb7da4a 100644
--- a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp
+++ b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp
@@ -90,6 +90,8 @@ static const char generatedHeader[] =
"\n"
;
+static QIODevice::OpenMode openFlags = QIODevice::WriteOnly | QIODevice::Text;
+
static void closeAndPrintFilePath(QFile &file)
{
if (file.isOpen()) {
@@ -214,7 +216,7 @@ public:
QFileInfo fileInfo(_cplusplusDir, QLatin1String("ASTVisit.cpp"));
QFile file(fileInfo.absoluteFilePath());
- if (! file.open(QFile::WriteOnly))
+ if (! file.open(openFlags))
return;
QTextStream output(&file);
@@ -351,7 +353,7 @@ public:
QFileInfo fileInfo(_cplusplusDir, QLatin1String("ASTMatch0.cpp"));
QFile file(fileInfo.absoluteFilePath());
- if (! file.open(QFile::WriteOnly))
+ if (! file.open(openFlags))
return;
QTextStream output(&file);
@@ -462,7 +464,7 @@ public:
QFileInfo fileInfo(_cplusplusDir, QLatin1String("ASTMatcher.cpp"));
QFile file(fileInfo.absoluteFilePath());
- if (! file.open(QFile::WriteOnly))
+ if (! file.open(openFlags))
return;
QTextStream output(&file);
@@ -615,7 +617,7 @@ public:
QFileInfo fileInfo(_cplusplusDir, QLatin1String("ASTClone.cpp"));
QFile file(fileInfo.absoluteFilePath());
- if (! file.open(QFile::WriteOnly))
+ if (! file.open(openFlags))
return;
QTextStream output(&file);
@@ -751,7 +753,7 @@ public:
static void go(const QString &fileName, TranslationUnit *unit)
{
QFile file(fileName);
- if (! file.open(QFile::WriteOnly)) {
+ if (! file.open(openFlags)) {
std::cerr << "Cannot open dumpers file." << std::endl;
return;
}
@@ -1226,7 +1228,7 @@ void generateAST_cpp(const Snapshot &snapshot, const QDir &cplusplusDir)
tc.setPosition(documentEnd);
tc.insertText(newMethods);
- if (file.open(QFile::WriteOnly)) {
+ if (file.open(openFlags)) {
QTextStream out(&file);
out << cpp_document.toPlainText();
closeAndPrintFilePath(file);
@@ -1242,7 +1244,7 @@ void generateASTVisitor_H(const Snapshot &, const QDir &cplusplusDir,
const QString fileName = fileASTVisitor_h.absoluteFilePath();
QFile file(fileName);
- if (! file.open(QFile::WriteOnly))
+ if (! file.open(openFlags))
return;
QTextStream out(&file);
@@ -1335,7 +1337,7 @@ void generateASTMatcher_H(const Snapshot &, const QDir &cplusplusDir,
const QString fileName = fileASTMatcher_h.absoluteFilePath();
QFile file(fileName);
- if (! file.open(QFile::WriteOnly))
+ if (! file.open(openFlags))
return;
QTextStream out(&file);
@@ -1453,7 +1455,7 @@ QStringList generateAST_H(const Snapshot &snapshot, const QDir &cplusplusDir, co
replacementCastMethods.value(classAST));
}
- if (file.open(QFile::WriteOnly)) {
+ if (file.open(openFlags)) {
QTextStream out(&file);
out << document.toPlainText();
closeAndPrintFilePath(file);
@@ -1554,7 +1556,7 @@ void generateASTFwd_h(const Snapshot &snapshot, const QDir &cplusplusDir, const
cursors.first().insertText(replacement);
- if (file.open(QFile::WriteOnly)) {
+ if (file.open(openFlags)) {
QTextStream out(&file);
out << document.toPlainText();
closeAndPrintFilePath(file);
@@ -1567,7 +1569,7 @@ void generateASTPatternBuilder_h(const QDir &cplusplusDir)
QFileInfo fileInfo(cplusplusDir, QLatin1String("ASTPatternBuilder.h"));
QFile file(fileInfo.absoluteFilePath());
- if (! file.open(QFile::WriteOnly))
+ if (! file.open(openFlags))
return;
Overview oo;
diff --git a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro
index 364e9490ebc..6b4f9968423 100644
--- a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro
+++ b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro
@@ -1,15 +1,6 @@
-QT = core gui
-macx:CONFIG -= app_bundle
-win32:CONFIG += console
-TEMPLATE = app
-TARGET = cplusplus-update-frontend
-DESTDIR = ./
-DEFINES += QTCREATOR_UTILS_STATIC_LIB
+include(../cplusplus-shared/tool.pri)
-include(../../../qtcreator.pri)
-include(../../libs/cplusplus/cplusplus-lib.pri)
-
-DEFINES *= QT_NO_CAST_FROM_ASCII
DEFINES += PATH_CPP_FRONTEND=\\\"$$PWD/../../libs/3rdparty/cplusplus\\\"
-DEFINES += PATH_DUMPERS_FILE=\\\"$$PWD/../../../tests/tools/cplusplus-ast2png/dumpers.inc\\\"
-SOURCES += cplusplus-update-frontend.cpp ../../libs/utils/changeset.cpp
+DEFINES += PATH_DUMPERS_FILE=\\\"$$PWD/../cplusplus-ast2png/dumpers.inc\\\"
+
+SOURCES += cplusplus-update-frontend.cpp
diff --git a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.qbs b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.qbs
new file mode 100644
index 00000000000..66dbba53723
--- /dev/null
+++ b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.qbs
@@ -0,0 +1,12 @@
+import "../cplusplus-shared/CPlusPlusTool.qbs" as CPlusPlusTool
+
+CPlusPlusTool {
+ name: "cplusplus-update-frontend"
+
+ cpp.defines: base.concat([
+ 'PATH_CPP_FRONTEND="' + path + '/../../libs/3rdparty/cplusplus"',
+ 'PATH_DUMPERS_FILE="' + path + '/../cplusplus-ast2png/dumpers.inc"',
+ ])
+
+ files: "cplusplus-update-frontend.cpp"
+}
diff --git a/src/tools/cplusplustools.qbs b/src/tools/cplusplustools.qbs
new file mode 100644
index 00000000000..1b1bec39e08
--- /dev/null
+++ b/src/tools/cplusplustools.qbs
@@ -0,0 +1,10 @@
+Project {
+ name: "CPlusPlus Tools"
+ condition: qbs.getEnv("BUILD_CPLUSPLUS_TOOLS")
+ references: [
+ "cplusplus-ast2png/cplusplus-ast2png.qbs",
+ "cplusplus-frontend/cplusplus-frontend.qbs",
+ "cplusplus-mkvisitor/cplusplus-mkvisitor.qbs",
+ "cplusplus-update-frontend/cplusplus-update-frontend.qbs",
+ ]
+}
diff --git a/src/tools/icons/qtcreatoricons.svg b/src/tools/icons/qtcreatoricons.svg
index 2c04f551edb..2abe8175fae 100644
--- a/src/tools/icons/qtcreatoricons.svg
+++ b/src/tools/icons/qtcreatoricons.svg
@@ -581,6 +581,28 @@
y1="587"
x2="181"
y2="599" />
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath4556">
+ <rect
+ id="rect4558"
+ width="16"
+ height="16"
+ x="281"
+ y="584"
+ style="fill:none" />
+ </clipPath>
+ <clipPath
+ clipPathUnits="userSpaceOnUse"
+ id="clipPath3536">
+ <rect
+ style="opacity:0.41699997;fill:none;stroke:none"
+ id="rect3538"
+ width="64"
+ height="64"
+ x="329"
+ y="536" />
+ </clipPath>
<linearGradient
id="linearGradient4137-8">
<stop
@@ -1027,6 +1049,335 @@
transform="matrix(1,0,0,-1,16,1184)"
width="100%"
height="100%" />
+ <g
+ id="src/libs/utils/images/progressindicator_small"
+ clip-path="url(#clipPath4556)"
+ transform="matrix(-1,0,0,1,578,0)">
+ <g
+ id="g4504">
+ <rect
+ id="rect3693"
+ width="16"
+ height="16"
+ x="281"
+ y="584"
+ style="fill:none" />
+ <rect
+ style="fill:#9d9d9d;fill-opacity:1;stroke:none"
+ id="rect3698"
+ width="2"
+ height="5"
+ x="288"
+ y="584" />
+ </g>
+ <use
+ style="opacity:0.83"
+ height="600"
+ width="800"
+ transform="matrix(0.70710678,0.70710678,-0.70710678,0.70710678,503.25335,-30.961074)"
+ id="use4511"
+ xlink:href="#g4504"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.66"
+ height="600"
+ width="800"
+ transform="matrix(0,1,-1,0,881,303)"
+ id="use4525"
+ xlink:href="#g4504"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.49"
+ height="600"
+ width="800"
+ transform="matrix(-0.70710678,0.70710678,-0.70710678,-0.70710678,911.96107,806.25335)"
+ id="use4528"
+ xlink:href="#g4504"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(-1,0,0,-1,578,1184)"
+ id="use4530"
+ xlink:href="#g4504"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(-0.70710678,-0.70710678,0.70710678,-0.70710678,74.746645,1214.9611)"
+ id="use4532"
+ xlink:href="#g4504"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(0,-1,1,0,-303,881)"
+ id="use4534"
+ xlink:href="#g4504"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(0.70710678,-0.70710678,0.70710678,0.70710678,-333.96107,377.74665)"
+ id="use4536"
+ xlink:href="#g4504"
+ y="0"
+ x="0" />
+ </g>
+ <g
+ transform="matrix(-0.5,0,0,0.5,589.5,300)"
+ clip-path="url(#clipPath3536)"
+ id="src/libs/utils/images/progressindicator_medium">
+ <g
+ id="g3383">
+ <rect
+ style="opacity:0.41699997;fill:none;stroke:none"
+ id="rect3385"
+ width="64"
+ height="64"
+ x="329"
+ y="536" />
+ <rect
+ y="536"
+ x="359"
+ height="18"
+ width="4"
+ id="rect3387"
+ style="fill:#6d6d6d;fill-opacity:1;stroke:none" />
+ </g>
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3389"
+ transform="matrix(0.8660254,0.5,-0.5,0.8660254,332.36483,-104.40243)"
+ width="800"
+ height="600"
+ style="opacity:0.88700005" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3391"
+ transform="matrix(0.5,0.8660254,-0.8660254,0.5,672.40243,-28.635171)"
+ width="800"
+ height="600"
+ style="opacity:0.77300002" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3393"
+ transform="matrix(0,1,-1,0,929,207)"
+ width="800"
+ height="600"
+ style="opacity:0.66000001" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3395"
+ transform="matrix(-0.5,0.8660254,-0.8660254,-0.5,1033.4024,539.36483)"
+ width="800"
+ height="600"
+ style="opacity:0.547" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3397"
+ transform="matrix(-0.8660254,0.5,-0.5,-0.8660254,957.63514,879.40243)"
+ width="800"
+ height="600"
+ style="opacity:0.43299997" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3399"
+ transform="matrix(-1,0,0,-1,721.99997,1136)"
+ width="800"
+ height="600"
+ style="opacity:0.31999996" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3401"
+ transform="matrix(-0.8660254,-0.5,0.5,-0.8660254,389.63514,1240.4024)"
+ width="800"
+ height="600"
+ style="opacity:0.31999996" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3403"
+ transform="matrix(-0.5,-0.8660254,0.8660254,-0.5,49.597541,1164.6351)"
+ width="800"
+ height="600"
+ style="opacity:0.31999996" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3405"
+ transform="matrix(0,-1,1,0,-207.00003,928.99993)"
+ width="800"
+ height="600"
+ style="opacity:0.31999996" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3407"
+ transform="matrix(0.5,-0.8660254,0.8660254,0.5,-311.40246,596.6351)"
+ width="800"
+ height="600"
+ style="opacity:0.31999996" />
+ <use
+ x="0"
+ y="0"
+ xlink:href="#g3383"
+ id="use3409"
+ transform="matrix(0.8660254,-0.5,0.5,0.8660254,-235.6352,256.5975)"
+ width="800"
+ height="600"
+ style="opacity:0.31999996" />
+ </g>
+ <g
+ id="src/libs/utils/images/progressindicator_big"
+ clip-path="url(#clipPath3536)"
+ transform="matrix(-1,0,0,1,722,0)">
+ <g
+ id="g3369">
+ <rect
+ y="536"
+ x="329"
+ height="64"
+ width="64"
+ id="rect3365"
+ style="opacity:0.41699997;fill:none;stroke:none" />
+ <rect
+ rx="2"
+ style="fill:#6d6d6d;fill-opacity:1;stroke:none"
+ id="rect3367"
+ width="4"
+ height="17"
+ x="359"
+ y="536"
+ ry="2" />
+ </g>
+ <use
+ style="opacity:0.887"
+ height="600"
+ width="800"
+ transform="matrix(0.8660254,0.5,-0.5,0.8660254,332.36483,-104.40243)"
+ id="use3463"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.773"
+ height="600"
+ width="800"
+ transform="matrix(0.5,0.8660254,-0.8660254,0.5,672.40243,-28.635171)"
+ id="use3467"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.66"
+ height="600"
+ width="800"
+ transform="matrix(0,1,-1,0,929,207)"
+ id="use3469"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.547"
+ height="600"
+ width="800"
+ transform="matrix(-0.5,0.8660254,-0.8660254,-0.5,1033.4024,539.36483)"
+ id="use3471"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.433"
+ height="600"
+ width="800"
+ transform="matrix(-0.8660254,0.5,-0.5,-0.8660254,957.63514,879.40243)"
+ id="use3473"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(-1,0,0,-1,721.99997,1136)"
+ id="use3475"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(-0.8660254,-0.5,0.5,-0.8660254,389.63514,1240.4024)"
+ id="use3477"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(-0.5,-0.8660254,0.8660254,-0.5,49.597541,1164.6351)"
+ id="use3479"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(0,-1,1,0,-207.00003,928.99993)"
+ id="use3481"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(0.5,-0.8660254,0.8660254,0.5,-311.40246,596.6351)"
+ id="use3483"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ <use
+ style="opacity:0.32"
+ height="600"
+ width="800"
+ transform="matrix(0.8660254,-0.5,0.5,0.8660254,-235.6352,256.5975)"
+ id="use3485"
+ xlink:href="#g3369"
+ y="0"
+ x="0" />
+ </g>
</g>
<g
inkscape:groupmode="layer"
diff --git a/src/tools/iostool/iostool.pro b/src/tools/iostool/iostool.pro
index f612833598b..a16bff04430 100644
--- a/src/tools/iostool/iostool.pro
+++ b/src/tools/iostool/iostool.pro
@@ -8,7 +8,7 @@ CONFIG += console
# Prevent from popping up in the dock when launched.
# We embed the Info.plist file, so the application doesn't need to
# be a bundle.
-QMAKE_LFLAGS += -sectcreate __TEXT __info_plist \"$$PWD/Info.plist\"
+QMAKE_LFLAGS += -Wl,-sectcreate,__TEXT,__info_plist,\"$$PWD/Info.plist\"
CONFIG -= app_bundle
LIBS += -framework CoreFoundation -framework CoreServices -framework IOKit -lssl -lbz2 -framework Security -framework SystemConfiguration
diff --git a/src/tools/tools.pro b/src/tools/tools.pro
index 218f3c7e9e1..bb82504d148 100644
--- a/src/tools/tools.pro
+++ b/src/tools/tools.pro
@@ -19,6 +19,14 @@ mac {
SUBDIRS += iostool
}
+BUILD_CPLUSPLUS_TOOLS = $$(BUILD_CPLUSPLUS_TOOLS)
+!isEmpty(BUILD_CPLUSPLUS_TOOLS) {
+ SUBDIRS += cplusplus-ast2png \
+ cplusplus-frontend \
+ cplusplus-mkvisitor \
+ cplusplus-update-frontend
+}
+
QT_BREAKPAD_ROOT_PATH = $$(QT_BREAKPAD_ROOT_PATH)
!isEmpty(QT_BREAKPAD_ROOT_PATH) {
SUBDIRS += qtcrashhandler
diff --git a/src/tools/tools.qbs b/src/tools/tools.qbs
index 0217e73d82a..faeb1cce12f 100644
--- a/src/tools/tools.qbs
+++ b/src/tools/tools.qbs
@@ -4,6 +4,7 @@ Project {
name: "Tools"
references: [
"buildoutputparser/buildoutputparser.qbs",
+ "cplusplustools.qbs",
"qtcdebugger/qtcdebugger.qbs",
"qtcreatorcrashhandler/qtcreatorcrashhandler.qbs",
"qtpromaker/qtpromaker.qbs",